delminio-client / kit / en / eseguibili-client
raw · sha256 d3334bb783c1d7ab4efe99760bc6eec01ea443d86ad94f89d894a6fc43a72a43
1#!/usr/bin/env python3
2# © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE.
3"""Gli eseguibili di Delminio su questa macchina, in pari col registro."""
4import argparse
5import base64
6import collections
7import datetime
8import difflib
9import hashlib
10import io
11import json
12import math
13import os
14import platform
15import re
16import runpy
17import shlex
18import shutil
19import socket
20import subprocess
21import sys
22import tarfile
23import tempfile
24import time
25import urllib.error
26import urllib.parse
27import urllib.request
28try:
29 import fcntl
30except ImportError:
31 fcntl = None
32RILASCI = 'https://downloads.claude.ai/claude-code-releases'
33CANALI = {'stabile': 'stable', 'latest': 'latest'}
34CODEX_RILASCI = 'https://releases.openai.com/codex/releases'
35CODEX_TARGET = {'linux-x64': 'x86_64-unknown-linux-musl', 'linux-x64-musl': 'x86_64-unknown-linux-musl', 'linux-arm64': 'aarch64-unknown-linux-musl', 'linux-arm64-musl': 'aarch64-unknown-linux-musl', 'darwin-x64': 'x86_64-apple-darwin', 'darwin-arm64': 'aarch64-apple-darwin'}
36NODE_QWEN = '22.23.4'
37CLI_NOMI = {'claude': 'Claude Code', 'codex': 'Codex', 'qwen': 'Qwen Code', 'opencode': 'OpenCode'}
38SERVER_RUOLO = 'memoria-ruolo'
39NODE_RILASCI = 'https://nodejs.org/dist'
40NODE_TARGET = {'linux-x64': 'linux-x64', 'linux-arm64': 'linux-arm64', 'darwin-x64': 'darwin-x64', 'darwin-arm64': 'darwin-arm64'}
41_VERSIONE = re.compile('^\\d+\\.\\d+\\.\\d+$')
42_NOME_OK = re.compile('[A-Za-z0-9][A-Za-z0-9._-]{0,63}')
43FRASI = {
44 "modello_gratuito_nessuno": "none of the {n} free OpenCode models answers right now: a provider's key is needed",
45 "modello_gratuito_risposta": "ready",
46 "modello_gratuito_domanda": "Answer only with the word: ready",
47 "modello_gratuito_uso": "usage: modello-gratuito <the opencode binary>",
48 "installa_agente_uso": "usage: installa-agente claude|codex|qwen|opencode <version>",
49 "installa_agente_no": "{cli} did not install: {errore}",
50 "skill_riferite": "\U0001f9e9 This machine's skills told to Delminio, with commands, agents and MCP servers: {n}; the Skills view choices applied: {scelte}.",
51 "posta_arrivata": "\U0001f4ec Delminio: a message has arrived from another session \u2014 you'll find it below.",
52 "riga_senza_numero": "the {cli} row doesn't have a version number yet: save it again in the Agents view",
53 "non_versione": "\u201c{versione}\u201d isn't a version",
54 "senza_cli_ufficiale": "this machine ({sistema}) has no official CLI: Linux or macOS (on Windows, inside WSL)",
55 "versione_assente": "version {versione} doesn't exist for {piattaforma}",
56 "scarico_cli": " downloading CLI {versione} for {piattaforma} ({mb} MB)\u2026",
57 "checksum_cli": "the checksum of CLI {versione} doesn't match: I won't install it",
58 "senza_codex_ufficiale": "this machine ({sistema}) has no official Codex: Linux or macOS (on Windows, inside WSL)",
59 "codex_senza_pacchetto": "Codex version {versione} has no package for {piattaforma}",
60 "scarico_codex": " downloading Codex {versione} for {piattaforma}\u2026",
61 "digest_codex": "the digest of Codex {versione} doesn't match: I won't install it",
62 "pacchetto_fuori": "the {chi} package reaches outside its folder: I won't install it",
63 "codex_senza_binario": "there's no bin/codex in the Codex {versione} package",
64 "senza_node_ufficiale": "this machine ({sistema}) has no official Node for Qwen Code: Linux or macOS with glibc (on Windows, inside WSL)",
65 "node_senza_pacchetto": "Node {versione} has no package for {piattaforma}",
66 "scarico_node": " downloading Node {versione} for Qwen Code\u2026",
67 "checksum_node": "the checksum of Node {versione} doesn't match: I won't install it",
68 "installo_qwen": " installing Qwen Code {versione}\u2026",
69 "installo_opencode": " installing OpenCode {versione}\u2026",
70 "opencode_integrita": "OpenCode {versione}: the package does not match the npm registry integrity, and is not installed",
71 "opencode_senza_binario": "the OpenCode {versione} package has no bin/opencode",
72 "opencode_solo_v2": "OpenCode {versione} is version 1, which Delminio no longer supports: choose a version 2 in the Agents view",
73 "wrapper_opencode_solo_kit": "\u26a0\ufe0f {nome}: an OpenCode agent starts from a project connected to Delminio, where its plugin brings memory, messages and the opening and closing commands.",
74 "commento_config_opencode": "The OpenCode configuration for this agent: provider and model, no self-updates. The client adds the role prompt at launch.",
75 "qwen_non_installato": "Qwen Code {versione} didn't install: {perche}",
76 "npm_muto": "npm silent",
77 "cosa_posta_ruolo": "the agent role's messages",
78 "settings_file": "\u26a0\ufe0f this row's --settings are a file: {cosa} doesn't fit in",
79 "cosa_ricerca_spenta": "web search switched off",
80 "rito_apertura_descrizione": "Opens the session with the user: Delminio brings you your role's steps",
81 "rito_apertura_corpo": "I'm opening the session.",
82 "rito_chiusura_descrizione": "Ends the session with the user: Delminio brings you your role's steps",
83 "rito_chiusura_corpo": "I'm ending the session.",
84 "rito_plugin": "/opening and /closing for agents with a Delminio agent role",
85 "rito_negato": "\u26a0\ufe0f Delminio didn't provide the text of /{parola}: {perche}. Tell the user.",
86 "rito_muto": "\u26a0\ufe0f Delminio is not responding: the text of /{parola} didn't arrive. Tell the user.",
87 "chiudi_commento": "At the end of the session: what you've written goes into your workspace's history, and to its\nrepository if it has one. Delminio writes it at every startup; it takes no arguments. If the workspace has its own prima-di-chiudere.sh, it runs that first.",
88 "chiudi_niente": "nothing new to put in the history",
89 "chiudi_nella_storia": "\u2705 in the history: {commit}",
90 "chiudi_senza_repo": "your workspace has no repository to send it to: the history stays here",
91 "chiudi_mandata": "\u2705 sent to its repository",
92 "chiudi_push_fallito": "\u26a0\ufe0f the push didn't go through, tell the user: {errore}",
93 "non_si_clona": "can't be cloned",
94 "pull_fallito": "the pull didn't go through",
95 "altri_file": "- \u2026 and {n} more files",
96 "repo_ruolo_lontano_nuova": "the agent role's repository ({repo}) can't be reached from here: the history stays in the workspace",
97 "repo_ruolo_cambiato": "the agent role's repository has changed: now {repo}",
98 "repo_ruolo_lontano": "the agent role's repository can't be reached from here: you're working on the previous workspace",
99 "casa_ferma": "the workspace doesn't update from its repository: you're working on the previous one",
100 "uso_casa": "usage: casa <the project's delminio.sh> <role> <agent> [<folder>]",
101 "casa_nel_progetto": "\u26a0\ufe0f {agente}: the isolated workspace can't be inside the project (or contain it): its real files are there. Change the agent's folder in the Agents view.",
102 "casa_non_detta": "\u26a0\ufe0f {agente}: Delminio didn't say where the workspace is ({errore}): you're working on the previous one.",
103 "casa_senza_repo": "\u26a0\ufe0f {agente}: Delminio didn't say which repositories the agent role sees ({errore}): the workspace isn't created.",
104 "novita_titolo": "What has changed",
105 "novita_uscito": "Your agent role doesn't see it any more: it has left the workspace.",
106 "novita_non_si_clona": "\u26a0\ufe0f It can't be cloned from this machine ({repo}): {perche}. Tell the user.",
107 "novita_copia_repo": "The copy was created just now: it's the repository as it is.",
108 "avviso_non_si_clona": "{repo} can't be cloned: {perche}",
109 "avviso_non_si_aggiorna": "{repo} doesn't update: {perche}",
110 "novita_non_si_aggiorna": "\u26a0\ufe0f It doesn't update ({perche}): you're working on the previous copy.",
111 "novita_niente": "Nothing new since last time.",
112 "novita_uscito_spazio": "(The repository \u201c{repo}\u201d no longer belongs to the space: it isn't copied.)",
113 "copia_progetto_ferma": "the project's copy doesn't update: {perche}",
114 "progetto_non_si_copia": "\u26a0\ufe0f {agente}: I can't copy the project into {casa}",
115 "novita_copia_progetto": "The copy was created just now: it's the project as it is, in the progetto/ folder.",
116 "novita_al_tecnico": "To tell the user",
117 "commento_al_lancio": "Before starting, the registry: if another version was chosen in the Agents view,\nthe command syncs now and restarts rewritten. If that fails, it starts as it was.",
118 "commento_prompt": "The system prompt from Delminio, in a file with the pid (which exec leaves to the CLI): those\nof CLIs already closed are deleted by the next startup. Without a prompt the agent doesn't start half-ready.",
119 "prompt_negato": "\u26a0\ufe0f {nome}: Delminio didn't provide the system prompt of the agent role \u201c{porta}\u201d (HTTP {codice}).",
120 "commento_hook_sistema": "The hooks read it: the rules are already at the top.",
121 "codex_ruolo_solo": "an agent role with only its own half isn't available on Codex yet: the role's memory goes through --mcp-config, which Codex doesn't have",
122 "wrapper_descrizione_serie": "a Delminio command",
123 "wrapper_commento": "Written by Delminio's \u201ceseguibili\u201d client from its register (Agents view):\nuntouched, it's rewritten at every sync; if you change it, it stays yours, and Delminio doesn't touch it any more.",
124 "commento_login_codex": "The login belongs to the person: that of their Codex, with a link (never a copy).",
125 "wrapper_senza_repo": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone.",
126 "fornitore_ignoto": "this Delminio doesn't know the Qwen Code provider \u201c{fornitore}\u201d",
127 "wrapper_senza_chiave": "\u26a0\ufe0f {nome}: the {fornitore} key is missing. Put it in your environment, as {variabile}=\u2026 (in the shell profile), and start it again.",
128 "commento_settings_qwen": "Qwen Code's settings for this agent: provider and model, and nothing that talks to Alibaba.",
129 "commento_mie_qwen": "The person's layer: ~/.config/delminio/mie-qwen.json and, for this agent only, mie.json in this folder, merged over the settings above at every start. Delminio never writes them; only the keys in QWEN_DI_DELMINIO stay Delminio's, and its options give way to the keys the layer writes.",
130 "mie_qwen_illeggibili": "\u26a0\ufe0f {file} is not valid JSON, and the agent starts with Delminio's settings only: {errore}",
131 "commento_mie_codex": "The person's layer: ~/.config/delminio/mie-codex.toml, merged at every start into the config.toml Delminio prepares for Codex. Delminio never writes it; only the keys in CODEX_DI_DELMINIO stay Delminio's, and its options give way to the keys the layer writes.",
132 "mie_di_delminio": "\u26a0\ufe0f {nome} stays Delminio's: in your settings it does not count, and the agent uses Delminio's.",
133 "mie_della_riga": "\u26a0\ufe0f {nome} is chosen by the agent (Agents view): in your settings it does not count.",
134 "mie_codex_illeggibili": "\u26a0\ufe0f {file} cannot be read as TOML, and the agent starts with Delminio's settings only: {errore}",
135 "mie_codex_casa_illeggibile": "\u26a0\ufe0f {file} cannot be read piece by piece: your settings do not go in this time, and the file stays as it is ({errore})",
136 "mie_codex_scontro": "\u26a0\ufe0f {file} clashes with the configuration Delminio prepares for Codex, and the agent starts without your settings: {errore}",
137 "mie_toml_chiave": "line {riga}: a key or a header is needed here",
138 "mie_toml_aperta": "line {riga}: a multi-line string that never closes",
139 "explore_descrizione": "Fast read-only agent for exploring codebases: finds files by pattern (eg. \"src/components/**/*.tsx\"), searches code for keywords (eg. \"API endpoints\") or answers questions about the code (eg. \"how do the endpoints work?\"). Say how thorough: \"quick\", \"medium\" or \"very thorough\".",
140 "explore_prompt": "You are a file search specialist agent: you explore codebases thoroughly.\n\nThis is a READ-ONLY task: you only have tools to find, search and read files. Do not try to create, modify, move or delete anything, and do not try to run commands.\n\nHow you work:\n- glob to find files by pattern\n- grep_search to search file contents with a regex\n- read_file when you know which file you need\n- adapt the search to the thoroughness you were asked for\n- whenever you can, run several searches and reads in parallel\n- file paths in your final answer are always absolute\n- write your report directly as a message, without emojis\n\nIn your final answer give the absolute paths of the files that matter for the task. Quote code only when the exact text matters (a bug you found, a function signature you were asked for): do not recap code you merely read.",
141 "commento_casa": "The isolated workspace: the repositories its agent role sees, up to date, and `consegne/` where it writes.",
142 "commento_autoupdater": "the version is decided by the register, not by the CLI",
143 "commento_catalogo_opencode": "the model list is the one built into OpenCode: no requests to models.opencode.ai",
144 "commento_token_progetto": "The token belongs to the project: it goes through the client of the connected repository you're in\n(a worktree doesn't have the client, which lives in the main clone).",
145 "wrapper_senza_repo_claude": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone, or open claude.",
146 "wrapper_altro_spazio": "\u26a0\ufe0f {nome}: it's an agent role of the space \u201c{spazio}\u201d, and this folder is connected to another space. Go into the clone of a project from that space.",
147 "spazio_principale": "main",
148 "pulizia": " clean-up: removed {n} versions ({tolte}), kept {tenute}{riparo}",
149 "potate": " versions nobody uses, deleted: {tolte}",
150 "errori_testa": "Tool calls that failed on this computer in the last {giorni} days: {n} (the log: {file})",
151 "errori_nascosti": " {n} are not errors (an Esc, a command that says no by design): --tutti shows them",
152 "errori_nessuno": " none.",
153 "errori_per_specie": "By kind:",
154 "errori_per_programma": "By tool and program:",
155 "errori_ultime": "The latest:",
156 "nessuna": "none",
157 "al_riparo": " (rollback version: {versione})",
158 "installo_chiesta": " the admin asks for {cli} on this machine: installing it",
159 "prova_strumento": "Counts the letters of a word.",
160 "prova_chiedi": "Use the conta_lettere tool on the word \u201cDelminio\u201d. Don't answer in words.",
161 "prova_regola": "Rule {i} of this test: answer briefly, in the language the user writes in, and don't make up what you don't know.",
162 "prova_senza_chiave": "the key is missing: put it in the environment as {variabile}=\u2026 and start again",
163 "prova_sistema": "You are an assistant that uses tools.",
164 "prova_chiave_rifiutata": "the provider rejects the key ({codice}): {testo}",
165 "prova_strumento_errore": "the request with the tool answers {codice}",
166 "prova_ok": "Reply only: ok.",
167 "prova_senza_strumento": "the model didn't call the tool: it can't work with Delminio",
168 "prova_contesto_stretto": "context of {contesto} tokens: tight",
169 "prova_cache_muta": "the provider doesn't say what it reads from the cache",
170 "aiuto_descrizione": "Delminio's commands on this machine, synced with the register.",
171 "aiuto_nomi": "for rinomina: the old and the new",
172 "aiuto_da": "for the space: the .claude/delminio.sh client of a connected project",
173 "aiuto_converti": "with --modo kit, also rewrites the wrappers written with `--modo casa`",
174 "aiuto_vuoi": "the CLI the person chose when connecting: it is installed even if it is not here",
175 "aiuto_primo": "a file to write the command of that CLI's first agent into, to launch it",
176 "nessun_agente_di": "There is no {cli} agent in this space yet: the administrator switches one on in the Agents view, with \u201cAdd agent\u201d, then the connection is run again.",
177 "aiuto_al_lancio": "sync: asked by the wrapper before starting \u2014 exits 0 if the registry is already the applied one, 3 if it synced and the command must be relaunched",
178 "servono_url_token": "--url and --token-file (or --da) are needed",
179 "rifiutati": "noted: Delminio's commands are no longer offered on this machine",
180 "lasciati": " this space's commands: {n} removed from this machine",
181 "registro_muto": "\u26a0\ufe0f the command register doesn't arrive from {url}: {errore}",
182 "nomi_fuori_forma": "\u26a0\ufe0f register rows with a malformed name, skipped: {nomi}",
183 "uso_prova": "prova NAME \u2014 the name of a Qwen Code agent in the register (Agents view)",
184 "prova_inizio_locale": "Test of {nome} ({modello}): three requests to the local server\u2026",
185 "prova_inizio_fornitore": "Test of {nome} ({modello}): three requests to the provider, a few cents\u2026",
186 "prova_non_fatta": "\u26a0\ufe0f the test didn't run: {errore}",
187 "prova_riga_strumenti": " tools: {valore}",
188 "prova_si": "yes",
189 "prova_no": "NO",
190 "prova_riga_cache": " cache: {valore}",
191 "prova_cache_non_detta": "the provider doesn't say",
192 "prova_cache_letti": "{letti} tokens read out of {totale}",
193 "prova_riga_contesto": " context: {valore}",
194 "prova_non_lo_dice": "doesn't say",
195 "prova_riga_verdetto": " verdict: {valore}{nota}",
196 "prova_va": "works",
197 "prova_senza_cache": "works, but without cache: every request is paid in full",
198 "prova_non_va": "doesn't work",
199 "verdetto_perso": "\u26a0\ufe0f the verdict didn't reach Delminio: {errore}",
200 "uso_rinomina": "rinomina OLD NEW",
201 "rinomina_assente": "\u274c \u201c{nome}\u201d isn't in the register",
202 "rinomina_rifiutata": "\u274c Delminio won't rename: {errore}",
203 "rinominato": "\u2705 \u201c{vecchio}\u201d is now called \u201c{nuovo}\u201d in the register: \u201callinea\u201d writes the new command and removes the old one on every machine",
204 "stato_assente": "missing",
205 "stato_cambiato": "changed by its user: it stays theirs",
206 "stato_non_suo": "present, but not Delminio's",
207 "stato_intatto": "untouched",
208 "stato_altro_spazio": "untouched, but it's the command of another space ({spazi})",
209 "stato_riga": "{nome}: CLI {versione}{da_scaricare} \xb7 {modello} \xb7 role {porta} \xb7 {stato}",
210 "da_scaricare": " (to download)",
211 "modello_di_serie": "default model",
212 "stato_rifiutato": "the user said they don't want them on this machine (allinea writes them anyway)",
213 "registro_vuoto": "the register is empty: no commands",
214 "allinea_in_corso": " another sync is in progress on this machine: I'll let it finish",
215 "al_lancio": "\u23f3 The Agents view has changed: updating the agent commands before starting\u2026",
216 "al_lancio_attesa": "\u23f3 a sync is already running on this machine: waiting for it to finish, then starting on the new version\u2026",
217 "senza_cli_qui": " {nome}: {cli} isn't on this machine, I won't download it",
218 "passo_controllo": "{nome}: checking {cli} {versione}",
219 "passo_scarico": "{nome}: downloading {cli} {versione}, {mb} MB",
220 "passo_di": " of {mb}",
221 "non_di_delminio": "\u274c {percorso} already exists and isn't Delminio's: choose another name in the Agents view.",
222 "toccato_resta": " {percorso}: changed by its user, it stays as it is",
223 "smista_testa": "agent of more than one space on this machine: the folder you launch it from decides the space",
224 "smista_fuori": "\u26a0\ufe0f {nome} is an agent of more than one space on this machine ({spazi}): launch it from the folder of a connected project, and the folder decides the space.",
225 "smista_non_qui": "\u26a0\ufe0f {nome} is not an agent of this folder's space: it belongs to {spazi}. Launch it from the folder of a project in one of those spaces.",
226 "smistato": "\U0001f500 {nome}: more than one space on this machine wants it, with different rows ({spazi}). The name stays one: the folder you launch it from decides the space.",
227 "scritto": "\u2705 {percorso}: written (CLI {versione})",
228 "aggiornato": "\u2705 {percorso}: updated, CLI {prima} \u2192 {versione}",
229 "rinfrescato": "\u267b\ufe0f {percorso}: regenerated with the same CLI {versione} ({righe} lines changed; the reason is in eseguibili-diario.log, next to the command registry)",
230 "passo_scritto": "{nome}: written, {cli} {versione}",
231 "lasciato_ad_altri": " {percorso}: this space lets it go, it stays for {spazi}",
232 "tolto": " {percorso}: removed, it's no longer in the register",
233 "fuori_dal_path": "\u26a0\ufe0f {cartella} isn't in the PATH: add export PATH=\"{cartella}:$PATH\" to the shell profile (~/.bashrc, ~/.zshrc), or run the commands with the full path.",
234 "wrapper_chiave_negata": "\u26a0\ufe0f {nome}: Delminio won't give me the key \u201c{scelta}\u201d chosen in the Agents view. The answer:",
235 "commento_chiave_dal_motore": "The provider key is chosen by the admin in the Agents view: it's requested from Delminio at every\nstart and stays only in this process's environment \u2014 never in a file, never in the shell profile.",
236 "commento_chiave_di_qwen": "The key given to Qwen Code at its first start, if the environment doesn't have it.",
237 "prova_chiave_negata": "Delminio won't give the key \u201c{scelta}\u201d chosen in the Agents view: {errore}",
238 "commento_progetto_di_riserva": "Started from outside a connected repository (its own folder, any folder): the repository of\nthis space from which the client last synced.",
239 "wrapper_casa_senza_repo": "\u26a0\ufe0f {nome}: I don't know yet which connected repository to take the key from. Start it once from inside a repository connected to this space: after that it starts from anywhere.",
240 "commento_plugin_codex": "Delminio's plugin in this agent's Codex folder: the hooks come from there.",
241 "posta_ruolo_rifiutata": "\u26a0\ufe0f Delminio refuses this agent role's token (HTTP {codice}): the other sessions' messages don't reach you. It retries at every message; this notice appears only once, tell the user.",
242 "porto_non_qui": "\U0001f4e6 \u201c{cartella}\u201d is not sent to the team: it is not a skill, a command or an agent inside the folders the CLIs read.",
243 "porto_troppo": "\U0001f4e6 \u201c{cartella}\u201d is too big for the team: at most {file} files and {peso} bytes of text.",
244 "porto_fatto": "\U0001f4e6 \u201c{nome}\u201d is in the team: from the next start every agent gets it.",
245 "porto_no": "\U0001f4e6 \u201c{cartella}\u201d stays out of the team: {errore}",
246 "squadra_muta": "\U0001f465 The team skills did not arrive ({errore}): the previous ones stay, and it retries at the next start.",
247 "squadra_qui": "\U0001f465 The team on this computer, in the \u201c{plugin}\u201d plugin: {skill} skills, {comandi} commands, {agenti} agents, {mcp} MCP servers.",
248 "squadra_plugin_qui": "\U0001f50c The team's plugins: {accettati} accepted on this computer \xb7 {fermi} waiting for your user's approval (delminio accept, from their own terminal).",
249 "riga_da_accettare": "\u23f8 {nome}: the registry gives it arguments or environment variables you haven't accepted on this computer yet. The previous command stays; from your own terminal: delminio accept",
250 "accetta_senza_terminale": "delminio accept runs from a terminal: an agent can't accept on your behalf.",
251 "accetta_riga_domanda": "\nThe agent \u201c{nome}\u201d ({cli}) of the space {spazio} would start with:\n arguments: {argomenti}\n environment: {ambiente}\n\nThey run on this computer, with your permissions, every time you launch it. Accept them? [y/N] ",
252 "accetta_si": "y yes s si s\xec",
253 "accetta_righe_esito": "\u2705 agents: {nuovi} accepted now \xb7 {restano} stay on hold (if one changes, I'll ask again). The commands are rewritten at the next start."
254}
255
256def F(chiave, **sost):
257 t = FRASI.get(chiave, chiave)
258 for k, v in sost.items():
259 t = t.replace('{' + k + '}', str(v))
260 return t
261
262def _esc(t):
263 return re.sub('([\\\\"$`])', '\\\\\\1', t)
264
265def _sh(t, **codice):
266 q = '"' + _esc(t) + '"'
267 for k, v in codice.items():
268 q = q.replace('{' + k + '}', v)
269 return q
270
271def _printf(t, **args):
272 ordine = sorted(((t.index('{' + k + '}'), k) for k in args if '{' + k + '}' in t))
273 fmt = _esc(t.replace('%', '%%'))
274 for k in args:
275 fmt = fmt.replace('{' + k + '}', '%s')
276 return f'printf "{fmt}\\n" ' + ' '.join((args[k] for _, k in ordine))
277
278def _commento(testo):
279 return ['# ' + r for r in testo.split('\n')]
280
281def _v(t):
282 return tuple((int(x) for x in t.split('.')))
283
284def _get(url, token=None, timeout=30, metodo='GET', corpo=None, nome=False):
285 h = {'Authorization': f'Bearer {token}'} if token else {}
286 if nome:
287 h['User-Agent'] = 'delminio-eseguibili'
288 dati = None
289 if corpo is not None:
290 dati, h['Content-Type'] = (json.dumps(corpo).encode(), 'application/json')
291 req = urllib.request.Request(url, data=dati, headers=h, method=metodo)
292 with urllib.request.urlopen(req, timeout=timeout) as r:
293 return r.read()
294
295def _scarica(url, timeout, su=None, nome=False):
296 h = {'User-Agent': 'delminio-eseguibili'} if nome else {}
297 with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r:
298 totale = int(r.headers.get('Content-Length') or 0)
299 pezzi, fatti, detti = ([], 0, 0)
300 while True:
301 pezzo = r.read(1 << 20)
302 if not pezzo:
303 break
304 pezzi.append(pezzo)
305 fatti += len(pezzo)
306 if su and fatti - detti >= 4 << 20:
307 detti = fatti
308 su(fatti, totale)
309 return b''.join(pezzi)
310
311def piattaforma():
312 s, m = (platform.system().lower(), platform.machine().lower())
313 arch = {'x86_64': 'x64', 'amd64': 'x64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(m)
314 if s not in ('linux', 'darwin') or not arch:
315 return None
316 p = f'{s}-{arch}'
317 if s == 'linux':
318 try:
319 ldd = subprocess.run(['ldd', '--version'], capture_output=True, text=True).stdout
320 ldd += subprocess.run(['ldd', '--version'], capture_output=True, text=True).stderr
321 except OSError:
322 ldd = ''
323 if 'musl' in ldd.lower() or any((f.startswith('ld-musl-') for f in os.listdir('/lib') if os.path.isdir('/lib'))):
324 p += '-musl'
325 return p
326
327def versione_voluta(riga, canali):
328 v = riga['versione']
329 if v in CANALI and _VERSIONE.match(str(riga.get('versione_oggi') or '')):
330 v = riga['versione_oggi']
331 if v in CANALI and riga.get('cli') != 'claude':
332 chi = CLI_NOMI.get(riga.get('cli'), riga.get('cli'))
333 raise RuntimeError(F('riga_senza_numero', cli=chi))
334 if v in CANALI:
335 if v not in canali:
336 canali[v] = _get(f'{RILASCI}/{CANALI[v]}', timeout=15).decode().strip()
337 v = canali[v]
338 if riga.get('minimo') and _VERSIONE.match(riga['minimo']) and _VERSIONE.match(v) and (_v(v) < _v(riga['minimo'])):
339 v = riga['minimo']
340 if not _VERSIONE.match(v):
341 raise RuntimeError(F('non_versione', versione=v))
342 return v
343
344def assicura_cli(versione, cartella, prova, su=None):
345 if prova:
346 return prova
347 dove = os.path.join(cartella, versione)
348 if os.path.isfile(dove) and os.access(dove, os.X_OK):
349 return dove
350 p = piattaforma()
351 if not p:
352 raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
353 manifesto = json.loads(_get(f'{RILASCI}/{versione}/manifest.json', timeout=20))
354 voce = (manifesto.get('platforms') or {}).get(p)
355 if not voce:
356 raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p))
357 print(F('scarico_cli', versione=versione, piattaforma=p, mb=voce.get('size', 0) // 1000000), flush=True)
358 dati = _scarica(f"{RILASCI}/{versione}/{p}/{voce.get('binary', 'claude')}", 600, su=su)
359 if hashlib.sha256(dati).hexdigest() != voce.get('checksum'):
360 raise RuntimeError(F('checksum_cli', versione=versione))
361 os.makedirs(cartella, exist_ok=True)
362 with open(dove + '.nuovo', 'wb') as f:
363 f.write(dati)
364 os.chmod(dove + '.nuovo', 493)
365 os.replace(dove + '.nuovo', dove)
366 return dove
367
368def assicura_codex(versione, cartella, prova, su=None):
369 if prova:
370 return prova
371 dove = os.path.join(cartella, versione)
372 binario = os.path.join(dove, 'bin', 'codex')
373 if os.path.isfile(binario) and os.access(binario, os.X_OK):
374 return binario
375 target = CODEX_TARGET.get(piattaforma() or '')
376 if not target:
377 raise RuntimeError(F('senza_codex_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
378 rilascio = json.loads(_get(f'{CODEX_RILASCI}/{versione}/release.json', timeout=20, nome=True))
379 nome = f'codex-package-{target}.tar.gz'
380 voce = next((x for x in rilascio.get('assets') or [] if x.get('name') == nome), None)
381 if not voce or not str(voce.get('digest') or '').startswith('sha256:'):
382 raise RuntimeError(F('codex_senza_pacchetto', versione=versione, piattaforma=target))
383 print(F('scarico_codex', versione=versione, piattaforma=target), flush=True)
384 dati = _scarica(f'{CODEX_RILASCI}/{versione}/{nome}', 600, su=su, nome=True)
385 if hashlib.sha256(dati).hexdigest() != voce['digest'].split(':', 1)[1]:
386 raise RuntimeError(F('digest_codex', versione=versione))
387 tappa = dove + '.nuovo'
388 shutil.rmtree(tappa, ignore_errors=True)
389 os.makedirs(cartella, exist_ok=True)
390 with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
391 for m in t.getmembers():
392 fuori = lambda x: x.startswith('/') or '..' in x.split('/')
393 if fuori(m.name) or m.islnk() or m.isdev() or (m.issym() and fuori(m.linkname)):
394 raise RuntimeError(F('pacchetto_fuori', chi=f'Codex {versione}'))
395 t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
396 if not os.path.isfile(os.path.join(tappa, 'bin', 'codex')):
397 shutil.rmtree(tappa, ignore_errors=True)
398 raise RuntimeError(F('codex_senza_binario', versione=versione))
399 for f in ('bin/codex', 'bin/codex-code-mode-host', 'codex-path/rg', 'codex-resources/bwrap'):
400 if os.path.isfile(os.path.join(tappa, f)):
401 os.chmod(os.path.join(tappa, f), 493)
402 shutil.rmtree(dove, ignore_errors=True)
403 os.replace(tappa, dove)
404 return binario
405
406def _estrai(dati, tappa, chi):
407 with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
408 for m in t.getmembers():
409 dentro = os.path.normpath(m.name)
410 if m.name.startswith('/') or dentro.startswith('..') or m.islnk() or m.isdev():
411 raise RuntimeError(F('pacchetto_fuori', chi=chi))
412 if m.issym():
413 dove = os.path.normpath(os.path.join(os.path.dirname(dentro), m.linkname))
414 if m.linkname.startswith('/') or dove.startswith('..'):
415 raise RuntimeError(F('pacchetto_fuori', chi=chi))
416 t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
417
418def node_di(versioni_qwen):
419 return os.path.join(os.path.dirname(os.path.normpath(versioni_qwen)), f'node-{NODE_QWEN}')
420
421def assicura_node(versioni_qwen, su=None):
422 dove = node_di(versioni_qwen)
423 if os.access(os.path.join(dove, 'bin', 'node'), os.X_OK):
424 return dove
425 target = NODE_TARGET.get(piattaforma() or '')
426 if not target:
427 raise RuntimeError(F('senza_node_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
428 nome = f'node-v{NODE_QWEN}-{target}'
429 somme = _get(f'{NODE_RILASCI}/v{NODE_QWEN}/SHASUMS256.txt', timeout=20).decode()
430 attesa = next((r.split()[0] for r in somme.splitlines() if r.endswith(f' {nome}.tar.gz')), '')
431 if not attesa:
432 raise RuntimeError(F('node_senza_pacchetto', versione=NODE_QWEN, piattaforma=target))
433 print(F('scarico_node', versione=NODE_QWEN), flush=True)
434 dati = _scarica(f'{NODE_RILASCI}/v{NODE_QWEN}/{nome}.tar.gz', 600, su=su)
435 if hashlib.sha256(dati).hexdigest() != attesa:
436 raise RuntimeError(F('checksum_node', versione=NODE_QWEN))
437 tappa = dove + '.nuovo'
438 shutil.rmtree(tappa, ignore_errors=True)
439 os.makedirs(tappa)
440 _estrai(dati, tappa, f'Node {NODE_QWEN}')
441 shutil.rmtree(dove, ignore_errors=True)
442 os.replace(os.path.join(tappa, nome), dove)
443 shutil.rmtree(tappa, ignore_errors=True)
444 return dove
445
446def assicura_qwen(versione, cartella, prova, su=None):
447 if prova:
448 return prova
449 dove = os.path.join(cartella, versione)
450 binario = os.path.join(dove, 'bin', 'qwen')
451 if os.path.isfile(binario):
452 return binario
453 node = assicura_node(cartella, su=su)
454 tappa = dove + '.nuovo'
455 shutil.rmtree(tappa, ignore_errors=True)
456 os.makedirs(cartella, exist_ok=True)
457 print(F('installo_qwen', versione=versione), flush=True)
458 env = {**os.environ, 'PATH': os.path.join(node, 'bin') + os.pathsep + os.environ.get('PATH', ''), 'npm_config_update_notifier': 'false', 'npm_config_fund': 'false', 'npm_config_audit': 'false'}
459 r = subprocess.run([os.path.join(node, 'bin', 'npm'), 'install', '-g', '--prefix', tappa, '--cache', os.path.join(os.path.dirname(os.path.normpath(cartella)), 'npm-cache'), '--ignore-scripts', '--no-fund', '--no-audit', f'@qwen-code/qwen-code@{versione}'], env=env, capture_output=True, text=True, timeout=900)
460 if r.returncode != 0 or not os.path.isfile(os.path.join(tappa, 'bin', 'qwen')):
461 shutil.rmtree(tappa, ignore_errors=True)
462 coda = (r.stderr or r.stdout or '').strip().splitlines()[-3:]
463 raise RuntimeError(F('qwen_non_installato', versione=versione, perche=' / '.join(coda) or F('npm_muto')))
464 shutil.rmtree(dove, ignore_errors=True)
465 os.replace(tappa, dove)
466 return binario
467OPENCODE_NPM = 'https://registry.npmjs.org'
468OPENCODE_PACCHETTO = '@opencode/cli-{p}'
469
470def assicura_opencode(versione, cartella, prova, su=None):
471 if prova:
472 return prova
473 if not opencode_v2(versione):
474 raise RuntimeError(F('opencode_solo_v2', versione=versione))
475 dove = os.path.join(cartella, versione)
476 binario = os.path.join(dove, 'bin', 'opencode')
477 if os.path.isfile(binario) and os.access(binario, os.X_OK):
478 return binario
479 p = piattaforma()
480 if not p:
481 raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
482 pacchetto = OPENCODE_PACCHETTO.format(p=p)
483 try:
484 meta = json.loads(_get(f"{OPENCODE_NPM}/{pacchetto.replace('/', '%2F')}/{versione}", timeout=20))
485 except Exception:
486 raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p)) from None
487 dist = meta.get('dist') or {}
488 integrity = str(dist.get('integrity') or '')
489 if not integrity.startswith('sha512-') or not dist.get('tarball'):
490 raise RuntimeError(F('opencode_integrita', versione=versione))
491 print(F('installo_opencode', versione=versione), flush=True)
492 dati = _scarica(dist['tarball'], 600, su=su)
493 if 'sha512-' + base64.b64encode(hashlib.sha512(dati).digest()).decode() != integrity:
494 raise RuntimeError(F('opencode_integrita', versione=versione))
495 tappa = dove + '.nuovo'
496 shutil.rmtree(tappa, ignore_errors=True)
497 os.makedirs(cartella, exist_ok=True)
498 _estrai(dati, tappa, f'OpenCode {versione}')
499 dentro = os.path.join(tappa, 'package', 'bin', 'opencode')
500 if not os.path.isfile(dentro):
501 shutil.rmtree(tappa, ignore_errors=True)
502 raise RuntimeError(F('opencode_senza_binario', versione=versione))
503 os.makedirs(os.path.join(tappa, 'bin'), exist_ok=True)
504 os.replace(dentro, os.path.join(tappa, 'bin', 'opencode'))
505 os.chmod(os.path.join(tappa, 'bin', 'opencode'), 493)
506 shutil.rmtree(os.path.join(tappa, 'package'), ignore_errors=True)
507 shutil.rmtree(dove, ignore_errors=True)
508 os.replace(tappa, dove)
509 return binario
510
511def _q(s):
512 return shlex.quote(str(s))
513
514def cli_qui(cli, versioni, versioni_codex, prova, versioni_qwen='', volute=(), versioni_opencode=''):
515 if prova:
516 return True
517 nome = cli if cli in CLI_NOMI else 'claude'
518 if shutil.which(nome) or cli in volute:
519 return True
520 cartella = {'codex': versioni_codex, 'qwen': versioni_qwen, 'opencode': versioni_opencode}.get(cli) or versioni
521 try:
522 return any((_VERSIONE.match(f) for f in os.listdir(cartella)))
523 except OSError:
524 return False
525
526def installa_agente(argv):
527 if len(argv) != 2 or argv[0] not in ('claude', 'codex', 'qwen', 'opencode'):
528 print(F('installa_agente_uso'), file=sys.stderr)
529 return 2
530 cli, versione = argv
531 prova = os.environ.get('DELMINIO_CLI_PROVA', '')
532 registro = os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
533 try:
534 v = versione if cli in ('qwen', 'opencode') else versione_voluta({'versione': versione, 'cli': cli}, {})
535 if not _VERSIONE.match(v):
536 raise RuntimeError(F('non_versione', versione=v))
537 if cli == 'claude':
538 binario = assicura_cli(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions'), prova)
539 elif cli == 'codex':
540 binario = assicura_codex(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions'), prova)
541 elif cli == 'qwen':
542 versioni_qwen = os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
543 binario = assicura_qwen(v, versioni_qwen, prova)
544 if not prova:
545 print('DELMINIO_NODE=' + os.path.join(node_di(versioni_qwen), 'bin'), flush=True)
546 else:
547 binario = assicura_opencode(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions'), prova)
548 except (RuntimeError, OSError, ValueError, urllib.error.URLError) as e:
549 print(F('installa_agente_no', cli=CLI_NOMI[cli], errore=e), file=sys.stderr)
550 return 1
551 mio = _leggi(registro)
552 mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {cli})
553 _scrivi(registro, mio)
554 print(binario)
555 return 0
556
557def modello_gratuito(argv):
558 if len(argv) != 1 or not os.access(argv[0], os.X_OK):
559 print(F('modello_gratuito_uso'), file=sys.stderr)
560 return 2
561 oc = argv[0]
562 try:
563 elenco = subprocess.run([oc, '--standalone', 'models'], capture_output=True, text=True, timeout=60).stdout
564 except (OSError, subprocess.TimeoutExpired):
565 elenco = ''
566 candidati = [r.strip() for r in elenco.splitlines() if r.strip().startswith('opencode/') and r.strip().endswith('-free')]
567 for m in candidati:
568 try:
569 r = subprocess.run([oc, '--standalone', 'run', '-m', m, F('modello_gratuito_domanda')], capture_output=True, text=True, timeout=90, cwd=tempfile.gettempdir())
570 except (OSError, subprocess.TimeoutExpired):
571 continue
572 if r.returncode == 0 and F('modello_gratuito_risposta').lower() in r.stdout.lower():
573 print(m)
574 return 0
575 print(F('modello_gratuito_nessuno', n=len(candidati)), file=sys.stderr)
576 return 1
577
578def personaggio(riga):
579 return bool(riga.get('porta')) and riga.get('nascita') == 'porta'
580
581def spazio_di(url, token):
582 u = url.rstrip('/')
583 try:
584 pezzo = token.split('.')[1]
585 cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
586 except (IndexError, ValueError, AttributeError):
587 cli = ''
588 k = u if cli in ('', 'unico') else f'{u}#{cli}'
589 return _ALIASI.get(k, k)
590_ALIASI = {}
591
592def _alias(mio, chiave, istanza):
593 if not istanza:
594 return chiave
595 for k, sp in list((mio.get('spazi') or {}).items()):
596 if k != chiave and sp.get('istanza') == istanza and (k not in (mio.get('alias') or {})):
597 mio.setdefault('alias', {})[chiave] = k
598 _ALIASI[chiave] = k
599 mio.get('spazi', {}).pop(chiave, None)
600 for chi in (mio.get('padroni') or {}).values():
601 if chiave in chi:
602 chi[:] = list(dict.fromkeys((k if c == chiave else c for c in chi)))
603 return k
604 return chiave
605
606def _istanza_di(url, token):
607 try:
608 return json.loads(_get(url.rstrip('/') + '/api/eseguibili', token, timeout=10)).get('istanza') or ''
609 except (OSError, ValueError, AttributeError, urllib.error.URLError):
610 return ''
611
612def nome_spazio(spazio):
613 return spazio.rsplit('#', 1)[1] if '#' in spazio else F('spazio_principale')
614
615def _token_di(token_file):
616 try:
617 with open(os.path.expanduser(token_file), encoding='utf-8') as f:
618 return f.read().strip()
619 except OSError:
620 return ''
621
622def canale_del_ruolo(spazio, porta):
623 spazio = hashlib.sha256(spazio.encode()).hexdigest()[:12]
624 chiave = re.sub('[^a-z0-9._-]+', '-', porta.lower()).strip('-') or 'ruolo'
625 return os.path.join(os.path.expanduser('~/.config/delminio/ruoli'), spazio, chiave + '.json')
626
627def progetto_dello_spazio(spazio):
628 return os.path.join(os.path.dirname(canale_del_ruolo(spazio, 'x')), 'progetto')
629
630def ricorda_il_progetto(spazio):
631 qui = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
632 try:
633 c = subprocess.run(['git', '-C', qui, 'rev-parse', '--path-format=absolute', '--git-common-dir'], capture_output=True, text=True, timeout=10)
634 if c.returncode == 0 and c.stdout.strip():
635 qui = os.path.dirname(c.stdout.strip())
636 except (OSError, subprocess.SubprocessError):
637 pass
638 if not os.access(os.path.join(qui, '.claude', 'delminio.sh'), os.X_OK):
639 return
640 f = progetto_dello_spazio(spazio)
641 try:
642 with open(f, encoding='utf-8') as fh:
643 if fh.read().strip() == qui:
644 return
645 except OSError:
646 pass
647 os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
648 tmp = f + '.nuovo'
649 with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as fh:
650 fh.write(qui + '\n')
651 os.replace(tmp, f)
652
653def _righe_del_repo(riga, spazio, avviso):
654 righe = ['r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi']
655 if (riga.get('scelte') or {}).get('casa') == 'separata' or riga.get('cartella'):
656 righe += [*_commento(F('commento_progetto_di_riserva')), 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', f' r=$(cat {_q(progetto_dello_spazio(spazio))} 2>/dev/null) || r=""', 'fi']
657 avviso = F('wrapper_casa_senza_repo', nome=riga['nome'])
658 return righe + ['if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' echo ' + _sh(avviso) + ' >&2', ' exit 1', 'fi']
659
660def assicura_canale(base_url, token, porta):
661 f = canale_del_ruolo(spazio_di(base_url, token), porta)
662 precedente, col_nome = ('', False)
663 if os.path.isfile(f):
664 try:
665 with open(f, encoding='utf-8') as h:
666 srv = json.load(h)['mcpServers']
667 col_nome = SERVER_RUOLO in srv
668 precedente = (srv.get(SERVER_RUOLO) or srv['delminio-ruolo'])['headers']['Authorization'].removeprefix('Bearer ')
669 except (ValueError, KeyError, TypeError, FileNotFoundError):
670 pass
671 d = json.loads(_get(base_url.rstrip('/') + '/api/porte/' + urllib.parse.quote(porta) + '/token', token, metodo='POST', corpo={'precedente': precedente}))
672 if precedente and d['token'] == precedente and col_nome:
673 return f
674 os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
675 conf = {'mcpServers': {SERVER_RUOLO: {'type': 'http', 'url': base_url.rstrip('/') + '/mcp', 'headers': {'Authorization': 'Bearer ' + d['token']}}}}
676 fd = os.open(f + '.nuovo', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
677 with os.fdopen(fd, 'w', encoding='utf-8') as h:
678 json.dump(conf, h)
679 os.replace(f + '.nuovo', f)
680 return f
681
682def ganci_della_posta(canale):
683
684 def cmd(momento):
685 return f'python3 "$DELMINIO_POSTA_CLIENT" posta-ruolo {_q(canale)} {momento}'
686 pulizia = {'type': 'command', 'command': 'python3 "$DELMINIO_POSTA_CLIENT" pulizia', 'timeout': 10}
687 return {'UserPromptSubmit': [{'hooks': [{'type': 'command', 'command': cmd('umano'), 'timeout': 30}]}], 'PostToolUse': [{'hooks': [{'type': 'command', 'command': cmd('volo'), 'timeout': 10}]}], 'Stop': [{'hooks': [{'type': 'command', 'command': cmd('attesa'), 'timeout': 43200, 'asyncRewake': True}, dict(pulizia)]}], 'SessionEnd': [{'hooks': [dict(pulizia)]}]}
688
689def con_i_ganci(args, ganci):
690 return con_le_impostazioni(args, {'hooks': ganci}, F('cosa_posta_ruolo'))
691
692def _unisci(s, extra):
693 for k, v in extra.items():
694 if isinstance(v, dict) and isinstance(s.get(k), dict):
695 _unisci(s[k], v)
696 elif isinstance(v, list) and isinstance(s.get(k), list):
697 s[k].extend((x for x in v if x not in s[k]))
698 else:
699 s.setdefault(k, v)
700
701def con_le_impostazioni(args, extra, cosa):
702 args = list(args)
703 for i, a in enumerate(args[:-1]):
704 if a == '--settings' and args[i + 1].lstrip().startswith('{'):
705 try:
706 s = json.loads(args[i + 1])
707 except ValueError:
708 break
709 _unisci(s, json.loads(json.dumps(extra)))
710 args[i + 1] = json.dumps(s, ensure_ascii=False, separators=(',', ':'))
711 return args
712 if '--settings' in args:
713 sys.stderr.write(F('settings_file', cosa=cosa) + '\n')
714 return args
715 return args + ['--settings', json.dumps(extra, ensure_ascii=False, separators=(',', ':'))]
716PERMESSI = {'claude': {'chiede': ['--permission-mode', 'manual'], 'modifiche': ['--permission-mode', 'acceptEdits'], 'classificatore': ['--permission-mode', 'auto']}, 'codex': {'chiede': ['-s', 'read-only', '-a', 'on-request'], 'modifiche': ['-s', 'workspace-write', '-a', 'on-request'], 'classificatore': ['--approve-for-me']}, 'qwen': {'chiede': ['--approval-mode', 'default'], 'modifiche': ['--approval-mode', 'auto-edit'], 'classificatore': ['--approval-mode', 'auto']}}
717
718def ambiente_della_riga(riga):
719 return {k: v for k, v in (riga.get('ambiente') or {}).items() if not str(k).startswith('DELMINIO_')}
720
721def lancio_delle_scelte(riga):
722 sc, cli = (riga.get('scelte') or {}, riga.get('cli') or 'claude')
723 args, env = (list(PERMESSI.get(cli, {}).get(sc.get('permessi'), [])), {})
724 if sc.get('conversazioni') in CONVERSAZIONI:
725 env['DELMINIO_CONVERSAZIONI'] = sc['conversazioni']
726 if cli == 'opencode':
727 return (args, env)
728 if cli == 'qwen':
729 if sc.get('ricerca_web') == 'spenta':
730 args += ['--exclude-tools', 'web_search', '--exclude-tools', 'web_fetch']
731 return (args, env)
732 if cli == 'codex':
733 if sc.get('ricerca_web') == 'spenta':
734 args += ['-c', 'web_search="disabled"']
735 if sc.get('telemetria') == 'spenta':
736 args += ['-c', 'analytics.enabled=false', '-c', 'feedback.enabled=false']
737 if sc.get('velocita') == 'fast':
738 args += ['-c', 'service_tier="fast"', '-c', 'features.fast_mode=true']
739 return (args, env)
740 if sc.get('ricerca_web') == 'spenta':
741 args = con_le_impostazioni(args, {'permissions': {'deny': ['WebSearch', 'WebFetch']}}, F('cosa_ricerca_spenta'))
742 if sc.get('telemetria') == 'spenta':
743 env.update({'DISABLE_TELEMETRY': '1', 'DISABLE_ERROR_REPORTING': '1', 'CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY': '1'})
744 if sc.get('classificatore'):
745 env['CLAUDE_CODE_AUTO_MODE_MODEL'] = sc['classificatore']
746 if sc.get('casa') == 'separata':
747 args += ['--restricted', '--allowedTools=Edit(consegne/**)']
748 return (args, env)
749
750def _pid_della_cli():
751 pid = os.getppid()
752 for _ in range(4):
753 try:
754 exe = os.path.basename(os.readlink(f'/proc/{pid}/exe'))
755 if _VERSIONE.match(exe) or exe == 'claude':
756 return pid
757 with open(f'/proc/{pid}/stat', encoding='utf-8') as f:
758 pid = int(f.read().rsplit(')', 1)[1].split()[1])
759 except (OSError, ValueError, IndexError):
760 break
761 return os.getppid()
762
763def _rito_del_ruolo():
764 return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'rito-del-ruolo')
765_SKILL_DEL_RITO = {'apertura': (F('rito_apertura_descrizione'), F('rito_apertura_corpo')), 'chiusura': (F('rito_chiusura_descrizione'), F('rito_chiusura_corpo'))}
766COMANDI = {
767 "riti": {
768 "apertura": "apertura",
769 "chiusura": "chiusura",
770 "closing": "chiusura",
771 "handoff": "chiusura",
772 "opening": "apertura",
773 "start": "apertura"
774 }
775}
776_SINONIMI_DEL_RITO = dict(COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'})
777_SKILL_DEL_RITO.update({nome: _SKILL_DEL_RITO[nostra] for nome, nostra in _SINONIMI_DEL_RITO.items()})
778
779def assicura_rito():
780 voluti = {os.path.join('.claude-plugin', 'plugin.json'): json.dumps({'name': 'delminio', 'description': F('rito_plugin')}, ensure_ascii=False, indent=2) + '\n'}
781 for nome, (descrizione, corpo) in _SKILL_DEL_RITO.items():
782 voluti[os.path.join('skills', nome, 'SKILL.md')] = f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\ndisable-model-invocation: true\n---\n{corpo} $ARGUMENTS\n'
783 for rel, testo in voluti.items():
784 p = os.path.join(_rito_del_ruolo(), rel)
785 try:
786 with open(p, encoding='utf-8') as f:
787 if f.read() == testo:
788 continue
789 except OSError:
790 pass
791 os.makedirs(os.path.dirname(p), exist_ok=True)
792 with open(p + '.nuovo', 'w', encoding='utf-8') as f:
793 f.write(testo)
794 os.replace(p + '.nuovo', p)
795 return _rito_del_ruolo()
796_NOMI_DEL_RITO = '|'.join((re.escape(n) for n in sorted(_SINONIMI_DEL_RITO, key=len, reverse=True)))
797_GESTO_DEL_RITO = re.compile('(?:/(?:delminio:)?(' + _NOMI_DEL_RITO + ')(?:\\s.*)?|(' + _NOMI_DEL_RITO + ')\\s*(?::.*)?)', re.I | re.S)
798
799def _rito_del_messaggio(base, token, radice, evento):
800 prima = (evento.get('prompt') or '').strip().split('\n', 1)[0].strip()
801 m = _GESTO_DEL_RITO.fullmatch(prima)
802 parola = (m.group(1) or m.group(2)).lower() if m else ''
803 parola = _SINONIMI_DEL_RITO.get(parola, parola)
804 segno = radice + '.aperta'
805 if not parola and os.path.exists(segno):
806 return ''
807 q = urllib.parse.urlencode({'parola': parola or 'apertura', 'da_se': '' if parola else '1'})
808 try:
809 testo = json.loads(_get(f'{base}/api/canale/ruolo/rito?{q}', token, timeout=15)).get('testo') or ''
810 open(segno, 'w').close()
811 return testo
812 except urllib.error.HTTPError as e:
813 if not parola:
814 return ''
815 try:
816 perche = json.loads(e.read()).get('error') or str(e)
817 except ValueError:
818 perche = str(e)
819 return F('rito_negato', parola=parola, perche=perche)
820 except (OSError, ValueError, urllib.error.URLError):
821 return F('rito_muto', parola=parola) if parola else ''
822CHIUDI_SH = '\n'.join(['#!/bin/bash', *_commento(F('chiudi_commento')), 'CASA="$(cd "$(dirname "$0")" && pwd)"\ncd "$CASA" || exit 1\n[ -f "$CASA/prima-di-chiudere.sh" ] && bash "$CASA/prima-di-chiudere.sh"\ngit add -A\nif git diff --cached --quiet; then', ' echo ' + _sh(F('chiudi_niente')), 'else\n file=$(git diff --cached --name-only | head -8 | tr \'\\n\' \' \')\n git commit -q -m "$(git config user.name): $(date \'+%d/%m %H:%M\') — $file" \\', ' && echo ' + _sh(F('chiudi_nella_storia', commit='{commit}'), commit="$(git log -1 --format='%h %s')"), 'fi\nif ! git remote get-url origin >/dev/null 2>&1; then', ' echo ' + _sh(F('chiudi_senza_repo')), 'elif out=$(git push -q origin HEAD 2>&1); then echo ' + _sh(F('chiudi_mandata')), 'else echo ' + _sh(F('chiudi_push_fallito', errore='{errore}'), errore='$out') + '; fi', ''])
823_IGNORATI_DELLA_CASA = ('/repo/', '/progetto/', '/NOVITA.md', '/.visto*')
824
825def _riga_exec(*pezzi):
826 return 'exec ' + ' '.join((p for p in pezzi if p))
827
828def _chiave_repo(remoto):
829 r = (remoto or '').strip()
830 if not r or r.startswith('locale:'):
831 return r
832 if '://' in r:
833 r = r.split('://', 1)[1]
834 autorita, separatore, percorso = r.partition('/')
835 r = autorita.rsplit('@', 1)[-1] + separatore + percorso
836 host, _, percorso = r.partition('/')
837 host = host.split(':', 1)[0]
838 elif ':' in r and (not r.startswith('/')):
839 host, _, percorso = r.partition(':')
840 host = host.split('@', 1)[-1]
841 else:
842 return r.rstrip('/').removesuffix('.git')
843 return f"{host.lower()}/{percorso.strip('/').removesuffix('.git').rstrip('/')}"
844
845def _git(*args, cwd=None):
846 env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'}
847 return subprocess.run(['git', *args], cwd=cwd, env=env, capture_output=True, text=True)
848
849def _origine(cartella):
850 o = _git('remote', 'get-url', 'origin', cwd=cartella).stdout.strip()
851 if o and os.path.isdir(o):
852 o = _git('remote', 'get-url', 'origin', cwd=o).stdout.strip() or o
853 return o
854
855def _https(remoto):
856 c = _chiave_repo(remoto)
857 return f'https://{c}.git' if '/' in c and '.' in c.split('/', 1)[0] else ''
858
859def _clona(remoto, progetto, dest, cartelle):
860 fonti = []
861 if progetto and _chiave_repo(_origine(progetto)) == _chiave_repo(remoto):
862 fonti.append(progetto)
863 fonti += [remoto] + ([_https(remoto)] if _https(remoto) else [])
864 ultimo = ''
865 for f in fonti:
866 r = _git('clone', '-q', '--no-checkout', f, dest)
867 if r.returncode == 0:
868 if cartelle:
869 _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
870 c = _git('checkout', '-q', cwd=dest)
871 if c.returncode == 0:
872 return ''
873 ultimo = c.stderr.strip()
874 else:
875 ultimo = r.stderr.strip()
876 shutil.rmtree(dest, ignore_errors=True)
877 return ultimo.splitlines()[-1] if ultimo else F('non_si_clona')
878
879def _aggiorna(dest, cartelle):
880 if cartelle:
881 _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
882 elif _git('config', 'core.sparseCheckout', cwd=dest).stdout.strip() == 'true':
883 _git('sparse-checkout', 'disable', cwd=dest)
884 r = _git('pull', '-q', '--ff-only', cwd=dest)
885 return '' if r.returncode == 0 else (r.stderr.strip().splitlines() or [F('pull_fallito')])[-1]
886
887def _testa(cartella):
888 return _git('rev-parse', 'HEAD', cwd=cartella).stdout.strip()
889
890def _uscito(cartella, prima, cartelle=(), quanti=40):
891 spec = [f":(exclude){c[1:].lstrip('/')}" if c.startswith('!') else c.lstrip('/') or '*' for c in cartelle]
892 file = _git('diff', '--name-only', f'{prima}..HEAD', '--', *spec, cwd=cartella).stdout.splitlines()
893 righe = [f'- {f}' for f in file[:quanti]]
894 if len(file) > quanti:
895 righe.append(F('altri_file', n=len(file) - quanti))
896 return righe
897
898def _la_casa_e_un_repo(casa, suo, agente):
899 avvisi = []
900 if not os.path.isdir(os.path.join(casa, '.git')):
901 vuota = not os.path.isdir(casa) or not os.listdir(casa)
902 if suo and vuota and (_git('clone', '-q', suo, casa).returncode == 0):
903 pass
904 else:
905 os.makedirs(casa, exist_ok=True)
906 _git('init', '-q', '-b', 'main', cwd=casa)
907 if suo:
908 _git('remote', 'add', 'origin', suo, cwd=casa)
909 if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
910 avvisi.append(F('repo_ruolo_lontano_nuova', repo=suo))
911 elif _git('rev-parse', '-q', '--verify', 'origin/main', cwd=casa).returncode == 0:
912 _git('checkout', '-q', '-B', 'main', 'origin/main', cwd=casa)
913 else:
914 ora = _git('remote', 'get-url', 'origin', cwd=casa).stdout.strip()
915 if suo and (not ora):
916 _git('remote', 'add', 'origin', suo, cwd=casa)
917 elif suo and _chiave_repo(ora) != _chiave_repo(suo):
918 _git('remote', 'set-url', 'origin', suo, cwd=casa)
919 avvisi.append(F('repo_ruolo_cambiato', repo=suo))
920 if suo or ora:
921 ramo = _git('rev-parse', '--abbrev-ref', 'HEAD', cwd=casa).stdout.strip() or 'main'
922 if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
923 avvisi.append(F('repo_ruolo_lontano'))
924 elif _git('rev-parse', '-q', '--verify', f'origin/{ramo}', cwd=casa).returncode == 0 and _git('merge', '-q', '--ff-only', f'origin/{ramo}', cwd=casa).returncode != 0:
925 avvisi.append(F('casa_ferma'))
926 if not _git('config', '--local', 'user.name', cwd=casa).stdout.strip():
927 _git('config', 'user.name', agente, cwd=casa)
928 _git('config', 'user.email', f'{agente}@ruoli.delminio', cwd=casa)
929 return avvisi
930
931def _scrivi_se_cambia(percorso, testo, modo=None):
932 try:
933 with open(percorso, encoding='utf-8') as f:
934 if f.read() == testo:
935 return
936 except OSError:
937 pass
938 with open(percorso + '.nuovo', 'w', encoding='utf-8') as f:
939 f.write(testo)
940 if modo:
941 os.chmod(percorso + '.nuovo', modo)
942 os.replace(percorso + '.nuovo', percorso)
943
944def casa(argv):
945 if len(argv) not in (3, 4):
946 sys.stderr.write(F('uso_casa') + '\n')
947 return 2
948 client, ruolo, agente = argv[:3]
949 url = token_file = ''
950 for riga in open(client, encoding='utf-8'):
951 k, _, v = riga.strip().partition('=')
952 if k == 'URL' and v:
953 url = (shlex.split(v) or [''])[0]
954 elif k == 'FILE_TOKEN' and v:
955 token_file = (shlex.split(v) or [''])[0]
956 token = _token_di(token_file)
957 progetto = os.path.dirname(os.path.dirname(os.path.abspath(client)))
958 spazio = spazio_di(url, token)
959 casa = os.path.abspath(os.path.expanduser(argv[3])) if len(argv) == 4 and argv[3] else os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'case', hashlib.sha256(spazio.encode()).hexdigest()[:12], agente)
960 vero = os.path.realpath(progetto)
961 if os.path.realpath(casa) == vero or os.path.realpath(casa).startswith(vero + os.sep) or vero.startswith(os.path.realpath(casa) + os.sep):
962 sys.stderr.write(F('casa_nel_progetto', agente=agente) + '\n')
963 return 1
964 try:
965 conf = json.loads(_get(f"{url.rstrip('/')}/api/porte/{urllib.parse.quote(ruolo)}/casa", token, timeout=15))
966 except (OSError, ValueError, urllib.error.URLError) as e:
967 if os.path.isdir(casa):
968 sys.stderr.write(F('casa_non_detta', agente=agente, errore=e) + '\n')
969 print(casa)
970 return 0
971 sys.stderr.write(F('casa_senza_repo', agente=agente, errore=e) + '\n')
972 return 1
973 avvisi = _la_casa_e_un_repo(casa, conf.get('suo') or '', agente)
974 if len(argv) == 3:
975 os.chmod(casa, 448)
976 os.makedirs(os.path.join(casa, 'consegne'), exist_ok=True)
977 scelti = {r['nome']: r for r in conf.get('repo') or []}
978 novita = ['# ' + F('novita_titolo'), '']
979 if scelti:
980 base = os.path.join(casa, 'repo')
981 os.makedirs(base, exist_ok=True)
982 shutil.rmtree(os.path.join(casa, 'progetto'), ignore_errors=True)
983 for d in sorted(os.listdir(base)):
984 if d not in scelti and os.path.isdir(os.path.join(base, d, '.git')):
985 shutil.rmtree(os.path.join(base, d), ignore_errors=True)
986 novita += [f'## repo/{d}', '', F('novita_uscito'), '']
987 for nome, r in scelti.items():
988 dest, cartelle = (os.path.join(base, nome), r.get('cartelle') or [])
989 if os.path.isdir(os.path.join(dest, '.git')) and _chiave_repo(_origine(dest)) != _chiave_repo(r['chiave']):
990 shutil.rmtree(dest, ignore_errors=True)
991 novita += [f'## repo/{nome}', '']
992 if not os.path.isdir(os.path.join(dest, '.git')):
993 perche = _clona(r['chiave'], progetto, dest, cartelle)
994 novita += [F('novita_non_si_clona', repo=r['chiave'], perche=perche) if perche else F('novita_copia_repo'), '']
995 if perche:
996 avvisi.append(F('avviso_non_si_clona', repo=f'repo/{nome}', perche=perche))
997 continue
998 prima = _testa(dest)
999 perche = _aggiorna(dest, cartelle)
1000 if perche:
1001 avvisi.append(F('avviso_non_si_aggiorna', repo=f'repo/{nome}', perche=perche))
1002 novita.append(F('novita_non_si_aggiorna', perche=perche))
1003 righe = _uscito(dest, prima, cartelle) if prima and prima != _testa(dest) else []
1004 novita += (righe or ([F('novita_niente')] if not perche else [])) + ['']
1005 for nome in conf.get('usciti') or []:
1006 novita += [F('novita_uscito_spazio', repo=nome), '']
1007 else:
1008 base = os.path.join(casa, 'repo')
1009 if os.path.isdir(base):
1010 shutil.rmtree(base, ignore_errors=True)
1011 dest = os.path.join(casa, 'progetto')
1012 if os.path.isdir(os.path.join(dest, '.git')):
1013 prima = _testa(dest)
1014 perche = _aggiorna(dest, [])
1015 if perche:
1016 avvisi.append(F('copia_progetto_ferma', perche=perche))
1017 righe = _uscito(dest, prima, quanti=60) if prima != _testa(dest) else []
1018 novita += righe or [F('novita_niente')]
1019 else:
1020 r = _git('clone', '-q', progetto, dest)
1021 if r.returncode != 0:
1022 sys.stderr.write(F('progetto_non_si_copia', agente=agente, casa=casa) + '\n')
1023 return 1
1024 novita.append(F('novita_copia_progetto'))
1025 if avvisi:
1026 novita += ['', '## ' + F('novita_al_tecnico'), ''] + [f'- {a}' for a in avvisi]
1027 _scrivi_se_cambia(os.path.join(casa, 'NOVITA.md'), '\n'.join(novita).rstrip() + '\n')
1028 _scrivi_se_cambia(os.path.join(casa, 'chiudi.sh'), CHIUDI_SH, 493)
1029 ignorati = os.path.join(casa, '.gitignore')
1030 try:
1031 ci_sono = open(ignorati, encoding='utf-8').read().splitlines()
1032 except OSError:
1033 ci_sono = []
1034 mancano = [x for x in _IGNORATI_DELLA_CASA if x not in ci_sono]
1035 if mancano:
1036 _scrivi_se_cambia(ignorati, '\n'.join(ci_sono + mancano).strip() + '\n')
1037 for a in avvisi:
1038 sys.stderr.write(f'⚠️ {agente}: {a}\n')
1039 print(casa)
1040 return 0
1041
1042def posta_ruolo(argv):
1043 if len(argv) != 2 or argv[1] not in ('umano', 'volo', 'attesa'):
1044 return 0
1045 canale, momento = argv
1046 try:
1047 with open(canale, encoding='utf-8') as f:
1048 srv = json.load(f)['mcpServers']
1049 srv = srv.get(SERVER_RUOLO) or srv['delminio-ruolo']
1050 base = srv['url'].rsplit('/mcp', 1)[0]
1051 token = srv['headers']['Authorization'].split(' ', 1)[1]
1052 except (OSError, ValueError, KeyError, IndexError):
1053 return 0
1054 evento = {}
1055 if not sys.stdin.isatty():
1056 try:
1057 evento = json.loads(sys.stdin.read() or '{}')
1058 except ValueError:
1059 pass
1060 if momento == 'volo' and evento.get('agent_id'):
1061 return 0
1062 cli = _pid_della_cli()
1063 sid = re.sub('[^A-Za-z0-9_-]', '', str(evento.get('session_id') or cli))[:64]
1064 stato = os.path.join(os.path.dirname(canale), 'posta')
1065 os.makedirs(stato, mode=448, exist_ok=True)
1066 radice = os.path.join(stato, os.path.splitext(os.path.basename(canale))[0] + '-' + sid)
1067 if momento == 'volo':
1068 try:
1069 if time.time() - os.path.getmtime(radice + '.volo') < 10:
1070 return 0
1071 except OSError:
1072 pass
1073 open(radice + '.volo', 'w').close()
1074
1075 def guarda(segna=True):
1076 with open(radice + '.lock', 'w') as lk:
1077 if fcntl is not None:
1078 fcntl.flock(lk, fcntl.LOCK_EX)
1079 try:
1080 with open(radice + '.visto', encoding='utf-8') as f:
1081 dopo = f.read().strip()
1082 except OSError:
1083 dopo = ''
1084 q = urllib.parse.urlencode({'dopo': dopo, 'momento': momento})
1085 try:
1086 r = json.loads(_get(f'{base}/api/canale/ruolo?{q}', token, timeout=10))
1087 except urllib.error.HTTPError as e:
1088 if segna and e.code in (401, 403) and (not os.path.exists(radice + '.rifiutato')):
1089 open(radice + '.rifiutato', 'w').close()
1090 return F('posta_ruolo_rifiutata', codice=e.code)
1091 return ''
1092 except (OSError, ValueError, urllib.error.URLError):
1093 return ''
1094 if os.path.exists(radice + '.rifiutato'):
1095 os.remove(radice + '.rifiutato')
1096 if segna and r.get('ultimo') and (r['ultimo'] != dopo):
1097 with open(radice + '.visto', 'w', encoding='utf-8') as f:
1098 f.write(r['ultimo'])
1099 if not segna and r.get('testo'):
1100 return r.get('ultimo') or ''
1101 return r.get('testo') or ''
1102 if momento != 'attesa':
1103 testo = guarda()
1104 if momento == 'umano':
1105 testo = '\n\n'.join((t for t in (_rito_del_messaggio(base, token, radice, evento), testo) if t))
1106 if testo:
1107 nome = 'UserPromptSubmit' if momento == 'umano' else 'PostToolUse'
1108 print(json.dumps({'hookSpecificOutput': {'hookEventName': nome, 'additionalContext': testo}}))
1109 return 0
1110 posta_qwen = os.environ.get('DELMINIO_QWEN_POSTA') or ''
1111 if posta_qwen:
1112 m = re.search('-(\\d+)\\.jsonl$', posta_qwen)
1113 if m:
1114 cli = int(m.group(1))
1115 if not os.path.isfile(posta_qwen) or os.fork():
1116 return 0
1117 os.setsid()
1118 nulla = os.open(os.devnull, os.O_RDWR)
1119 for fd in (0, 1, 2):
1120 os.dup2(nulla, fd)
1121 with open(radice + '.attesa', 'w', encoding='utf-8') as f:
1122 f.write(str(os.getpid()))
1123 giri = 0
1124 while True:
1125 testo = guarda(segna=not posta_qwen)
1126 if testo and posta_qwen:
1127 with open(radice + '.avviso.lock', 'w') as lk:
1128 if fcntl is not None:
1129 fcntl.flock(lk, fcntl.LOCK_EX)
1130 mia, gia = (False, '')
1131 try:
1132 with open(radice + '.attesa', encoding='utf-8') as f:
1133 mia = f.read().strip() == str(os.getpid())
1134 except OSError:
1135 pass
1136 try:
1137 with open(radice + '.avvisato', encoding='utf-8') as f:
1138 gia = f.read().strip()
1139 except OSError:
1140 pass
1141 if not mia:
1142 return 0
1143 if testo != gia:
1144 with open(posta_qwen, 'a', encoding='utf-8') as f:
1145 f.write(json.dumps({'type': 'submit', 'text': F('posta_arrivata')}, ensure_ascii=False) + '\n')
1146 with open(radice + '.avvisato', 'w', encoding='utf-8') as f:
1147 f.write(testo)
1148 return 0
1149 elif testo:
1150 sys.stderr.write(testo + '\n')
1151 return 2
1152 try:
1153 os.kill(cli, 0)
1154 with open(radice + '.attesa', encoding='utf-8') as f:
1155 if f.read().strip() != str(os.getpid()):
1156 return 0
1157 except (OSError, ValueError):
1158 return 0
1159 giri += 1
1160 time.sleep(3 if giri < 40 else 15 if giri < 80 else 30)
1161GIORNI_DOPO_UN_CRASH = 3
1162CONVERSAZIONI = ('subito', 'fine_sessione')
1163
1164def _pid_vivo(pid):
1165 try:
1166 os.kill(int(pid), 0)
1167 return True
1168 except ProcessLookupError:
1169 return False
1170 except (PermissionError, ValueError, TypeError, OverflowError):
1171 return True
1172
1173def _sessioni_vive(registro):
1174 vive = set()
1175 for f in glob_ordinato(os.path.join(registro, '*.json')):
1176 try:
1177 with open(f, encoding='utf-8') as h:
1178 d = json.load(h)
1179 if _pid_vivo(d.get('pid') or os.path.basename(f).split('.')[0]) and d.get('sessionId'):
1180 vive.add(str(d['sessionId']))
1181 except (OSError, ValueError, AttributeError):
1182 continue
1183 return vive
1184
1185def glob_ordinato(schema):
1186 import glob
1187 return sorted(glob.glob(schema))
1188
1189def _vecchia(percorsi, giorni):
1190 if giorni <= 0:
1191 return True
1192 soglia = time.time() - giorni * 86400
1193 for p in percorsi:
1194 try:
1195 if os.path.getmtime(p) >= soglia:
1196 return False
1197 except OSError:
1198 continue
1199 return True
1200
1201def _via(p):
1202 try:
1203 if os.path.isdir(p) and (not os.path.islink(p)):
1204 shutil.rmtree(p, ignore_errors=True)
1205 elif os.path.lexists(p):
1206 os.unlink(p)
1207 except OSError:
1208 pass
1209
1210def _ancora_dopo(percorsi, secondi=15):
1211 if not percorsi or os.fork():
1212 return
1213 try:
1214 os.setsid()
1215 nulla = os.open(os.devnull, os.O_RDWR)
1216 for fd in (0, 1, 2):
1217 os.dup2(nulla, fd)
1218 time.sleep(secondi)
1219 for p in percorsi:
1220 _via(p)
1221 finally:
1222 os._exit(0)
1223
1224def _da_togliere(sessioni, vive, mia, fine, subito, giorni):
1225 via = set()
1226 for sid, percorsi in sessioni.items():
1227 if sid == mia:
1228 if fine or subito:
1229 via.add(sid)
1230 continue
1231 if sid in vive:
1232 continue
1233 if _vecchia(percorsi, giorni):
1234 via.add(sid)
1235 return via
1236
1237def _pulisci_claude(evento, mia, fine, subito, giorni):
1238 casa = os.path.realpath(os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude'))
1239 progetti = os.path.join(casa, 'projects')
1240 trascritto = str(evento.get('transcript_path') or '')
1241 if trascritto:
1242 cartella = os.path.dirname(os.path.realpath(trascritto))
1243 else:
1244 dove = os.environ.get('CLAUDE_PROJECT_DIR') or str(evento.get('cwd') or '')
1245 if not dove:
1246 return
1247 cartella = os.path.join(progetti, re.sub('[^A-Za-z0-9]', '-', dove))
1248 if os.path.dirname(cartella) != progetti or not os.path.isdir(cartella):
1249 return
1250 sessioni = {}
1251 for nome in os.listdir(cartella):
1252 sid = nome[:-6] if nome.endswith('.jsonl') else nome
1253 if sid == 'memory' or not re.fullmatch('[0-9a-fA-F-]{8,}', sid):
1254 continue
1255 sessioni.setdefault(sid, []).append(os.path.join(cartella, nome))
1256 via = _da_togliere(sessioni, _sessioni_vive(os.path.join(casa, 'sessions')), mia, fine, subito, giorni)
1257 for sid in via:
1258 for p in sessioni[sid]:
1259 _via(p)
1260 for p in (os.path.join(casa, 'file-history', sid), os.path.join(casa, 'session-env', sid), os.path.join(casa, 'tasks', sid), *glob_ordinato(os.path.join(casa, 'todos', sid + '*'))):
1261 _via(p)
1262 if via:
1263 _togli_dalla_cronologia(os.path.join(casa, 'history.jsonl'), via)
1264 if fine and mia in via:
1265 _ancora_dopo([os.path.join(cartella, mia + '.jsonl'), os.path.join(cartella, mia)])
1266
1267def _togli_dalla_cronologia(f, via):
1268 try:
1269 with open(f, encoding='utf-8') as h:
1270 righe = h.readlines()
1271 except OSError:
1272 return
1273 tenute = []
1274 for r in righe:
1275 try:
1276 if str(json.loads(r).get('sessionId') or '') in via:
1277 continue
1278 except (ValueError, AttributeError):
1279 pass
1280 tenute.append(r)
1281 if len(tenute) == len(righe):
1282 return
1283 tmp = f + '.delminio'
1284 try:
1285 with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as h:
1286 h.writelines(tenute)
1287 os.replace(tmp, f)
1288 except OSError:
1289 _via(tmp)
1290
1291def _casa_delminio(var, sotto):
1292 h = os.environ.get(var)
1293 if not h:
1294 return None
1295 casa = os.path.realpath(h)
1296 base = os.path.realpath(os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', sotto))
1297 return casa if os.path.dirname(casa) == base and os.path.isdir(casa) else None
1298
1299def _pulisci_qwen(mia, fine, subito, giorni):
1300 casa = _casa_delminio('QWEN_HOME', 'qwen')
1301 if not casa:
1302 return
1303 eta, tutto = ({}, {})
1304 for p in glob_ordinato(os.path.join(casa, 'projects', '*', 'chats', '*')):
1305 sid = os.path.basename(p).split('.', 1)[0]
1306 eta.setdefault(sid, []).append(p)
1307 tutto.setdefault(sid, []).append(p)
1308 degli_agenti = {}
1309 for d in glob_ordinato(os.path.join(casa, 'projects', '*', 'subagents', '*')):
1310 sid = os.path.basename(d)
1311 tutto.setdefault(sid, []).append(d)
1312 degli_agenti.setdefault(sid, []).extend([d, *glob_ordinato(os.path.join(d, '*'))])
1313 for sid, percorsi in degli_agenti.items():
1314 eta.setdefault(sid, percorsi)
1315 for p in [*glob_ordinato(os.path.join(casa, 'file-history', '*')), *glob_ordinato(os.path.join(casa, 'tmp', '*', 'background-shells', '*'))]:
1316 tutto.setdefault(os.path.basename(p), []).append(p)
1317 for sid, percorsi in tutto.items():
1318 eta.setdefault(sid, percorsi)
1319 vive = _sessioni_vive(os.path.join(casa, 'sessions'))
1320 via = _da_togliere(eta, vive, mia, fine, subito, giorni)
1321 for sid in via:
1322 for p in tutto[sid]:
1323 _via(p)
1324 if fine and mia in via:
1325 _ancora_dopo(tutto[mia])
1326 for f in glob_ordinato(os.path.join(casa, 'sessions', '*.json')):
1327 if not _pid_vivo(os.path.basename(f).split('.')[0]):
1328 _via(f)
1329 if not vive - ({mia} if fine else set()):
1330 for d in glob_ordinato(os.path.join(casa, 'tmp', '*')):
1331 for x in ('logs.json', 'tool-results', 'checkpoints'):
1332 _via(os.path.join(d, x))
1333
1334def _pulisci_codex(mia, fine, giorni):
1335 casa = _casa_delminio('CODEX_HOME', 'codex')
1336 cli = os.environ.get('DELMINIO_CLI') or ''
1337 if not casa or os.path.basename(cli) != 'codex' or (not os.path.isfile(cli)):
1338 return
1339 stato = os.path.join(casa, 'delminio-pulizia')
1340 os.makedirs(stato, mode=448, exist_ok=True)
1341 if fine and re.fullmatch('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', mia):
1342 open(os.path.join(stato, mia + '.pending'), 'a').close()
1343 if not fine and giorni > 0:
1344 return
1345 env = {k: os.environ[k] for k in ('HOME', 'PATH', 'CODEX_HOME', 'DELMINIO_CLI', 'LANG', 'XDG_DATA_HOME', 'DELMINIO_CONVERSAZIONI') if k in os.environ}
1346 subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-codex', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
1347
1348def _codex_vivi(casa):
1349 for p in glob_ordinato('/proc/[0-9]*'):
1350 try:
1351 if os.path.basename(os.path.realpath(os.path.join(p, 'exe'))) != 'codex':
1352 continue
1353 with open(os.path.join(p, 'environ'), 'rb') as h:
1354 v = h.read().split(b'\x00')
1355 c = next((x.split(b'=', 1)[1] for x in v if x.startswith(b'CODEX_HOME=')), None)
1356 if c is None or os.path.realpath(os.fsdecode(c)) == casa:
1357 return True
1358 except FileNotFoundError:
1359 continue
1360 except OSError:
1361 return True
1362 return False
1363
1364def pulizia_codex(argv):
1365 import fcntl, sqlite3, uuid
1366 from contextlib import closing
1367 casa = _casa_delminio('CODEX_HOME', 'codex')
1368 cli = os.environ.get('DELMINIO_CLI') or ''
1369 if not casa or os.path.basename(cli) != 'codex':
1370 return 0
1371 giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
1372 stato = os.path.join(casa, 'delminio-pulizia')
1373 os.makedirs(stato, mode=448, exist_ok=True)
1374 with open(os.path.join(stato, 'lock'), 'w') as lk:
1375 try:
1376 fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
1377 except OSError:
1378 return 0
1379 while _codex_vivi(casa):
1380 time.sleep(3)
1381 via = {os.path.basename(p)[:-8] for p in glob_ordinato(os.path.join(stato, '*.pending'))}
1382 db = os.path.join(casa, 'state_5.sqlite')
1383 if os.path.isfile(db) and glob_ordinato(os.path.join(casa, 'state_*.sqlite')) == [db]:
1384 soglia = time.time() - giorni * 86400
1385 with closing(sqlite3.connect('file:' + db + '?mode=ro', uri=True)) as c:
1386 for sid, ultima in c.execute('SELECT id, updated_at FROM threads').fetchall():
1387 if isinstance(ultima, (int, float)) and 0 < ultima < soglia:
1388 via.add(str(sid))
1389 tolte = []
1390 for sid in sorted(via):
1391 try:
1392 sid = str(uuid.UUID(sid))
1393 except ValueError:
1394 continue
1395 if _codex_vivi(casa):
1396 return 0
1397 r = subprocess.run([cli, 'delete', '--force', sid], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=120)
1398 if r.returncode == 0:
1399 tolte.append(sid)
1400 _via(os.path.join(stato, sid + '.pending'))
1401 for s in glob_ordinato(os.path.join(casa, 'shell_snapshots', sid + '.*.sh')):
1402 _via(s)
1403 if tolte and (not _codex_vivi(casa)):
1404 for prefisso in ('state', 'thread_history', 'queue', 'logs', 'goals', 'memories'):
1405 for p in glob_ordinato(os.path.join(casa, prefisso + '_*.sqlite')):
1406 try:
1407 with closing(sqlite3.connect(p, timeout=5)) as c:
1408 if c.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]:
1409 continue
1410 c.execute('VACUUM')
1411 c.execute('PRAGMA wal_checkpoint(TRUNCATE)')
1412 except sqlite3.Error:
1413 continue
1414 return 0
1415_SESSIONE_OPENCODE = re.compile('ses_[A-Za-z0-9]{8,64}')
1416
1417def _segni_opencode():
1418 d = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'opencode', 'conversazioni')
1419 os.makedirs(d, mode=448, exist_ok=True)
1420 return d
1421
1422def _pulisci_opencode(mia, fine, giorni):
1423 cli = os.environ.get('DELMINIO_CLI') or ''
1424 if os.path.basename(cli) != 'opencode' or not os.path.isfile(cli) or (not _SESSIONE_OPENCODE.fullmatch(mia)):
1425 return
1426 stato = _segni_opencode()
1427 pid = os.environ.get('DELMINIO_CLI_PID') or str(os.getppid())
1428 with open(os.path.join(stato, mia + '.json'), 'w', encoding='utf-8') as h:
1429 json.dump({'pid': pid, 'cli': cli, 'linea': '2'}, h)
1430 if fine:
1431 open(os.path.join(stato, mia + '.fine'), 'a').close()
1432 env = {k: os.environ[k] for k in ('HOME', 'PATH', 'LANG', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME') if k in os.environ}
1433 subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-opencode', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
1434
1435def pulizia_opencode(argv):
1436 import fcntl
1437 giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
1438 stato = _segni_opencode()
1439 with open(os.path.join(stato, 'lock'), 'w') as lk:
1440 try:
1441 fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
1442 except OSError:
1443 return 0
1444 while True:
1445 segnate, attese = ({}, False)
1446 for f in glob_ordinato(os.path.join(stato, 'ses_*.json')):
1447 sid = os.path.basename(f)[:-5]
1448 try:
1449 with open(f, encoding='utf-8') as h:
1450 segnate[sid] = (json.load(h), f)
1451 except (OSError, ValueError):
1452 continue
1453 via = []
1454 for sid, (d, f) in segnate.items():
1455 finita = os.path.exists(os.path.join(stato, sid + '.fine'))
1456 if _pid_vivo(d.get('pid')):
1457 attese = attese or finita
1458 continue
1459 if finita or _vecchia([f], giorni):
1460 via.append((sid, d))
1461 for sid, d in via:
1462 cli = d.get('cli') if os.path.isfile(str(d.get('cli') or '')) else ''
1463 if d.get('linea') != '2':
1464 for x in ('.json', '.fine'):
1465 _via(os.path.join(stato, sid + x))
1466 continue
1467 if not cli:
1468 continue
1469 cmd = [cli, 'session', 'delete', sid, '--standalone']
1470 try:
1471 r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=120)
1472 except (OSError, subprocess.TimeoutExpired):
1473 continue
1474 if r.returncode == 0 or b'Session not found' in r.stdout + r.stderr:
1475 for x in ('.json', '.fine'):
1476 _via(os.path.join(stato, sid + x))
1477 if not attese:
1478 return 0
1479 time.sleep(3)
1480
1481def pulizia(argv):
1482 modo = os.environ.get('DELMINIO_CONVERSAZIONI') or ''
1483 if modo not in CONVERSAZIONI:
1484 return 0
1485 try:
1486 evento = json.loads(sys.stdin.read() or '{}') if not sys.stdin.isatty() else {}
1487 if not isinstance(evento, dict):
1488 evento = {}
1489 except ValueError:
1490 evento = {}
1491 fine = evento.get('hook_event_name') == 'SessionEnd' or argv[:1] == ['fine']
1492 mia = str(evento.get('session_id') or '')
1493 subito = modo == 'subito'
1494 giorni = 0 if subito else GIORNI_DOPO_UN_CRASH
1495 cli = os.environ.get('DELMINIO_CLI_NOME') or 'claude'
1496 try:
1497 if cli == 'qwen':
1498 _pulisci_qwen(mia, fine, subito, giorni)
1499 elif cli == 'codex':
1500 _pulisci_codex(mia, fine, giorni)
1501 elif cli == 'opencode':
1502 _pulisci_opencode(mia, fine, giorni)
1503 elif cli == 'claude':
1504 _pulisci_claude(evento, mia, fine, subito, giorni)
1505 except Exception:
1506 pass
1507 return 0
1508ERRORI_TETTO_BYTE = 2000000
1509ERRORI_RIGHE = 3
1510ERRORI_CARATTERI = 300
1511_USCITA = re.compile('^Exit code (\\d+)\\s*')
1512_DICE_NO = {'grep', 'egrep', 'fgrep', 'rg', 'diff', 'cmp', 'test', '[', '[['}
1513_SEGRETO = re.compile('(?i)\\b(token|password|passwd|secret|segreto|bearer|api[_-]?key|authorization)\\b(\\S*?)([=:]\\s*|\\s+)\\S+')
1514_LUNGO = re.compile('[A-Za-z0-9_\\-+=]{24,}')
1515_ESADECIMALE = re.compile('[0-9a-fA-F]{32,}')
1516ENTROPIA_DI_UNA_CHIAVE = 4.3
1517_FERMATO_CLI = re.compile('^blocked|isolated\\sin\\sthe\\sworktree|permission|denied|rejected')
1518_TEMPO = re.compile('timed\\sout|timeout')
1519
1520def _registro_errori():
1521 casa = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
1522 return os.path.join(casa, 'delminio', 'errori-strumenti.jsonl')
1523
1524def _entropia(s):
1525 return -sum((k / len(s) * math.log2(k / len(s)) for k in collections.Counter(s).values()))
1526
1527def _maschera(t):
1528 t = _SEGRETO.sub(lambda m: m.group(1) + m.group(2) + m.group(3) + '…', t)
1529 t = _ESADECIMALE.sub('…', t)
1530 return _LUNGO.sub(lambda m: '…' if _entropia(m.group(0)) > ENTROPIA_DI_UNA_CHIAVE else m.group(0), t)
1531
1532def _programma(comando):
1533 pezzi = [p for p in re.split('&&|\\|\\||;|\\||\\n', comando or '') if p.strip()]
1534 if not pezzi:
1535 return ''
1536 for parola in pezzi[-1].split():
1537 if re.match('^[A-Za-z_][A-Za-z0-9_]*=', parola) or parola in ('sudo', 'timeout', 'time', '!'):
1538 continue
1539 if re.fullmatch('\\d+[smh]?', parola):
1540 continue
1541 return os.path.basename(parola.strip('\'"()'))[:40]
1542 return ''
1543
1544def _specie(evento, programma, errore):
1545 if evento.get('is_interrupt'):
1546 return ('interrotto', True)
1547 m = _USCITA.match(errore)
1548 if m:
1549 resto = errore[m.end():].strip()
1550 if m.group(1) == '1' and (not resto or programma in _DICE_NO):
1551 return ('uscita_senza_errore', True)
1552 return ('uscita', False)
1553 basso = errore.lower()
1554 if '<tool_use_error>' in basso or 'inputvalidationerror' in basso:
1555 return ('tool', False)
1556 if 'delminio' in basso or '🔒' in errore:
1557 return ('fermato_da_delminio', False)
1558 if _FERMATO_CLI.search(basso):
1559 return ('fermato_dalla_cli', False)
1560 if _TEMPO.search(basso):
1561 return ('tempo', False)
1562 return ('altro', False)
1563
1564def errori_registra(_argv):
1565 try:
1566 evento = json.loads(sys.stdin.read() or '{}')
1567 tool = str(evento.get('tool_name') or '')[:60]
1568 entrata = evento.get('tool_input') or {}
1569 comando = entrata.get('command') if isinstance(entrata, dict) else ''
1570 programma = _programma(comando) if isinstance(comando, str) else ''
1571 errore = str(evento.get('error') or '').strip()
1572 specie, non_errore = _specie(evento, programma, errore)
1573 righe = [r for r in errore.splitlines() if r.strip()][:ERRORI_RIGHE]
1574 voce = {'quando': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), 'sessione': os.environ.get('DELMINIO_SESSIONE_NOME') or '', 'cli': 'claude', 'cartella': str(evento.get('cwd') or '')[:200], 'tool': tool, 'programma': programma, 'specie': specie, 'non_errore': non_errore, 'errore': _maschera(' ⏎ '.join(righe))[:ERRORI_CARATTERI], 'ms': evento.get('duration_ms')}
1575 dove = _registro_errori()
1576 os.makedirs(os.path.dirname(dove), mode=448, exist_ok=True)
1577 with open(dove, 'a', encoding='utf-8') as f:
1578 f.write(json.dumps(voce, ensure_ascii=False) + '\n')
1579 if os.path.getsize(dove) > ERRORI_TETTO_BYTE:
1580 with open(dove, encoding='utf-8', errors='replace') as f:
1581 tenute = f.readlines()
1582 tenute = tenute[len(tenute) // 2:]
1583 nuovo = dove + f'.{os.getpid()}.tmp'
1584 with open(nuovo, 'w', encoding='utf-8') as f:
1585 f.writelines(tenute)
1586 os.replace(nuovo, dove)
1587 except Exception:
1588 pass
1589 return 0
1590
1591def errori(argv):
1592 tutti = '--tutti' in argv or '--all' in argv
1593 numeri = [a for a in argv if a.isdigit()]
1594 giorni = int(numeri[0]) if numeri else 7
1595 dal = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=giorni)
1596 dove = _registro_errori()
1597 voci = []
1598 try:
1599 with open(dove, encoding='utf-8', errors='replace') as f:
1600 for r in f:
1601 try:
1602 v = json.loads(r)
1603 if datetime.datetime.fromisoformat(v['quando']) >= dal:
1604 voci.append(v)
1605 except (ValueError, KeyError, TypeError):
1606 continue
1607 except FileNotFoundError:
1608 pass
1609 nascoste = [v for v in voci if v.get('non_errore')]
1610 mostrate = voci if tutti else [v for v in voci if not v.get('non_errore')]
1611 print(F('errori_testa', giorni=giorni, n=len(mostrate), file=dove))
1612 if nascoste and (not tutti):
1613 print(F('errori_nascosti', n=len(nascoste)))
1614 if not mostrate:
1615 print(F('errori_nessuno'))
1616 return 0
1617 print(F('errori_per_specie'))
1618 for specie, n in collections.Counter((v.get('specie', '') for v in mostrate)).most_common():
1619 print(f' {n:4} {specie}')
1620 print(F('errori_per_programma'))
1621 for (tool, prog), n in collections.Counter(((v.get('tool', ''), v.get('programma', '')) for v in mostrate)).most_common(12):
1622 print(f" {n:4} {tool}{(' ' + prog if prog else '')}")
1623 print(F('errori_ultime'))
1624 for v in mostrate[-15:]:
1625 print(f" {v.get('quando', '')[:16].replace('T', ' ')} {v.get('sessione') or '—'} {v.get('tool', '')}{(' ' + v['programma'] if v.get('programma') else '')} · {v.get('specie', '')} · {v.get('errore', '')[:110]}")
1626 return 0
1627
1628def _righe_del_prompt(riga, url, token_file):
1629 nome, porta = (riga['nome'], riga.get('porta'))
1630 rotta = 'nascita' if riga.get('nascita') == 'intera' else 'sistema'
1631 return [*_commento(F('commento_prompt')), 'D="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-eseguibili"', 'mkdir -p "$D" && chmod 700 "$D"', f'for f in "$D"/{nome}-*.txt; do', ' [ -e "$f" ] || continue; p=${f##*-}; p=${p%.txt}', ' kill -0 "$p" 2>/dev/null || rm -f "$f"', 'done', f'F="$D/{nome}-$$.txt"', f"""codice=$( (umask 077; printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -G -o "$F" -w "%{{http_code}}" -K - --data-urlencode {_q('ordine=' + porta)} """ + (f"--data-urlencode {_q('modello=' + riga['ordine'])} " if riga.get('ordine') and rotta == 'nascita' else '') + f"{_q(url.rstrip('/') + '/api/porte/' + rotta)}) 2>/dev/null)", 'if [ "$codice" != 200 ] || [ ! -s "$F" ]; then', ' ' + _printf(F('prompt_negato', nome='{nome}', porta='{porta}', codice='{codice}'), nome=_q(nome), porta=_q(porta), codice='"${codice:-000}"') + ' >&2', ' [ -s "$F" ] && head -c 400 "$F" >&2 && echo >&2', ' rm -f "$F"; exit 1', 'fi', *_commento(F('commento_hook_sistema')), 'export DELMINIO_SISTEMA="$F"']
1632
1633def _righe_al_lancio(modo, url, token_file):
1634 if modo == 'kit':
1635 chi = [' q=${r:-$(git rev-parse --show-toplevel 2>/dev/null)}', ' if [ -n "$q" ] && [ -f "$q/.claude/eseguibili.py" ]; then', ' python3 "$q/.claude/eseguibili.py" allinea --al-lancio --modo kit --da "$q/.claude/delminio.sh" >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi', ' fi']
1636 else:
1637 chi = [f' python3 {_q(os.path.abspath(__file__))} allinea --al-lancio --modo casa --url {_q(url)} --token-file {_q(token_file)} >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi']
1638 return [*_commento(F('commento_al_lancio')), 'if [ -z "${DELMINIO_AL_LANCIO:-}" ]; then', *chi, 'fi', 'unset DELMINIO_AL_LANCIO']
1639
1640def _testa_del_wrapper(riga):
1641 chi = ' '.join(str(riga.get('descrizione') or F('wrapper_descrizione_serie')).split())
1642 return ['#!/bin/sh', f"# {riga['nome']} — {chi}", *_commento(F('wrapper_commento'))]
1643
1644def wrapper_codex(riga, cli, modo, url, token_file):
1645 nome, porta = (riga['nome'], riga.get('porta'))
1646 if personaggio(riga):
1647 raise RuntimeError(F('codex_ruolo_solo'))
1648 di_serie = [] if modo == 'kit' else ['--no-daemon', '-c', 'check_for_update_on_startup=false']
1649 della_riga = []
1650 if riga.get('modello'):
1651 della_riga += ['-m', riga['modello']]
1652 if riga.get('effort'):
1653 della_riga += ['-c', f'''model_reasoning_effort="{riga['effort']}"''']
1654 contesto = riga.get('_contesto') or {}
1655 espliciti = riga.get('argomenti') or []
1656 if contesto.get('massimo') and (not any((x.startswith('model_context_window=') for x in espliciti))):
1657 di_serie += ['-c', f"model_context_window={int(contesto['massimo'])}"]
1658 if contesto.get('compatta') and (not any((x.startswith('model_auto_compact_token_limit=') for x in espliciti))):
1659 di_serie += ['-c', f"model_auto_compact_token_limit={int(contesto['compatta'])}"]
1660 delle_scelte, env_scelte = lancio_delle_scelte(riga)
1661 della_riga += delle_scelte + list(riga.get('argomenti') or [])
1662 casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
1663 righe = [*_testa_del_wrapper(riga), f'export CODEX_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/codex/{casa}"', 'export DELMINIO_CLI_NOME=codex', f"export DELMINIO_PERMESSI={_q((riga.get('scelte') or {}).get('permessi') or '')}", f'export DELMINIO_CLI={_q(cli)}']
1664 if riga.get('ordine'):
1665 righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
1666 for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
1667 if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
1668 righe.append(f'export {k}={_q(v)}')
1669 righe += ['mkdir -p "$CODEX_HOME" && chmod 700 "$CODEX_HOME"', *_commento(F('commento_login_codex')), '[ -e "$CODEX_HOME/auth.json" ] || [ ! -f "$HOME/.codex/auth.json" ] || ln -s "$HOME/.codex/auth.json" "$CODEX_HOME/auth.json"']
1670
1671 def strato(client):
1672 return [*_commento(F('commento_mie_codex')), f'DELMINIO_MIE=$(python3 {client} mie-codex "$CODEX_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := chiavi_della_riga('codex', della_riga)) else '') + ') || DELMINIO_MIE=""', 'export DELMINIO_MIE', *righe_dello_strato('codex', di_serie, della_riga, 'DELMINIO_MIE')]
1673 if modo == 'kit' and porta:
1674 righe += [*_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
1675 righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
1676 if (tetto := (riga.get('_base') or {}).get('codex.tetto_uscite')):
1677 righe.append(f'export DELMINIO_TETTO_USCITE={int(tetto)}')
1678 righe += _righe_al_lancio(modo, url, token_file)
1679 righe += strato('"$r/.claude/eseguibili.py"')
1680 righe.append(_riga_exec('bash "$r/.claude/delminio.sh" codex', '"$@"'))
1681 return '\n'.join(righe) + '\n'
1682 if porta:
1683 righe += _righe_del_prompt(riga, url, token_file)
1684 righe.append(f'export DELMINIO_PORTA={_q(porta)}')
1685 if riga.get('cartella'):
1686 righe.append(f"cd {_q(riga['cartella'])} || exit 1")
1687 prompt = ' -c "model_instructions_file=\\"$F\\""' if porta else ''
1688 righe += _righe_al_lancio(modo, url, token_file)
1689 pacchetto = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugin.py')
1690 righe += [*_commento(F('commento_plugin_codex')), f'[ -n "${{DELMINIO_SENZA_PLUGIN:-}}" ] || DELMINIO_CODEX={_q(cli)} python3 {_q(pacchetto)} codex "$CODEX_HOME" >/dev/null 2>&1 || true']
1691 righe += strato(_q(os.path.abspath(__file__)))
1692 righe.append(_riga_exec(_q(cli), prompt.strip(), '"$@"'))
1693 return '\n'.join(righe) + '\n'
1694MIE_QWEN = 'mie-qwen.json'
1695MIE_CODEX = 'mie-codex.toml'
1696QWEN_DI_DELMINIO = ('hooks', 'general.enableAutoUpdate', 'mcpServers.delminio', 'mcpServers.memoria')
1697CODEX_DI_DELMINIO = (('hooks',), ('mcp_servers', 'delminio'), ('mcp_servers', 'memoria'), ('plugins', 'delminio@delminio'), ('marketplaces', 'delminio'), ('model_instructions_file',), ('check_for_update_on_startup',))
1698OPZIONI_CHIAVE = {'codex': {'-m': 'model', '--model': 'model', '-s': 'sandbox_mode', '--sandbox': 'sandbox_mode', '-a': 'approval_policy', '--ask-for-approval': 'approval_policy'}, 'qwen': {'-m': 'model.name', '--model': 'model.name', '--approval-mode': 'tools.approvalMode', '--exclude-tools': 'tools.exclude'}}
1699
1700def cartella_mie():
1701 return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio')
1702
1703def _percorsi_json(d, dove=()):
1704 for k, v in d.items():
1705 if isinstance(v, dict):
1706 yield from _percorsi_json(v, dove + (k,))
1707 else:
1708 yield (dove + (k,))
1709
1710def _stampa_chiavi(percorsi):
1711 print('|' + '|'.join(sorted({'.'.join(p) for p in percorsi})) + '|')
1712
1713def _della_riga(argomenti):
1714 if '--della-riga' in argomenti:
1715 i = argomenti.index('--della-riga')
1716 return (argomenti[:i] + argomenti[i + 2:], [tuple(k.split('.')) for k in argomenti[i + 1].split(',') if k])
1717 return (argomenti, [])
1718
1719def _sotto(percorso, chiavi):
1720 return any((percorso[:len(k)] == k for k in chiavi))
1721
1722def _sopra(percorso, chiavi):
1723 return [k for k in chiavi if len(k) > len(percorso) and k[:len(percorso)] == percorso]
1724
1725def unisci_mie_qwen(argomenti):
1726 argomenti, della_riga = _della_riga(argomenti)
1727 casa = argomenti[0]
1728 base = json.load(open(os.path.join(casa, 'settings.json'), encoding='utf-8'))
1729 scritte = []
1730 di_delminio = [tuple(x.split('.')) for x in QWEN_DI_DELMINIO]
1731
1732 def unisci(a, b, dove=''):
1733 for k, v in b.items():
1734 if dove + k in QWEN_DI_DELMINIO:
1735 print(F('mie_di_delminio', nome=dove + k), file=sys.stderr)
1736 continue
1737 percorso = tuple((dove + k).split('.'))
1738 if _sotto(percorso, della_riga):
1739 print(F('mie_della_riga', nome=dove + k), file=sys.stderr)
1740 continue
1741 dentro_d, dentro_r = (_sopra(percorso, di_delminio), _sopra(percorso, della_riga))
1742 if isinstance(v, dict) and (isinstance(a.get(k), dict) or dentro_d or dentro_r):
1743 if not isinstance(a.get(k), dict):
1744 a[k] = {}
1745 unisci(a[k], v, dove + k + '.')
1746 elif dentro_d or dentro_r:
1747 for x in dentro_d:
1748 print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
1749 for x in dentro_r:
1750 print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
1751 else:
1752 a[k] = v
1753 scritte.extend([percorso + p for p in _percorsi_json(v)] if isinstance(v, dict) else [percorso])
1754 for file in (os.path.join(cartella_mie(), MIE_QWEN), os.path.join(casa, 'mie.json')):
1755 if not os.path.isfile(file):
1756 continue
1757 try:
1758 mie = json.load(open(file, encoding='utf-8'))
1759 if not isinstance(mie, dict):
1760 raise ValueError(type(mie).__name__)
1761 except (OSError, ValueError) as e:
1762 print(F('mie_qwen_illeggibili', file=file, errore=e), file=sys.stderr)
1763 continue
1764 unisci(base, mie)
1765 with open(os.path.join(casa, 'settings.json'), 'w', encoding='utf-8') as h:
1766 json.dump(base, h, indent=2, ensure_ascii=False)
1767 _stampa_chiavi(scritte)
1768 return 0
1769
1770def _toml_chiave(s, i):
1771 parti = []
1772 while True:
1773 while i < len(s) and s[i] in ' \t':
1774 i += 1
1775 if i < len(s) and s[i] in '"\'':
1776 q, j = (s[i], i + 1)
1777 while j < len(s) and s[j] != q and (s[j] != '\n'):
1778 j += 2 if q == '"' and s[j] == '\\' else 1
1779 nome = s[i + 1:j]
1780 if q == '"':
1781 try:
1782 nome = json.loads('"' + nome + '"')
1783 except ValueError:
1784 pass
1785 parti.append(nome)
1786 i = j + 1
1787 else:
1788 j = i
1789 while j < len(s) and (s[j].isalnum() or s[j] in '_-'):
1790 j += 1
1791 if j == i:
1792 raise ValueError(F('mie_toml_chiave', riga=s.count('\n', 0, i) + 1))
1793 parti.append(s[i:j])
1794 i = j
1795 while i < len(s) and s[i] in ' \t':
1796 i += 1
1797 if s[i:i + 1] != '.':
1798 return (tuple(parti), i)
1799 i += 1
1800
1801def _toml_fine_valore(s, i):
1802 profondo = 0
1803 while i < len(s):
1804 if s.startswith('"""', i) or s.startswith("'''", i):
1805 q, j = (s[i:i + 3], i + 3)
1806 while True:
1807 k = s.find(q, j)
1808 if k < 0:
1809 raise ValueError(F('mie_toml_aperta', riga=s.count('\n', 0, i) + 1))
1810 barre = len(s[:k]) - len(s[:k].rstrip('\\'))
1811 if q == '"""' and barre % 2:
1812 j = k + 1
1813 continue
1814 i = k + 3
1815 while s[i:i + 1] == q[0]:
1816 i += 1
1817 break
1818 continue
1819 c = s[i]
1820 if c in '"\'':
1821 j = i + 1
1822 while j < len(s) and s[j] != c and (s[j] != '\n'):
1823 j += 2 if c == '"' and s[j] == '\\' else 1
1824 i = j + 1
1825 continue
1826 if c == '#':
1827 k = s.find('\n', i)
1828 i = len(s) if k < 0 else k
1829 continue
1830 if c in '[{':
1831 profondo += 1
1832 elif c in ']}':
1833 profondo -= 1
1834 elif c == '\n' and profondo <= 0:
1835 return i + 1
1836 i += 1
1837 return i
1838
1839def toml_pezzi(testo):
1840 pezzi, i, tabella = ([], 0, ())
1841 while i < len(testo):
1842 j = i
1843 while j < len(testo) and testo[j] in ' \t\r':
1844 j += 1
1845 if j >= len(testo) or testo[j] in '\n#':
1846 k = testo.find('\n', j)
1847 fine = len(testo) if k < 0 else k + 1
1848 pezzi.append(('altro', None, testo[i:fine]))
1849 i = fine
1850 continue
1851 if testo[j] == '[':
1852 lista = testo.startswith('[[', j)
1853 percorso, k = _toml_chiave(testo, j + (2 if lista else 1))
1854 if not testo.startswith(']]' if lista else ']', k):
1855 raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
1856 k = testo.find('\n', k)
1857 fine = len(testo) if k < 0 else k + 1
1858 tabella = percorso
1859 pezzi.append(('lista' if lista else 'tabella', percorso, testo[i:fine]))
1860 i = fine
1861 continue
1862 percorso, k = _toml_chiave(testo, j)
1863 if testo[k:k + 1] != '=':
1864 raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
1865 fine = _toml_fine_valore(testo, k + 1)
1866 pezzi.append(('chiave', tabella + percorso, testo[i:fine]))
1867 i = fine
1868 return pezzi
1869
1870def _toml_parti(pezzi):
1871 cima, sezioni = ([], [])
1872 for p in pezzi:
1873 if p[0] in ('tabella', 'lista'):
1874 sezioni.append([p])
1875 elif sezioni:
1876 sezioni[-1].append(p)
1877 else:
1878 cima.append(p)
1879 return (cima, sezioni)
1880
1881def _di_delminio_codex(percorso):
1882 return any((percorso[:len(r)] == r for r in CODEX_DI_DELMINIO))
1883SEGNO_MIE = '# delminio-strato:' + MIE_CODEX
1884SEGNO_DA_PARTE = '# delminio-strato:da-parte'
1885SEGNO_FINE = '# delminio-strato:fine'
1886_TRATTO = re.compile('(?ms)^(' + re.escape(SEGNO_MIE) + '|' + re.escape(SEGNO_DA_PARTE) + ')[^\\n]*\\n(.*?)^' + re.escape(SEGNO_FINE) + '[^\\n]*\\n?')
1887
1888def _unito(pezzi):
1889 t = ''.join((p[2] for p in pezzi))
1890 return t if not t or t.endswith('\n') else t + '\n'
1891
1892def _tratto(segno, testo, prefisso=''):
1893 if not testo.strip():
1894 return ''
1895 return segno + '\n' + ''.join((prefisso + r for r in testo.splitlines(keepends=True))) + SEGNO_FINE + '\n'
1896
1897def _casa_codex(testo):
1898 da_parte = []
1899
1900 def via(m):
1901 if m.group(1) == SEGNO_DA_PARTE:
1902 da_parte.extend((r[3:] if r.startswith('#= ') else r[2:] if r.startswith('#=') else '' for r in m.group(2).splitlines(keepends=True)))
1903 return ''
1904 cima, sezioni = _toml_parti(toml_pezzi(_TRATTO.sub(via, testo)))
1905 try:
1906 cima_p, sezioni_p = _toml_parti(toml_pezzi(''.join(da_parte)))
1907 except ValueError:
1908 cima_p, sezioni_p = ([], [])
1909 chiavi = {p[1] for p in cima + [x for s in sezioni for x in s] if p[0] == 'chiave'}
1910 cima += [p for p in cima_p if p[0] == 'chiave' and p[1] not in chiavi]
1911 for s in sezioni_p:
1912 torna = [p for p in s[1:] if p[0] != 'chiave' or p[1] not in chiavi]
1913 gemella = next((x for x in sezioni if x[0][0] == 'tabella' and x[0][1] == s[0][1]), None)
1914 if gemella is None:
1915 sezioni.append([s[0]] + torna)
1916 else:
1917 gemella.extend((p for p in torna if p[0] == 'chiave'))
1918 return (cima, sezioni)
1919
1920def unisci_mie_codex(argomenti):
1921 argomenti, della_riga = _della_riga(argomenti)
1922 casa = argomenti[0]
1923 conf, file = (os.path.join(casa, 'config.toml'), os.path.join(cartella_mie(), MIE_CODEX))
1924 try:
1925 with open(conf, encoding='utf-8') as h:
1926 testo = h.read()
1927 except FileNotFoundError:
1928 testo = ''
1929 try:
1930 cima_r, sezioni_r = _casa_codex(testo)
1931 except ValueError as e:
1932 print(F('mie_codex_casa_illeggibile', file=conf, errore=e), file=sys.stderr)
1933 _stampa_chiavi([])
1934 return 0
1935 senza = _unito(cima_r) + _unito([p for s in sezioni_r for p in s])
1936 nuovo, scritte = (senza, [])
1937 pezzi = None
1938 if os.path.isfile(file):
1939 try:
1940 with open(file, encoding='utf-8') as h:
1941 pezzi = toml_pezzi(h.read())
1942 except (OSError, ValueError, UnicodeDecodeError) as e:
1943 print(F('mie_codex_illeggibili', file=file, errore=e), file=sys.stderr)
1944 if pezzi:
1945 cima_m, sezioni_m = _toml_parti(pezzi)
1946
1947 def fuori(percorso):
1948 return _di_delminio_codex(percorso) or _sotto(percorso, della_riga)
1949
1950 def fuori_c(percorso):
1951 return fuori(percorso) or bool(_sopra(percorso, CODEX_DI_DELMINIO) or _sopra(percorso, della_riga))
1952
1953 def dillo(percorso):
1954 if fuori(percorso):
1955 print(F('mie_di_delminio' if _di_delminio_codex(percorso) else 'mie_della_riga', nome='.'.join(percorso)), file=sys.stderr)
1956 return
1957 for x in _sopra(percorso, CODEX_DI_DELMINIO):
1958 print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
1959 for x in _sopra(percorso, della_riga):
1960 print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
1961 for p in [p for p in cima_m if p[0] == 'chiave' and fuori_c(p[1])] + [s[0] for s in sezioni_m if fuori(s[0][1])] + [p for s in sezioni_m if not fuori(s[0][1]) for p in s[1:] if p[0] == 'chiave' and fuori_c(p[1])]:
1962 dillo(p[1])
1963 cima_m = [p for p in cima_m if not (p[0] == 'chiave' and fuori_c(p[1]))]
1964 sezioni_m = [[p for p in s if not (p[0] == 'chiave' and fuori_c(p[1]))] for s in sezioni_m if not fuori(s[0][1])]
1965 scritte = [p[1] for p in cima_m + [x for s in sezioni_m for x in s] if p[0] == 'chiave']
1966 tabelle_m = {s[0][1] for s in sezioni_m if s[0][0] == 'tabella'}
1967 coppie_m = set(scritte) | tabelle_m
1968
1969 def coperta(p):
1970 return p[0] == 'chiave' and (p[1] in coppie_m or any((p[1][:len(t)] == t for t in tabelle_m)))
1971 fuori = [p for p in cima_r if coperta(p)]
1972 cima_r = [p for p in cima_r if not coperta(p)]
1973 dentro, fuori_sezioni = ([], [])
1974 for s in sezioni_r:
1975 if s[0][0] == 'tabella' and s[0][1] in tabelle_m:
1976 fuori_sezioni.append(s)
1977 elif s[0][0] == 'lista':
1978 dentro.append(s)
1979 else:
1980 dentro.append([s[0]] + [p for p in s[1:] if not coperta(p)])
1981 if any((coperta(p) for p in s[1:])):
1982 fuori_sezioni.append([s[0]] + [p for p in s[1:] if coperta(p)])
1983 fuori += [p for s in sorted(fuori_sezioni, key=lambda s: s[0][1]) for p in s]
1984 nuovo = _tratto(SEGNO_MIE + ':chiavi', _unito(cima_m)) + _unito(cima_r) + _tratto(SEGNO_MIE + ':tabelle', _unito([p for s in sezioni_m for p in s])) + _unito([p for s in dentro for p in s]) + _tratto(SEGNO_DA_PARTE, _unito(fuori), '#= ')
1985 try:
1986 import tomllib
1987 except ImportError:
1988 tomllib = None
1989 if tomllib:
1990 try:
1991 tomllib.loads(nuovo)
1992 except tomllib.TOMLDecodeError as e:
1993 print(F('mie_codex_scontro', file=file, errore=e), file=sys.stderr)
1994 nuovo, scritte = (senza, [])
1995 if nuovo != testo:
1996 os.makedirs(casa, exist_ok=True)
1997 with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
1998 h.write(nuovo)
1999 os.chmod(conf + '.nuovo', 384)
2000 os.replace(conf + '.nuovo', conf)
2001 _stampa_chiavi(scritte)
2002 return 0
2003
2004def opzioni_dello_strato(cli, args):
2005 gruppi, i, chiavi = ([], 0, OPZIONI_CHIAVE.get(cli, {}))
2006 while i < len(args):
2007 a = args[i]
2008 nome, _, valore = a.partition('=')
2009 if cli == 'codex' and a in ('-c', '--config') and (i + 1 < len(args)):
2010 gruppi.append((args[i + 1].split('=', 1)[0].strip(), args[i:i + 2]))
2011 i += 2
2012 elif nome in chiavi and valore:
2013 gruppi.append((chiavi[nome], [a]))
2014 i += 1
2015 elif a in chiavi and i + 1 < len(args):
2016 gruppi.append((chiavi[a], args[i:i + 2]))
2017 i += 2
2018 else:
2019 gruppi.append((None, [a]))
2020 i += 1
2021 return gruppi
2022
2023def chiavi_della_riga(cli, della_riga):
2024 return ','.join(sorted({k for k, _ in opzioni_dello_strato(cli, della_riga) if k}))
2025
2026def righe_dello_strato(cli, di_serie, della_riga, variabile):
2027 righe = ['set -- ' + ' '.join((_q(a) for a in della_riga)) + ' "$@"'] if della_riga else []
2028 for chiave, gruppo in reversed(opzioni_dello_strato(cli, di_serie)):
2029 metti = 'set -- ' + ' '.join((_q(a) for a in gruppo)) + ' "$@"'
2030 if not chiave:
2031 righe.append(metti)
2032 continue
2033 parti = chiave.split('.')
2034 casi = '|'.join(('*"|' + '.'.join(parti[:n]) + '|"*' for n in range(1, len(parti) + 1)))
2035 righe.append(f'case "${{{variabile}:-}}" in {casi}) ;; *) {metti} ;; esac')
2036 return righe
2037
2038def chiave_qwen(riga):
2039 tipo = (riga.get('fornitore') or {}).get('tipo')
2040 fisso = ((riga.get('_fornitori') or {}).get(tipo) or {}).get('chiave')
2041 return fisso if fisso else re.sub('[^A-Z0-9]+', '_', riga['nome'].upper()).strip('_') + '_API_KEY'
2042
2043def impostazioni_qwen(riga):
2044 f = riga.get('fornitore') or {}
2045 info = (riga.get('_fornitori') or {}).get(f.get('tipo')) or {}
2046 if not info:
2047 raise RuntimeError(F('fornitore_ignoto', fornitore=f.get('tipo') or ''))
2048 spente = {} if (riga.get('scelte') or {}).get('telemetria') == 'accesa' else {'privacy': {'usageStatisticsEnabled': False}, 'telemetry': {'enabled': False}}
2049 auth, modello = (info['auth'], riga.get('modello') or '')
2050 indirizzo = f.get('indirizzo') or info.get('indirizzo') or ''
2051 fa = info.get('formato_anthropic') or {}
2052 if fa.get('prefisso') and modello.startswith(fa['prefisso']):
2053 auth, indirizzo = ('anthropic', fa['indirizzo'])
2054 contesto = int(f.get('contesto') or 0)
2055 memoria = (riga.get('scelte') or {}).get('memoria') == 'accesa'
2056 base = riga.get('_base') or {}
2057 attesa = int(base.get('qwen.prima_parola_ms') or QWEN_PRIMA_PAROLA_MS)
2058 generazione = {'timeout': attesa, 'streamIdleTimeoutMs': attesa, **({'contextWindowSize': contesto} if contesto else {})}
2059 compatta, voluto = ({}, int(f.get('compatta') or 0))
2060 finestra = contesto or (1000000 if auth == 'anthropic' and QWEN_CLAUDE_1M.search(modello) else 0)
2061 if finestra:
2062 soglia = min(1.0, voluto / finestra) if voluto else min(0.85, int(base.get('qwen.compatta') or QWEN_SOGLIA) / finestra)
2063 if voluto or soglia < 0.85:
2064 generazione['contextWindowSize'] = finestra
2065 compatta = {'context': {'autoCompactThreshold': round(soglia, 3)}}
2066 if info.get('auth') == 'anthropic':
2067 generazione['cacheRetention'] = '1h'
2068 fornitori = {auth: [{'id': modello, 'name': modello, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo} if indirizzo else {}), **({'generationConfig': generazione} if generazione else {})}]}
2069 veloce, extra = ((riga.get('scelte') or {}).get('classificatore') or '', {})
2070 if veloce and veloce != modello:
2071 auth_v, indirizzo_v = (info['auth'], f.get('indirizzo') or info.get('indirizzo') or '')
2072 if fa.get('prefisso') and veloce.startswith(fa['prefisso']):
2073 auth_v, indirizzo_v = ('anthropic', fa['indirizzo'])
2074 fornitori.setdefault(auth_v, []).append({'id': veloce, 'name': veloce, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo_v} if indirizzo_v else {})})
2075 extra = {'fastModel': veloce if auth_v == auth else f'{auth_v}:{veloce}'}
2076 return {'modelProviders': fornitori, **extra, 'security': {'auth': {'selectedType': auth}}, 'model': {'name': modello}, **spente, **compatta, 'memory': {'enableManagedAutoMemory': memoria, 'enableManagedAutoDream': memoria, 'enableAutoSkill': False, 'enableTeamMemory': False}, 'general': {'enableAutoUpdate': False}, 'ui': {'enableFollowupSuggestions': False, 'showToolCallDetails': False}, 'tools': {'approvalMode': 'default', 'toolSearch': {'enabled': False}}, 'permissions': {'deny': list(QWEN_TOOL_FUORI + (QWEN_TOOL_LARGHI if 0 < contesto < 65536 else ())), 'ask': list(QWEN_CHIEDI)}, 'review': {**QWEN_REVIEW, **({'effort': base['qwen.review']} if base.get('qwen.review') else {})}, 'skills': skill_qwen(riga.get('_skill'))}
2077
2078def della_riga_qwen(riga):
2079 sc, f = (riga.get('scelte') or {}, riga.get('fornitore') or {})
2080 chiavi = ['modelProviders', 'model.name', 'security.auth']
2081 if sc.get('classificatore'):
2082 chiavi.append('fastModel')
2083 if sc.get('telemetria'):
2084 chiavi += ['privacy.usageStatisticsEnabled', 'telemetry.enabled']
2085 if sc.get('memoria'):
2086 chiavi += ['memory.enableManagedAutoMemory', 'memory.enableManagedAutoDream']
2087 if f.get('compatta'):
2088 chiavi.append('context.autoCompactThreshold')
2089 if any(((x or {}).get('cli') == 'qwen' for x in riga.get('_skill') or [])):
2090 chiavi.append('skills')
2091 return ','.join(chiavi)
2092
2093def skill_qwen(scelte):
2094 spente, a_scelta = (list(QWEN_SKILL_SPENTE), list(QWEN_SKILL_A_SCELTA))
2095 for x in scelte or []:
2096 nome = (x or {}).get('nome')
2097 if (x or {}).get('cli') != 'qwen' or not nome:
2098 continue
2099 if x.get('stato') == 'accesa':
2100 spente = [n for n in spente if n != nome]
2101 a_scelta = [n for n in a_scelta if n != nome]
2102 elif x.get('stato') == 'spenta' and nome not in spente and (nome not in a_scelta):
2103 a_scelta.append(nome)
2104 return {'disabled': spente, 'defaultDisabled': a_scelta}
2105QWEN_TOOL_FUORI = ('artifact', 'autofix_pr', 'cron_create', 'cron_delete', 'cron_list', 'display_image', 'enter_worktree', 'exit_worktree', 'get_goal', 'list_agents', 'loop_wakeup', 'monitor', 'propose_goal', 'read_mcp_resource', 'record_artifact', 'report_findings', 'send_message', 'update_goal', 'zoom_image')
2106QWEN_TOOL_LARGHI = ('agent', 'enter_plan_mode', 'exit_plan_mode')
2107QWEN_SKILL_ACCESE = ('agent-delegation', 'batch', 'dataviz', 'extension-creator', 'new-app', 'review', 'simplify', 'stuck', 'zvec-grep-install')
2108QWEN_SKILL_A_SCELTA = ()
2109QWEN_SKILL_SPENTE = ('auto-memory', 'autofix-pr', 'batch-api', 'coordinate', 'goal-draft', 'loop', 'qc-helper', 'workflow-authoring', 'workflow-creator')
2110QWEN_CHIEDI = ('agent', 'workflow')
2111QWEN_REVIEW = {'effort': 'low'}
2112QWEN_SOGLIA = 300000
2113QWEN_PRIMA_PAROLA_MS = 60000
2114QWEN_CLAUDE_1M = re.compile('claude-(opus|sonnet|fable)-(5|4-[6-9])')
2115
2116def explore_qwen():
2117 return '\n'.join(['---', 'name: Explore', 'description: ' + json.dumps(F('explore_descrizione'), ensure_ascii=False), 'tools:', ' - read_file', ' - grep_search', ' - glob', '---', '', F('explore_prompt')])
2118
2119def _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file):
2120 out = []
2121 if (scelta := (riga.get('fornitore') or {}).get('chiave')):
2122 if dal_repo:
2123 leggi = 'python3 -c \'import shlex, sys\nfor l in open(sys.argv[1], encoding="utf-8"):\n k, _, x = l.strip().partition("=")\n if k == sys.argv[2] and x:\n print((shlex.split(x) or [""])[0])\n break\' "$r/.claude/delminio.sh"'
2124 out += [f'T=$({leggi} FILE_TOKEN 2>/dev/null)', f'U=$({leggi} URL 2>/dev/null)']
2125 dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$T")" | curl -sS -m 30 -K - "${{U%/}}"/api/eseguibili/{_q(urllib.parse.quote(nome))}/chiave"""
2126 else:
2127 dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -K - {_q(url.rstrip('/') + '/api/eseguibili/' + urllib.parse.quote(nome) + '/chiave')}"""
2128 out += [*_commento(F('commento_chiave_dal_motore')), f'''K=$( ({dal_motore.replace('curl -sS', 'curl -sSf', 1)}) 2>/dev/null) || K=""''', 'if [ -z "$K" ]; then', ' echo ' + _sh(F('wrapper_chiave_negata', nome=nome, scelta=scelta)) + ' >&2', f' ({dal_motore}) 2>&1 | head -c 400 >&2; echo >&2', ' exit 1', 'fi', f'export {chiave}="$K"', 'unset K' + (' T U' if dal_repo else '')]
2129 elif tipo == 'casa':
2130 out.append(f'[ -n "${{{chiave}:-}}" ] || export {chiave}=nessuna')
2131 else:
2132 leggi = f"""python3 -c 'import json, os, sys\ntry:\n e = json.load(open(os.path.expanduser("~/.qwen/settings.json"), encoding="utf-8")).get("env") or {{}}\n print(e.get(sys.argv[1]) or "")\nexcept (OSError, ValueError, AttributeError):\n pass' {chiave}"""
2133 out += [f'if [ -z "${{{chiave}:-}}" ]; then', *_commento(F('commento_chiave_di_qwen')), f' {chiave}=$({leggi} 2>/dev/null) || {chiave}=""', f' [ -n "${chiave}" ] && export {chiave}', 'fi', f'if [ -z "${{{chiave}:-}}" ]; then', ' echo ' + _sh(F('wrapper_senza_chiave', nome=nome, fornitore=riga['_fornitori'][tipo]['nome'], variabile=chiave)) + ' >&2', ' exit 1', 'fi']
2134 return out
2135
2136def wrapper_qwen(riga, cli, modo, url, token_file):
2137 nome, porta = (riga['nome'], riga.get('porta'))
2138 impostazioni = impostazioni_qwen(riga)
2139 canale = canale_del_ruolo(spazio_di(url, _token_di(token_file)), porta) if personaggio(riga) else ''
2140 if canale:
2141 impostazioni['hooks'] = ganci_della_posta(canale)
2142 for g in impostazioni['hooks']['Stop'][0]['hooks']:
2143 g.pop('asyncRewake', None)
2144 g['timeout'] = 10
2145 tipo = (riga.get('fornitore') or {}).get('tipo')
2146 chiave = chiave_qwen(riga)
2147 delle_scelte, env_scelte = lancio_delle_scelte(riga)
2148 fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
2149 casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
2150 node = os.path.join(node_di(os.path.dirname(os.path.dirname(os.path.dirname(cli)))), 'bin')
2151 righe = [*_testa_del_wrapper(riga), f'export QWEN_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/qwen/{casa}-{nome}"', 'export DELMINIO_CLI_NOME=qwen', 'export QWEN_CODE_MODELS_DEV=off', 'export QWEN_CODE_DISABLE_ARTIFACT=1', 'export QWEN_CODE_LEGACY_MCP_BLOCKING=1', *([f"export DELMINIO_CONTESTO={int((riga.get('fornitore') or {}).get('contesto') or 0)}"] if int((riga.get('fornitore') or {}).get('contesto') or 0) > 0 else []), f'export PATH={_q(node)}:"$PATH"', f'export DELMINIO_CLI={_q(cli)}']
2152 if riga.get('ordine'):
2153 righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
2154 for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
2155 if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
2156 righe.append(f'export {k}={_q(v)}')
2157 dal_repo = modo == 'kit' and bool(porta)
2158 if dal_repo:
2159 righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
2160 righe += _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file)
2161 righe += ['mkdir -p "$QWEN_HOME" && chmod 700 "$QWEN_HOME"', *_commento(F('commento_settings_qwen')), 'cat > "$QWEN_HOME/settings.json" <<\'IMPOSTAZIONI\'', json.dumps(impostazioni, indent=2, ensure_ascii=False), 'IMPOSTAZIONI', *_commento(F('commento_mie_qwen')), 'python3 ' + ('"$r/.claude/eseguibili.py"' if dal_repo else _q(os.path.abspath(__file__))) + ' mie-qwen "$QWEN_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := ','.join((x for x in (della_riga_qwen(riga), chiavi_della_riga('qwen', delle_scelte + list(riga.get('argomenti') or []))) if x))) else '') + ' >/dev/null', 'mkdir -p "$QWEN_HOME/agents"', 'cat > "$QWEN_HOME/agents/Explore.md" <<\'EXPLORE\'', explore_qwen(), 'EXPLORE']
2162 if canale:
2163 righe.append('mkdir -p "$QWEN_HOME/commands"')
2164 for gesto, (descrizione, _corpo) in _SKILL_DEL_RITO.items():
2165 righe += [f"""cat > "$QWEN_HOME/commands/{gesto}.md" <<'RITO'""", f'---\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\n---\n{gesto}', 'RITO']
2166 righe += [f'export DELMINIO_CANALE_RUOLO={_q(canale)}']
2167 if dal_repo:
2168 righe += [f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}"]
2169 if canale:
2170 righe += _fuori_dal_suo_spazio(nome, spazio_di(url, _token_di(token_file)))
2171 righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
2172 righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
2173 righe += _righe_al_lancio(modo, url, token_file)
2174 righe.append(_riga_exec('bash "$r/.claude/delminio.sh" qwen', fissi, '"$@"'))
2175 return '\n'.join(righe) + '\n'
2176 if porta:
2177 righe += _righe_del_prompt(riga, url, token_file)
2178 righe += [f'export DELMINIO_PORTA={_q(porta)}', 'export QWEN_SYSTEM_MD="$F"']
2179 if canale:
2180 righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
2181 if riga.get('cartella'):
2182 righe.append(f"cd {_q(riga['cartella'])} || exit 1")
2183 righe += _righe_al_lancio(modo, url, token_file)
2184 righe.append(_riga_exec(_q(cli), fissi, '"$@"'))
2185 return '\n'.join(righe) + '\n'
2186
2187def opencode_v2(versione):
2188 return str(versione).split('.', 1)[0] == '2'
2189OPENCODE_SOGLIA = 300000
2190OPENCODE_PRIMA_PAROLA_MS = 60000
2191
2192def config_opencode(riga, versione):
2193 f = riga.get('fornitore') or {}
2194 tipo = f.get('tipo')
2195 info = (riga.get('_fornitori') or {}).get(tipo) or {}
2196 if not info:
2197 raise RuntimeError(F('fornitore_ignoto', fornitore=tipo or ''))
2198 modello = riga.get('modello') or ''
2199 anthropic = info.get('auth') == 'anthropic'
2200 contesto = int(f.get('contesto') or 0)
2201 finestra = contesto or (1000000 if anthropic and QWEN_CLAUDE_1M.search(modello) else 0)
2202 base_spazio = riga.get('_base') or {}
2203 voluto = int(f.get('compatta') or 0)
2204 if finestra:
2205 soglia = min(voluto, finestra) if voluto else min(int(finestra * 0.85), int(base_spazio.get('opencode.compatta') or OPENCODE_SOGLIA))
2206 riserva = finestra - soglia
2207 else:
2208 riserva = '15%'
2209 base = {'update': 'disable', 'share': 'disabled', 'compaction': {'background': False, 'buffer': riserva}}
2210 if tipo == 'zen':
2211 return {**base, 'model': f'opencode/{modello}'} if modello else base
2212 chiave = chiave_qwen(riga)
2213 indirizzo = '' if anthropic else f.get('indirizzo') or info.get('indirizzo') or ''
2214 attesa = int(base_spazio.get('opencode.prima_parola_ms') or OPENCODE_PRIMA_PAROLA_MS)
2215 impostazioni = {**({'baseURL': indirizzo} if indirizzo else {}), 'headerTimeout': attesa, 'chunkTimeout': attesa}
2216 fornitore = {'name': info.get('nome') or tipo, 'env': [chiave], 'package': '@opencode/ai/providers/' + ('anthropic' if anthropic else 'openai-compatible'), 'settings': impostazioni, 'models': {modello: {'name': modello, **({'limit': {'context': finestra, 'output': min(32000, finestra // 4)}} if finestra else {})}}}
2217 return {**base, 'providers': {'delminio': fornitore}, 'model': f'delminio/{modello}'}
2218
2219def wrapper_opencode(riga, cli, modo, url, token_file):
2220 nome, porta = (riga['nome'], riga.get('porta'))
2221 if modo != 'kit':
2222 return '\n'.join([*_testa_del_wrapper(riga), 'echo ' + _sh(F('wrapper_opencode_solo_kit', nome=nome)) + ' >&2', 'exit 1']) + '\n'
2223 versione = os.path.basename(os.path.dirname(os.path.dirname(cli)))
2224 tipo = (riga.get('fornitore') or {}).get('tipo')
2225 delle_scelte, env_scelte = lancio_delle_scelte(riga)
2226 fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
2227 righe = [*_testa_del_wrapper(riga), 'export DELMINIO_CLI_NOME=opencode', 'export OPENCODE_DISABLE_AUTOUPDATE=1 # ' + F('commento_autoupdater'), *_commento(F('commento_config_opencode')), f'export DELMINIO_OPENCODE_CONFIG={_q(json.dumps(config_opencode(riga, versione), ensure_ascii=False, sort_keys=True))}', *([f'export DELMINIO_OPENCODE_GRATUITO={_q(nome)}'] if tipo == 'zen' and (not riga.get('modello')) else []), f'export DELMINIO_SQUADRA={hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]}', f'export DELMINIO_CLI={_q(cli)}']
2228 if riga.get('ordine'):
2229 righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
2230 for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
2231 if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
2232 righe.append(f'export {k}={_q(v)}')
2233 righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
2234 if tipo != 'zen':
2235 righe.append('export OPENCODE_DISABLE_MODELS_FETCH=1 # ' + F('commento_catalogo_opencode'))
2236 righe += _righe_della_chiave(riga, chiave_qwen(riga), tipo, nome, True, url, token_file)
2237 if porta:
2238 righe.append(f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}")
2239 righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
2240 elif riga.get('cartella'):
2241 righe.append(f"cd {_q(riga['cartella'])} || exit 1")
2242 righe += _righe_al_lancio(modo, url, token_file)
2243 righe.append(_riga_exec('bash "$r/.claude/delminio.sh" opencode', fissi, '"$@"'))
2244 return '\n'.join(righe) + '\n'
2245
2246def _fuori_dal_suo_spazio(nome, spazio):
2247 return ['qui=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null)', f'if [ -n "$qui" ] && [ "$qui" != {_q(spazio)} ]; then', ' echo ' + _sh(F('wrapper_altro_spazio', nome=nome, spazio=nome_spazio(spazio))) + ' >&2', ' exit 1', 'fi']
2248
2249def righe_della_casa(riga, nome, spazio):
2250 if (riga.get('scelte') or {}).get('casa') != 'separata':
2251 return [f"cd {_q(riga['cartella'])} || exit 1"] if riga.get('cartella') else []
2252 dove = _q(riga['cartella']) if riga.get('cartella') else ''
2253 return [*_commento(F('commento_casa')), f"""casa=$(python3 "$r/.claude/eseguibili.py" casa "$r/.claude/delminio.sh" {_q(riga['porta'])} {_q(nome)} {dove}) || exit 1""".rstrip(), 'cd "$casa" || exit 1']
2254
2255def wrapper(riga, cli, modo, url, token_file):
2256 if riga.get('cli') == 'codex':
2257 return wrapper_codex(riga, cli, modo, url, token_file)
2258 if riga.get('cli') == 'qwen':
2259 return wrapper_qwen(riga, cli, modo, url, token_file)
2260 if riga.get('cli') == 'opencode':
2261 return wrapper_opencode(riga, cli, modo, url, token_file)
2262 nome = riga['nome']
2263 args = []
2264 if riga.get('modello'):
2265 args += ['--model', riga['modello']]
2266 if riga.get('effort'):
2267 args += ['--effort', riga['effort']]
2268 delle_scelte, env_scelte = lancio_delle_scelte(riga)
2269 env_scelte = {**(riga.get('_promemoria') or {}), **env_scelte}
2270 args += delle_scelte + list(riga.get('argomenti') or [])
2271 if personaggio(riga):
2272 spazio = spazio_di(url, _token_di(token_file))
2273 canale = canale_del_ruolo(spazio, riga['porta'])
2274 args = con_i_ganci(args, ganci_della_posta(canale))
2275 args += ['--mcp-config', canale, '--allowedTools', f'mcp__{SERVER_RUOLO}__delminio,mcp__{SERVER_RUOLO}__delminio_write']
2276 args += ['--plugin-dir', _rito_del_ruolo()]
2277 fissi = ' '.join((_q(a) for a in args))
2278 righe = [*_testa_del_wrapper(riga), 'export DISABLE_AUTOUPDATER=1 # ' + F('commento_autoupdater')]
2279 if riga.get('ordine'):
2280 righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
2281 for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
2282 if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
2283 righe.append(f'export {k}={_q(v)}')
2284 porta = riga.get('porta')
2285 if modo == 'kit':
2286 if porta:
2287 righe += [*_commento(F('commento_token_progetto')), *_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo_claude', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
2288 if personaggio(riga):
2289 righe += _fuori_dal_suo_spazio(nome, spazio)
2290 righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
2291 if personaggio(riga):
2292 righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
2293 righe += _righe_al_lancio(modo, url, token_file)
2294 righe.append(_riga_exec('bash "$r/.claude/delminio.sh" claude', fissi, '"$@"'))
2295 return '\n'.join(righe) + '\n'
2296 elif porta:
2297 righe += _righe_del_prompt(riga, url, token_file)
2298 righe.append(f'export DELMINIO_PORTA={_q(porta)}')
2299 if personaggio(riga):
2300 righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
2301 if riga.get('cartella'):
2302 righe.append(f"cd {_q(riga['cartella'])} || exit 1")
2303 prompt = ' --system-prompt-file "$F"' if porta and modo != 'kit' else ''
2304 righe += _righe_al_lancio(modo, url, token_file)
2305 righe.append(_riga_exec(_q(cli), fissi, prompt.strip(), '"$@"'))
2306 return '\n'.join(righe) + '\n'
2307PROMEMORIA_AMMESSI = frozenset({'CLAUDE_CODE_SILENT_TURN_REMINDER_TEXT', 'CLAUDE_CODE_SILENT_TURN_REMINDER'})
2308
2309def parte_libera(riga):
2310 return {'cli': str(riga.get('cli') or 'claude'), 'argomenti': [str(x) for x in riga.get('argomenti') or []], 'ambiente': {str(k): str(v) for k, v in (riga.get('ambiente') or {}).items()}}
2311
2312def impronta_libera(riga):
2313 return hashlib.sha256(json.dumps([str(riga.get('nome') or ''), parte_libera(riga)], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
2314
2315def da_accettare(riga, accettati):
2316 p = parte_libera(riga)
2317 return bool(p['argomenti'] or p['ambiente']) and impronta_libera(riga) not in accettati
2318
2319def _visibile_riga(v):
2320 return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
2321
2322def accetta(registro):
2323 mio = _leggi(registro)
2324 fermi = [(url, x) for url, sp in (mio.get('spazi') or {}).items() for x in sp.get('fermi') or [] if isinstance(x, dict)]
2325 if not fermi:
2326 return 0
2327 try:
2328 tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
2329 except OSError:
2330 print(F('accetta_senza_terminale'), file=sys.stderr)
2331 return 1
2332 accettati, presi, restano = (set(mio.get('accettati') or []), set(), 0)
2333 for url, x in fermi:
2334 p = parte_libera(x)
2335 tty.write(F('accetta_riga_domanda', nome=_visibile_riga(x.get('nome')), cli=_visibile_riga(p['cli']), spazio=_visibile_riga(come_si_chiama(url)), argomenti=_visibile_riga(shlex.join(p['argomenti']) or '—'), ambiente=_visibile_riga(' '.join((f'{k}={shlex.quote(v)}' for k, v in sorted(p['ambiente'].items()))) or '—')))
2336 tty.flush()
2337 if tty_in.readline().strip().lower() in F('accetta_si').split():
2338 accettati.add(impronta_libera(x))
2339 presi.add(url)
2340 else:
2341 restano += 1
2342 mio = _leggi(registro)
2343 mio['accettati'] = sorted(set(mio.get('accettati') or []) | accettati)
2344 for url in presi:
2345 (mio.get('spazi') or {}).get(url, {})['registro'] = ''
2346 _scrivi(registro, mio)
2347 print(F('accetta_righe_esito', nuovi=len(fermi) - restano, restano=restano))
2348 return 0
2349
2350def _impronta(testo):
2351 return hashlib.sha256(testo.encode('utf-8')).hexdigest()[:16]
2352
2353def _del_file(p):
2354 try:
2355 with open(p, encoding='utf-8') as f:
2356 return _impronta(f.read())
2357 except (OSError, UnicodeDecodeError):
2358 return None
2359_DIARIO_MAX = 1000000
2360
2361def _nel_diario(registro, percorso, prima, dopo, vecchio, nuovo):
2362 diario = os.path.join(os.path.dirname(registro) or '.', 'eseguibili-diario.log')
2363 righe = [r for r in difflib.unified_diff((vecchio or '').splitlines(), nuovo.splitlines(), lineterm='', n=0) if not r.startswith(('---', '+++'))]
2364 testa = f"── {time.strftime('%Y-%m-%d %H:%M:%S')} {percorso} · CLI {prima or '—'} → {dopo}"
2365 try:
2366 if os.path.exists(diario) and os.path.getsize(diario) > _DIARIO_MAX:
2367 with open(diario, encoding='utf-8', errors='replace') as f:
2368 resto = f.read()[-_DIARIO_MAX // 2:]
2369 with open(diario, 'w', encoding='utf-8') as f:
2370 f.write(resto[resto.find('\n── ') + 1:] if '\n── ' in resto else resto)
2371 with open(os.open(diario, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384), 'a', encoding='utf-8') as f:
2372 f.write('\n'.join([testa, *righe]) + '\n')
2373 except OSError:
2374 pass
2375 return sum((1 for r in righe if r.startswith(('+', '-'))))
2376_SEGNO_CASA = 'export DELMINIO_SISTEMA="$F"'
2377
2378def _di_casa(p):
2379 try:
2380 with open(p, encoding='utf-8') as f:
2381 return _SEGNO_CASA in f.read()
2382 except (OSError, UnicodeDecodeError):
2383 return False
2384
2385def _leggi(path):
2386 try:
2387 with open(path, encoding='utf-8') as f:
2388 return json.load(f)
2389 except (OSError, ValueError):
2390 return {}
2391_CHIAVE_PER_SPAZIO = 1792090627
2392
2393def _spazio(mio, url):
2394 spazi = mio.setdefault('spazi', {})
2395 base = url.split('#', 1)[0]
2396 if url not in spazi and url != base and (base in spazi) and ((spazi[base].get('quando') or 0) < _CHIAVE_PER_SPAZIO) and (not any((k.startswith(base + '#') for k in spazi))):
2397 spazi[url] = spazi.pop(base)
2398 for chi in mio.get('padroni', {}).values():
2399 chi[:] = [url if u == base else u for u in chi]
2400 if url not in spazi:
2401 s = spazi[url] = {}
2402 if len(spazi) == 1:
2403 for k in ('registro', 'quando', 'rifiutato', 'cli'):
2404 if k in mio:
2405 s[k] = mio.pop(k)
2406 for p in mio.get('eseguibili', {}):
2407 mio.setdefault('padroni', {}).setdefault(p, [url])
2408 return spazi[url]
2409
2410def _scrivi(path, dati):
2411 os.makedirs(os.path.dirname(path), mode=448, exist_ok=True)
2412 with open(path + '.nuovo', 'w', encoding='utf-8') as f:
2413 json.dump(dati, f, ensure_ascii=False, indent=1)
2414 os.replace(path + '.nuovo', path)
2415
2416def _cli_del_wrapper(p):
2417 try:
2418 with open(p, encoding='utf-8') as f:
2419 testo = f.read()
2420 except OSError:
2421 return ''
2422 m = re.search('/versions(?:-pinned)?/(\\d+\\.\\d+\\.\\d+)', testo)
2423 return m.group(1) if m else '?'
2424
2425def sul_disco(versioni):
2426 try:
2427 return sorted((f for f in os.listdir(versioni) if _VERSIONE.match(f)), key=_v, reverse=True)
2428 except OSError:
2429 return []
2430
2431def nudo(bin_dir, versioni):
2432 p = os.path.join(bin_dir, 'claude')
2433 if not os.path.lexists(p):
2434 return ''
2435 vero = os.path.realpath(p)
2436 if os.path.dirname(vero) == os.path.realpath(versioni) and _VERSIONE.match(os.path.basename(vero)):
2437 return os.path.basename(vero)
2438 return 'altro'
2439
2440def pulisci(bin_dir, versioni, scelte=None):
2441 usate = set()
2442 cartelle = {os.path.realpath(versioni), os.path.abspath(os.path.expanduser(versioni))}
2443 voce = re.compile('(?:%s|/versions(?:-pinned)?)/(\\d+\\.\\d+\\.\\d+)' % '|'.join((re.escape(c) for c in cartelle)))
2444 try:
2445 nomi = [os.path.join(bin_dir, n) for n in os.listdir(bin_dir)]
2446 except OSError:
2447 nomi = []
2448 for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
2449 nomi += [os.path.join(radice, n) for n in file]
2450 for p in nomi:
2451 if os.path.islink(p):
2452 vero = os.path.realpath(p)
2453 if os.path.dirname(vero) == os.path.realpath(versioni):
2454 usate.add(os.path.basename(vero))
2455 continue
2456 try:
2457 if os.path.isfile(p) and os.path.getsize(p) < 200000:
2458 with open(p, encoding='utf-8', errors='ignore') as f:
2459 usate.update(voce.findall(f.read()))
2460 except OSError:
2461 pass
2462 if (n := nudo(bin_dir, versioni)) and n != 'altro':
2463 usate.add(n)
2464 libere = [v for v in sul_disco(versioni) if v not in usate]
2465 alta = max((v for v in usate if _VERSIONE.match(v)), key=_v, default=None)
2466 prima = [v for v in libere if alta and _v(v) < _v(alta)]
2467 riparo = (prima or libere)[:1]
2468 if scelte is not None:
2469 riparo = [v for v in libere if v not in scelte]
2470 tolte, errori = ([], [])
2471 for v in [x for x in libere if x not in riparo]:
2472 try:
2473 os.remove(os.path.join(versioni, v))
2474 tolte.append(v)
2475 except OSError as e:
2476 errori.append(f'{v}: {e.strerror}')
2477 esito = {'tolte': tolte, 'tenute': sorted(usate | set(riparo), key=_v, reverse=True)}
2478 if scelte is not None:
2479 riparo = []
2480 if errori:
2481 esito['errore'] = '; '.join(errori)[:300]
2482 print(F('pulizia', n=len(tolte), tolte=', '.join(tolte) or F('nessuna'), tenute=', '.join(esito['tenute']) or F('nessuna'), riparo=F('al_riparo', versione=riparo[0]) if riparo else ''))
2483 return esito
2484
2485def _cosa_lancia(bin_dir):
2486 nomi = [os.path.join(bin_dir, n) for n in (os.listdir(bin_dir) if os.path.isdir(bin_dir) else ())]
2487 for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
2488 nomi += [os.path.join(radice, n) for n in file]
2489 testi = []
2490 for p in nomi:
2491 try:
2492 if os.path.islink(p):
2493 testi.append(os.path.realpath(p))
2494 elif os.path.isfile(p) and os.path.getsize(p) < 200000:
2495 with open(p, encoding='utf-8', errors='ignore') as f:
2496 testi.append(f.read())
2497 except OSError:
2498 pass
2499 if os.path.isdir('/proc'):
2500 for pid in os.listdir('/proc'):
2501 if pid.isdigit():
2502 try:
2503 with open(f'/proc/{pid}/cmdline', 'rb') as f:
2504 testi.append(f.read().replace(b'\x00', b' ').decode(errors='ignore'))
2505 testi.append(os.readlink(f'/proc/{pid}/exe'))
2506 except OSError:
2507 pass
2508 else:
2509 try:
2510 testi.append(subprocess.run(['ps', '-axww', '-o', 'comm=', '-o', 'command='], capture_output=True, text=True, errors='ignore', timeout=20, check=True).stdout)
2511 except (OSError, subprocess.SubprocessError):
2512 return None
2513 return '\n'.join(testi)
2514
2515def pota(bin_dir, cartelle, nudo_claude=''):
2516 testo, tolte = (_cosa_lancia(bin_dir), [])
2517 if testo is None:
2518 return tolte
2519
2520 def via(dove, nome):
2521 try:
2522 shutil.rmtree(dove) if os.path.isdir(dove) and (not os.path.islink(dove)) else os.remove(dove)
2523 tolte.append(nome)
2524 except OSError:
2525 pass
2526 for cartella in [c for c in cartelle if c and os.path.isdir(c)]:
2527 radici = '|'.join((re.escape(c) for c in {os.path.realpath(cartella), os.path.abspath(cartella)}))
2528 usate = set(re.findall('(?:%s)/(\\d+\\.\\d+\\.\\d+)' % radici, testo)) | {nudo_claude}
2529 for v in sul_disco(cartella):
2530 if v not in usate:
2531 via(os.path.join(cartella, v), v)
2532 sopra = os.path.realpath(os.path.dirname(os.path.normpath(cartella)))
2533 nodi = set(re.findall('%s/(node-\\d[\\w.]*)' % re.escape(sopra), testo))
2534 for n in os.listdir(sopra) if nodi else ():
2535 if n.startswith('node-') and n not in nodi and os.path.isdir(os.path.join(sopra, n)):
2536 via(os.path.join(sopra, n), n)
2537 if tolte:
2538 print(F('potate', tolte=', '.join(tolte)), flush=True)
2539 return tolte
2540
2541def riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte=None, esito=None, senza_cli=()):
2542 stato = []
2543 for r in righe:
2544 p = os.path.join(bin_dir, r['nome'])
2545 ora = _del_file(p)
2546 intatto = ora is not None and impronte.get(p) == ora
2547 cli = (scritte or {}).get(p, '') if intatto else _cli_del_wrapper(p) if ora else ''
2548 stato.append({'nome': r['nome'], 'cli': cli, 'stato': 'senza_cli' if ora is None and r['nome'] in senza_cli else 'manca' if ora is None else 'intatto' if intatto else 'toccato'})
2549 corpo = {'host': socket.gethostname(), 'righe': stato, 'registro': registro, 'disco': sul_disco(versioni), 'nudo': nudo(bin_dir, versioni)}
2550 if esito:
2551 corpo['esito'] = esito
2552 try:
2553 return json.loads(_get(f'{base}/macchina', token, metodo='POST', corpo=corpo, timeout=10) or b'{}')
2554 except (OSError, ValueError, urllib.error.URLError):
2555 return {}
2556INSTALLABILI = tuple(CLI_NOMI)
2557
2558def richiesta(base, token, risposta, righe, impronte, bin_dir, versioni, registro, scritte, mio=None, file_mio=''):
2559 r = (risposta or {}).get('richiesta') or {}
2560 if r.get('pulizia'):
2561 scelte = r.get('versioni')
2562 esito = pulisci(bin_dir, versioni, scelte if isinstance(scelte, list) else None)
2563 riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito=esito)
2564 nuove = {c for c in r.get('installa') or [] if c in INSTALLABILI}
2565 if nuove and mio is not None and file_mio:
2566 mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | nuove)
2567 _scrivi(file_mio, mio)
2568 print(F('installo_chiesta', cli=', '.join(sorted(nuove))), flush=True)
2569 riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito={'installate': sorted(nuove)})
2570 return True
2571 return False
2572SEGNO_SMISTA = '# delminio-più-spazi'
2573_DIR_COMANDI = ['']
2574
2575def cartella_dei_comandi(registro):
2576 return os.path.join(os.path.dirname(registro) or '.', 'comandi')
2577
2578def comando_dello_spazio(spazio, nome):
2579 return os.path.join(_DIR_COMANDI[0], cartella_dello_spazio(spazio), nome)
2580
2581def cartella_dello_spazio(spazio):
2582 return re.sub('[^A-Za-z0-9._-]', '_', spazio)
2583
2584def come_si_chiama(spazio):
2585 if '#' in spazio:
2586 return spazio.rsplit('#', 1)[1]
2587 return urllib.parse.urlsplit(spazio).netloc or spazio
2588
2589def e_smistatore(p):
2590 try:
2591 with open(p, encoding='utf-8') as f:
2592 return SEGNO_SMISTA in f.read()
2593 except (OSError, UnicodeDecodeError):
2594 return False
2595
2596def smistatore(nome, spazi):
2597 elenco = ', '.join((come_si_chiama(s) for s in spazi))
2598 dove = _q(_DIR_COMANDI[0])
2599 return '\n'.join(['#!/bin/sh', f'# {nome} — ' + F('smista_testa'), SEGNO_SMISTA, *_commento(F('wrapper_commento')), 'r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ] || [ ! -f "$r/.claude/eseguibili.py" ]; then', ' echo ' + _sh(F('smista_fuori', nome=nome, spazi=elenco)) + ' >&2', ' exit 1', 'fi', 's=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null) || s=""', 'd=$(printf %s "$s" | tr -c \'A-Za-z0-9._-\' \'_\')', f'f={dove}/"$d"/{_q(nome)}', 'if [ -n "$s" ] && [ -x "$f" ]; then', ' exec "$f" "$@"', 'fi', 'echo ' + _sh(F('smista_non_qui', nome=nome, spazi=elenco)) + ' >&2', 'exit 1']) + '\n'
2600
2601def _scrivi_eseguibile(p, testo):
2602 os.makedirs(os.path.dirname(p), mode=448, exist_ok=True)
2603 with open(p + '.nuovo', 'w', encoding='utf-8') as f:
2604 f.write(testo)
2605 os.chmod(p + '.nuovo', 493)
2606 os.replace(p + '.nuovo', p)
2607
2608def dividi(p, url, testo, padroni, impronte):
2609 chi = padroni.get(p) or []
2610 nuovo = not e_smistatore(p)
2611 if nuovo:
2612 with open(p, encoding='utf-8') as f:
2613 di_prima = f.read()
2614 for u in chi:
2615 if u != url:
2616 q = comando_dello_spazio(u, os.path.basename(p))
2617 _scrivi_eseguibile(q, di_prima)
2618 impronte[q] = _impronta(di_prima)
2619 q = comando_dello_spazio(url, os.path.basename(p))
2620 _scrivi_eseguibile(q, testo)
2621 impronte[q] = _impronta(testo)
2622 if url not in chi:
2623 chi.append(url)
2624 padroni[p] = chi
2625 rifai_smistatore(p, chi, impronte)
2626 return nuovo
2627
2628def rifai_smistatore(p, chi, impronte):
2629 t = smistatore(os.path.basename(p), chi)
2630 if _del_file(p) != _impronta(t):
2631 _scrivi_eseguibile(p, t)
2632 impronte[p] = _impronta(t)
2633
2634def lascia_il_nome(p, url, padroni, impronte):
2635 chi = padroni.get(p) or []
2636 if url in chi:
2637 chi.remove(url)
2638 smista = e_smistatore(p) and impronte.get(p) == _del_file(p)
2639 if smista:
2640 q = comando_dello_spazio(url, os.path.basename(p))
2641 if impronte.get(q) and _del_file(q) == impronte[q]:
2642 os.remove(q)
2643 impronte.pop(q, None)
2644 if not chi:
2645 tolto = os.path.exists(p) and _del_file(p) == impronte.get(p)
2646 if tolto:
2647 os.remove(p)
2648 impronte.pop(p, None)
2649 padroni.pop(p, None)
2650 return 'tolto' if tolto else 'resta'
2651 if not smista:
2652 return 'altri'
2653 if len(chi) > 1:
2654 rifai_smistatore(p, chi, impronte)
2655 return 'altri'
2656 q = comando_dello_spazio(chi[0], os.path.basename(p))
2657 if impronte.get(q) and _del_file(q) == impronte[q]:
2658 with open(q, encoding='utf-8') as f:
2659 suo = f.read()
2660 _scrivi_eseguibile(p, suo)
2661 impronte[p] = _impronta(suo)
2662 os.remove(q)
2663 impronte.pop(q, None)
2664 return 'tornato'
2665 rifai_smistatore(p, chi, impronte)
2666 return 'altri'
2667_SKILL_PROGETTO = (('.claude/skills', ('claude',)), ('.agents/skills', ('codex', 'qwen')), ('.qwen/skills', ('qwen',)))
2668_SKILL_TETTO = 300
2669
2670def _skill_testa(percorso):
2671 try:
2672 with open(percorso, 'rb') as h:
2673 crudo = h.read(200000)
2674 except OSError:
2675 return None
2676 testo = crudo.decode('utf-8', errors='replace')
2677 m = re.match('^---\\s*\\n(.*?)\\n---\\s*(\\n|$)', testo, re.S)
2678 testa = m.group(1) if m else ''
2679
2680 def campo(nome):
2681 c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
2682 if not c:
2683 return ''
2684 v = ' '.join(c.group(1).split())
2685 if v[:1] in '"\'' and v[-1:] == v[:1]:
2686 v = v[1:-1]
2687 return '' if v in ('>', '|', '>-', '|-') else v
2688 nome = campo('name') or os.path.basename(os.path.dirname(percorso))
2689 return {'nome': nome, 'descrizione': campo('description')[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16]}
2690
2691def _skill_in(cartella):
2692 if not os.path.isdir(cartella):
2693 return []
2694 out = []
2695 for n in sorted(os.listdir(cartella)):
2696 p = os.path.join(cartella, n, 'SKILL.md')
2697 if not n.startswith('.') and os.path.isfile(p):
2698 t = _skill_testa(p)
2699 if t:
2700 out.append((t, p))
2701 return out
2702
2703def _da_leggere(p, radice):
2704 casa = os.path.expanduser('~')
2705 if radice and p.startswith(radice + os.sep):
2706 return os.path.relpath(os.path.dirname(p), radice)
2707 if p.startswith(casa + os.sep):
2708 return '~/' + os.path.relpath(os.path.dirname(p), casa)
2709 return os.path.dirname(p)
2710
2711def _case_codex():
2712 base = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'codex')
2713 return sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else []) if os.path.isfile(os.path.join(base, n, 'config.toml'))))
2714
2715def _blocchi_codex(testo):
2716 out = {}
2717 for b in re.split('(?m)^\\[\\[skills\\.config\\]\\]\\s*$', testo)[1:]:
2718 corpo = re.split('(?m)^\\[', b, maxsplit=1)[0]
2719 p = re.search('(?m)^path\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"', corpo)
2720 e = re.search('(?m)^enabled\\s*=\\s*(true|false)', corpo)
2721 if p:
2722 out[json.loads('"' + p.group(1) + '"')] = not (e and e.group(1) == 'false')
2723 return out
2724
2725def _claude_scelte(radice):
2726 out = {}
2727 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
2728 for f in (os.path.join(cfg, 'settings.json'), os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')):
2729 s = _leggi(f)
2730 if isinstance(s.get('skillOverrides'), dict):
2731 out.update(s['skillOverrides'])
2732 return out
2733_STATO_CLAUDE = {'on': 'accesa', 'name-only': 'accesa', 'user-invocable-only': 'a_mano', 'off': 'spenta'}
2734
2735def _qwen_stato(nome, livello, scelte):
2736 voluta = scelte.get(('qwen', nome))
2737 if voluta:
2738 return 'accesa' if voluta == 'accesa' else 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano'
2739 if livello != 'di_serie':
2740 return 'accesa'
2741 return 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano' if nome in QWEN_SKILL_A_SCELTA else 'accesa'
2742
2743def _progetto(radice):
2744 remoto = ''
2745 if radice:
2746 try:
2747 remoto = subprocess.run(['git', '-C', radice, 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, timeout=5).stdout.strip()
2748 except (OSError, subprocess.SubprocessError):
2749 remoto = ''
2750 return 'progetto:' + (re.sub('//[^/@]*@', '//', remoto) or os.path.basename(radice or ''))
2751
2752def raccogli_skill(radice, versioni_qwen, scelte=None):
2753 scelte = scelte or {}
2754 carte = []
2755 progetto = _progetto(radice)
2756 claude = _claude_scelte(radice) if radice else {}
2757 case = _case_codex()
2758 codex_blocchi = {}
2759 for casa in case:
2760 with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
2761 codex_blocchi.update(_blocchi_codex(h.read()))
2762
2763 def stato(cli, nome, livello, percorsi):
2764 out = {}
2765 for c in cli:
2766 if c == 'claude':
2767 out[c] = _STATO_CLAUDE.get(claude.get(nome, 'on'), 'accesa')
2768 elif c == 'codex':
2769 out[c] = 'spenta' if any((codex_blocchi.get(p) is False for p in percorsi)) else 'accesa'
2770 elif c == 'qwen':
2771 out[c] = _qwen_stato(nome, livello, scelte)
2772 return out
2773
2774 def metti(livello, dove, cartella, cli):
2775 for t, p in _skill_in(cartella):
2776 carte.append({**t, 'livello': livello, 'dove': dove, 'cartella': _da_leggere(p, radice), 'cli': list(cli), 'stato': stato(cli, t['nome'], livello, [p])})
2777 if radice:
2778 for rel, cli in _SKILL_PROGETTO:
2779 metti('progetto', progetto, os.path.join(radice, rel), cli)
2780 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
2781 metti('personale', 'personale', os.path.join(cfg, 'skills'), ('claude',))
2782 metti('personale', 'personale', os.path.expanduser('~/.agents/skills'), ('codex', 'qwen'))
2783 metti('personale', 'personale', os.path.expanduser('~/.qwen/skills'), ('qwen',))
2784 viste = set()
2785 for casa in case:
2786 for t, p in _skill_in(os.path.join(casa, 'skills', '.system')):
2787 if t['nome'] not in viste:
2788 viste.add(t['nome'])
2789 carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'codex', 'cli': ['codex'], 'stato': stato(('codex',), t['nome'], 'di_serie', [os.path.join(c, 'skills', '.system', t['nome'], 'SKILL.md') for c in case])})
2790 metti('personale', 'personale', os.path.join(casa, 'skills'), ('codex',))
2791 qv = sorted((v for v in (os.listdir(versioni_qwen) if os.path.isdir(versioni_qwen) else []) if _VERSIONE.match(v)), key=lambda v: tuple((int(x) for x in v.split('.'))))
2792 if qv:
2793 for t, _p in _skill_in(os.path.join(versioni_qwen, qv[-1], 'lib', 'node_modules', '@qwen-code', 'qwen-code', 'bundled')):
2794 carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'qwen ' + qv[-1], 'cli': ['qwen'], 'stato': stato(('qwen',), t['nome'], 'di_serie', [])})
2795 pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
2796 if radice and os.path.isfile(pacchetto) and shutil.which(os.environ.get('DELMINIO_CLI') or 'claude'):
2797 try:
2798 di_claude = runpy.run_path(pacchetto).get('SKILL_CLAUDE') or {}
2799 except Exception:
2800 di_claude = {}
2801 for nome in sorted(di_claude):
2802 carte.append({'nome': nome, 'descrizione': '', 'impronta': '', 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'claude', 'cli': ['claude'], 'stato': stato(('claude',), nome, 'di_serie', [])})
2803 carte += raccogli_pezzi(radice, progetto)
2804 return carte[:_SKILL_TETTO]
2805_COMANDI = (('.claude/commands', 'claude'), ('.qwen/commands', 'qwen'))
2806_AGENTI = (('.claude/agents', 'claude'), ('.qwen/agents', 'qwen'))
2807_PEZZO_PESO = 100000
2808_CHIAVE_FLAG = re.compile('^--?(?:[\\w-]*(?:token|key|secret|password|passwd|pass|auth|credential)[\\w-]*)$', re.I)
2809_CHIAVE_VALORE = re.compile('(?:^(?:sk-|ghp_|gho_|ghs_|github_pat_|xox[abpr]-|glpat-|AKIA|AIza)\\S+)|(?:^(?=[^/.]*\\d)(?=[^/.]*[A-Za-z])[A-Za-z0-9_+=-]{24,}$)')
2810NASCOSTO = '•••'
2811
2812def _testa_md(testo):
2813 m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
2814 testa, corpo = (m.group(1), testo[m.end():]) if m else ('', testo)
2815
2816 def campo(nome):
2817 c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
2818 if not c:
2819 return ''
2820 v = ' '.join(c.group(1).split())
2821 if v[:1] in '"\'' and v[-1:] == v[:1]:
2822 v = v[1:-1]
2823 return '' if v in ('>', '|', '>-', '|-') else v
2824 return (campo, corpo)
2825
2826def _prima_riga(corpo):
2827 for r in corpo.splitlines():
2828 r = r.strip().lstrip('#').strip()
2829 if r:
2830 return r[:200]
2831 return ''
2832
2833def _toml_stringa(testo, chiave):
2834 m = re.search('(?m)^' + re.escape(chiave) + '\\s*=\\s*("""(.*?)"""|\\\'\\\'\\\'(.*?)\\\'\\\'\\\'|"((?:[^"\\\\\\n]|\\\\.)*)"|\\\'([^\\\'\\n]*)\\\')', testo, re.S)
2835 if not m:
2836 return ''
2837 if m.group(4) is not None:
2838 try:
2839 return json.loads('"' + m.group(4) + '"')
2840 except ValueError:
2841 return m.group(4)
2842 return next((g for g in (m.group(2), m.group(3), m.group(5)) if g is not None))
2843
2844def _scheda_file(p, rel_nome, cli, tipo):
2845 try:
2846 with open(p, 'rb') as h:
2847 crudo = h.read(_PEZZO_PESO + 1)
2848 except OSError:
2849 return None
2850 testo = crudo.decode('utf-8', errors='replace')
2851 if p.endswith('.toml'):
2852 descrizione, nome = (_toml_stringa(testo, 'description'), rel_nome)
2853 else:
2854 campo, corpo = _testa_md(testo)
2855 nome = (campo('name') if tipo == 'agente' else '') or rel_nome
2856 descrizione = campo('description') or (_prima_riga(corpo) if tipo == 'comando' else '')
2857 return {'nome': nome, 'descrizione': descrizione[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16], 'tipo': tipo, 'cli': [cli], 'stato': {}}
2858
2859def _file_in(cartella, estensioni, ricorsivo):
2860 if not os.path.isdir(cartella):
2861 return []
2862 out = []
2863 for base, cartelle, nomi in os.walk(cartella):
2864 cartelle[:] = sorted((c for c in cartelle if not c.startswith('.'))) if ricorsivo else []
2865 for n in sorted(nomi):
2866 p = os.path.join(base, n)
2867 if n.startswith('.') or not n.endswith(estensioni) or (not os.path.isfile(p)):
2868 continue
2869 rel = os.path.relpath(p, cartella)
2870 out.append((p, os.path.splitext(rel)[0].replace(os.sep, ':')))
2871 return out
2872
2873def _cartella_da_leggere(p, radice):
2874 casa = os.path.expanduser('~')
2875 if radice and p.startswith(radice + os.sep):
2876 return os.path.relpath(p, radice)
2877 if p.startswith(casa + os.sep):
2878 return '~/' + os.path.relpath(p, casa)
2879 return p
2880
2881def _argomenti_puliti(argomenti):
2882 out, dopo_flag = ([], False)
2883 for a in argomenti or []:
2884 a = str(a)
2885 if '=' in a and _CHIAVE_FLAG.match(a.split('=', 1)[0]):
2886 out.append(a.split('=', 1)[0] + '=' + NASCOSTO)
2887 elif dopo_flag or _CHIAVE_VALORE.search(a) or '${' in a:
2888 out.append(NASCOSTO)
2889 else:
2890 out.append(a[:500])
2891 dopo_flag = bool(_CHIAVE_FLAG.match(a)) and '=' not in a
2892 return out[:40]
2893
2894def _url_pulito(url):
2895 try:
2896 u = urllib.parse.urlsplit(str(url or ''))
2897 except ValueError:
2898 return ''
2899 if u.scheme not in ('http', 'https') or not u.hostname:
2900 return ''
2901 host = u.netloc.rpartition('@')[2]
2902 return urllib.parse.urlunsplit((u.scheme, host, u.path, '', ''))[:500]
2903
2904def _variabile_del_token(intestazioni):
2905 for k, v in (intestazioni or {}).items():
2906 m = re.fullmatch('(?:Bearer\\s+)?\\$\\{?([A-Za-z_][A-Za-z0-9_]{0,63})\\}?', str(v or '').strip())
2907 if str(k).lower() == 'authorization' and m:
2908 return m.group(1)
2909 return ''
2910
2911def _server(nome, d, cli, livello, dove, cartella):
2912 if not isinstance(d, dict):
2913 return None
2914 url = d.get('url') or d.get('httpUrl') or ''
2915 intest = {}
2916 for k in ('headers', 'http_headers', 'env_http_headers'):
2917 if isinstance(d.get(k), dict):
2918 intest.update(d[k])
2919 if url:
2920 token = str(d.get('bearer_token_env_var') or '') or _variabile_del_token(intest)
2921 mcp = {'tipo': 'remoto', 'url': _url_pulito(url), 'intestazioni': sorted((str(k) for k in intest))[:20]}
2922 if token:
2923 mcp['token_variabile'] = token
2924 elif d.get('command'):
2925 variabili = set(d['env']) if isinstance(d.get('env'), dict) else set()
2926 variabili |= {str(v) for v in d.get('env_vars') or [] if isinstance(v, str)}
2927 mcp = {'tipo': 'locale', 'comando': str(d['command'])[:300], 'argomenti': _argomenti_puliti(d.get('args') if isinstance(d.get('args'), list) else []), 'variabili': sorted(variabili)[:20]}
2928 else:
2929 return None
2930 return {'nome': str(nome), 'descrizione': str(d.get('description') or '')[:600], 'impronta': '', 'tipo': 'mcp', 'cli': [cli], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': cartella, 'mcp': mcp}
2931
2932def _toml_tabelle(testo, radice_tabella):
2933 try:
2934 import tomllib
2935 d = tomllib.loads(testo).get(radice_tabella)
2936 return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}
2937 except ImportError:
2938 pass
2939 except ValueError:
2940 return {}
2941 out = {}
2942 for m in re.finditer('(?m)^\\[' + re.escape(radice_tabella) + '\\.("[^"\\n]+"|[A-Za-z0-9_-]+)(\\.[A-Za-z_]+)?\\]\\s*$', testo):
2943 nome = m.group(1).strip('"')
2944 corpo = re.split('(?m)^\\[', testo[m.end():], maxsplit=1)[0]
2945 campi = out.setdefault(nome, {})
2946 if m.group(2):
2947 campi[m.group(2)[1:]] = {k.strip('"'): '' for k in re.findall('(?m)^("[^"\\n]+"|[A-Za-z0-9_-]+)\\s*=', corpo)}
2948 continue
2949 for chiave, valore in re.findall('(?m)^([A-Za-z_]+)\\s*=\\s*(.+?)\\s*$', corpo):
2950 if valore.startswith('{'):
2951 campi[chiave] = {k.strip('"'): '' for k in re.findall('("[^"]+"|[A-Za-z0-9_-]+)\\s*=', valore)}
2952 else:
2953 try:
2954 campi[chiave] = json.loads(valore)
2955 except ValueError:
2956 campi[chiave] = valore.strip("'")
2957 return out
2958
2959def _codex_config(radice):
2960 out = []
2961 if radice:
2962 out.append((os.path.join(radice, '.codex', 'config.toml'), 'progetto'))
2963 casa = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
2964 out.append((os.path.join(casa, 'config.toml'), 'personale'))
2965 out += [(os.path.join(c, 'config.toml'), 'personale') for c in _case_codex()]
2966 return [(p, l) for p, l in out if os.path.isfile(p)]
2967
2968def raccogli_pezzi(radice, progetto):
2969 carte = []
2970 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
2971 casa_qwen = os.path.expanduser('~/.qwen')
2972
2973 def file_di(tipo, coppie_progetto, personali, estensioni, ricorsivo):
2974 dove_cli = [(os.path.join(radice, rel), cli, 'progetto', progetto) for rel, cli in coppie_progetto] if radice else []
2975 dove_cli += [(c, cli, 'personale', 'personale') for c, cli in personali]
2976 for cartella, cli, livello, dove in dove_cli:
2977 for p, rel_nome in _file_in(cartella, estensioni(cli), ricorsivo):
2978 if (s := _scheda_file(p, rel_nome, cli, tipo)):
2979 carte.append({**s, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(p, radice)})
2980 file_di('comando', _COMANDI, [(os.path.join(cfg, 'commands'), 'claude'), (os.path.join(casa_qwen, 'commands'), 'qwen')], lambda cli: ('.md', '.toml') if cli == 'qwen' else ('.md',), True)
2981 file_di('agente', _AGENTI, [(os.path.join(cfg, 'agents'), 'claude'), (os.path.join(casa_qwen, 'agents'), 'qwen')], lambda cli: ('.md',), False)
2982
2983 def server_json(percorso, chiavi, cli, livello, dove):
2984 d = _leggi(percorso)
2985 for k in chiavi:
2986 d = d.get(k) if isinstance(d, dict) else None
2987 for nome, s in (d or {}).items() if isinstance(d, dict) else []:
2988 if (x := _server(nome, s, cli, livello, dove, _cartella_da_leggere(percorso, radice))):
2989 carte.append(x)
2990 stato_claude = os.path.join(os.environ['CLAUDE_CONFIG_DIR'], '.claude.json') if os.environ.get('CLAUDE_CONFIG_DIR') else os.path.expanduser('~/.claude.json')
2991 if radice:
2992 server_json(os.path.join(radice, '.mcp.json'), ['mcpServers'], 'claude', 'progetto', progetto)
2993 server_json(os.path.join(radice, '.qwen', 'settings.json'), ['mcpServers'], 'qwen', 'progetto', progetto)
2994 server_json(stato_claude, ['projects', radice, 'mcpServers'], 'claude', 'personale', 'personale')
2995 server_json(stato_claude, ['mcpServers'], 'claude', 'personale', 'personale')
2996 server_json(os.path.join(casa_qwen, 'settings.json'), ['mcpServers'], 'qwen', 'personale', 'personale')
2997 visti = set()
2998 for percorso, livello in _codex_config(radice):
2999 try:
3000 with open(percorso, encoding='utf-8', errors='replace') as h:
3001 testo = h.read()
3002 except OSError:
3003 continue
3004 dove = progetto if livello == 'progetto' else 'personale'
3005 for nome, s in _toml_tabelle(testo, 'mcp_servers').items():
3006 if (livello, 'mcp', nome) not in visti and (x := _server(nome, s, 'codex', livello, dove, _cartella_da_leggere(percorso, radice))):
3007 visti.add((livello, 'mcp', nome))
3008 carte.append(x)
3009 for nome, s in _toml_tabelle(testo, 'agents').items():
3010 if (livello, 'agente', nome) not in visti:
3011 visti.add((livello, 'agente', nome))
3012 carte.append({'nome': nome, 'descrizione': str(s.get('description') or '')[:600], 'impronta': '', 'tipo': 'agente', 'cli': ['codex'], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(percorso, radice)})
3013 return carte
3014
3015def applica_skill(radice, scelte, fatte):
3016 ora = {f'{c}:{n}': v for (c, n), v in scelte.items()}
3017 via = [k for k in fatte or [] if k not in ora]
3018 pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
3019 try:
3020 p = runpy.run_path(pacchetto) if os.path.isfile(pacchetto) else {}
3021 except Exception:
3022 p = {}
3023 di_serie_claude, spente_codex = (p.get('SKILL_CLAUDE') or {}, set(p.get('SKILL_CODEX_SPENTE') or ()))
3024 locale = os.path.join(radice or '', '.claude', 'settings.local.json')
3025 if radice and os.path.isfile(locale):
3026 s = _leggi(locale)
3027 so = s.get('skillOverrides') if isinstance(s.get('skillOverrides'), dict) else {}
3028 prima = dict(so)
3029 for k, v in ora.items():
3030 c, n = k.split(':', 1)
3031 if c == 'claude':
3032 so[n] = 'on' if v == 'accesa' else 'user-invocable-only'
3033 for k in via:
3034 c, n = k.split(':', 1)
3035 if c == 'claude':
3036 if n in di_serie_claude:
3037 so[n] = di_serie_claude[n]
3038 else:
3039 so.pop(n, None)
3040 if so != prima:
3041 s['skillOverrides'] = so
3042 if not so:
3043 s.pop('skillOverrides', None)
3044 _scrivi_se_cambia(locale, json.dumps(s, indent=2, ensure_ascii=False) + '\n')
3045 for casa in _case_codex():
3046 conf = os.path.join(casa, 'config.toml')
3047 with open(conf, encoding='utf-8', errors='replace') as h:
3048 testo = h.read()
3049 nuovo = testo
3050
3051 def percorsi(n):
3052 out = [os.path.join(casa, 'skills', '.system', n, 'SKILL.md'), os.path.join(casa, 'skills', n, 'SKILL.md'), os.path.expanduser(os.path.join('~/.agents/skills', n, 'SKILL.md'))]
3053 if radice:
3054 out.append(os.path.join(radice, '.agents', 'skills', n, 'SKILL.md'))
3055 return [x for x in out if os.path.isfile(x)]
3056
3057 def blocco(t, percorso, acceso):
3058 chiave = json.dumps(percorso)
3059 schema = '(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(chiave) + '\\s*\\nenabled\\s*=\\s*(true|false)\\s*\\n?'
3060 riga = f"[[skills.config]]\npath = {chiave}\nenabled = {('true' if acceso else 'false')}\n"
3061 if acceso is None:
3062 return re.sub(schema, '', t)
3063 if re.search(schema, t):
3064 return re.sub(schema, riga.replace('\\', '\\\\'), t)
3065 return t.rstrip('\n') + '\n\n' + riga
3066 for k, v in ora.items():
3067 c, n = k.split(':', 1)
3068 if c == 'codex':
3069 for pp in percorsi(n):
3070 nuovo = blocco(nuovo, pp, v == 'accesa')
3071 for k in via:
3072 c, n = k.split(':', 1)
3073 if c == 'codex':
3074 for pp in percorsi(n):
3075 di_serie = '/skills/.system/' in pp.replace(os.sep, '/')
3076 nuovo = blocco(nuovo, pp, False if n in spente_codex and di_serie else None)
3077 if nuovo != testo:
3078 with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
3079 h.write(nuovo)
3080 os.replace(conf + '.nuovo', conf)
3081 return sorted(ora)
3082_PORTO_FILE, _PORTO_PESO = (30, 512000)
3083
3084def _cartelle_di_skill(radice):
3085 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
3086 out = [os.path.join(cfg, 'skills'), os.path.expanduser('~/.agents/skills'), os.path.expanduser('~/.qwen/skills')]
3087 out += [os.path.join(c, 'skills') for c in _case_codex()]
3088 if radice:
3089 out += [os.path.join(radice, rel) for rel, _cli in _SKILL_PROGETTO]
3090 return {os.path.realpath(x) for x in out}
3091
3092def _file_da_portare(radice, cartella):
3093 if cartella.startswith('~/'):
3094 d = os.path.expanduser(cartella)
3095 elif os.path.isabs(cartella):
3096 d = cartella
3097 else:
3098 d = os.path.join(radice or '', cartella)
3099 vero = os.path.realpath(d)
3100 if os.path.islink(d) or os.path.dirname(vero) not in _cartelle_di_skill(radice) or (not os.path.isfile(os.path.join(vero, 'SKILL.md'))):
3101 return (None, F('porto_non_qui', cartella=cartella))
3102 file, peso = ({}, 0)
3103 for base, cartelle, nomi in os.walk(vero):
3104 cartelle[:] = sorted((c for c in cartelle if not c.startswith('.') and (not os.path.islink(os.path.join(base, c)))))
3105 for n in sorted(nomi):
3106 p = os.path.join(base, n)
3107 if n.startswith('.') or os.path.islink(p):
3108 continue
3109 try:
3110 with open(p, 'rb') as h:
3111 crudo = h.read(_PORTO_PESO + 1)
3112 testo = crudo.decode('utf-8')
3113 except (OSError, UnicodeDecodeError):
3114 continue
3115 peso += len(crudo)
3116 if len(file) >= _PORTO_FILE or peso > _PORTO_PESO:
3117 return (None, F('porto_troppo', cartella=cartella, file=_PORTO_FILE, peso=_PORTO_PESO))
3118 file[os.path.relpath(p, vero).replace(os.sep, '/')] = testo
3119 return (file, '')
3120
3121def _cartelle_di_pezzi(radice):
3122 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
3123 out = [os.path.join(cfg, 'commands'), os.path.join(cfg, 'agents'), os.path.expanduser('~/.qwen/commands'), os.path.expanduser('~/.qwen/agents')]
3124 if radice:
3125 out += [os.path.join(radice, rel) for rel, _cli in _COMANDI + _AGENTI]
3126 return [os.path.realpath(x) for x in out]
3127
3128def _pezzo_da_portare(radice, cartella):
3129 if cartella.startswith('~/'):
3130 p = os.path.expanduser(cartella)
3131 elif os.path.isabs(cartella):
3132 p = cartella
3133 else:
3134 p = os.path.join(radice or '', cartella)
3135 vero = os.path.realpath(p)
3136 dentro = any((vero.startswith(c + os.sep) for c in _cartelle_di_pezzi(radice)))
3137 if os.path.islink(p) or not dentro or (not os.path.isfile(vero)) or (not vero.endswith(('.md', '.toml'))):
3138 return (None, F('porto_non_qui', cartella=cartella))
3139 try:
3140 with open(vero, 'rb') as h:
3141 crudo = h.read(_PEZZO_PESO + 1)
3142 testo = crudo.decode('utf-8')
3143 except (OSError, UnicodeDecodeError):
3144 return (None, F('porto_non_qui', cartella=cartella))
3145 if len(crudo) > _PEZZO_PESO:
3146 return (None, F('porto_troppo', cartella=cartella, file=1, peso=_PEZZO_PESO))
3147 return ({os.path.basename(vero): testo}, '')
3148
3149def _squadra(a, token, url, radice, impronta):
3150 pacchetto = os.path.join(radice or '', '.claude', 'squadra.py')
3151 if not radice or not os.path.isfile(pacchetto):
3152 return ''
3153 try:
3154 p = runpy.run_path(pacchetto)
3155 except Exception:
3156 return ''
3157 if 'squadra_scrivi' not in p:
3158 return ''
3159 chiave = hashlib.sha256(url.encode()).hexdigest()[:12]
3160 if impronta != (p['squadra_di'](chiave) or {}).get('impronta', ''):
3161 if impronta:
3162 try:
3163 pacco = json.loads(_get(a.url.rstrip('/') + '/api/skill/squadra', token, timeout=30) or b'{}')
3164 except (OSError, ValueError, urllib.error.URLError) as e:
3165 return F('squadra_muta', errore=e)
3166 else:
3167 pacco = {}
3168 if isinstance(pacco, dict):
3169 p['squadra_scrivi'](chiave, pacco)
3170 p['squadra_claude'](radice, chiave)
3171 if 'squadra_plugin_claude' in p:
3172 try:
3173 p['squadra_plugin_claude'](radice, chiave)
3174 except (OSError, subprocess.SubprocessError):
3175 pass
3176 sq = p['squadra_di'](chiave)
3177 if not sq:
3178 return ''
3179 c = sq['ruoli'].get('conto') or {}
3180 detto = F('squadra_qui', skill=c.get('skill', 0), comandi=c.get('comando', 0), agenti=c.get('agente', 0), mcp=c.get('mcp', 0), plugin=sq['plugin'])
3181 try:
3182 with open(os.path.join(sq['cartella'], '.plugin.json'), encoding='utf-8') as h:
3183 plugin_sq = [x for x in json.load(h) if isinstance(x, dict)]
3184 except (OSError, ValueError, TypeError):
3185 plugin_sq = []
3186 if plugin_sq:
3187 fermi = sum((1 for x in plugin_sq if not x.get('accettato')))
3188 detto += '\n' + F('squadra_plugin_qui', accettati=len(plugin_sq) - fermi, fermi=fermi)
3189 return detto
3190
3191def gesto_skill(a, url, sp, registro, mio):
3192 try:
3193 radice = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=5).stdout.strip()
3194 except (OSError, subprocess.SubprocessError):
3195 radice = ''
3196 try:
3197 token = open(os.path.expanduser(a.token_file)).read().strip()
3198 except OSError as e:
3199 print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
3200 return 2
3201 base = a.url.rstrip('/') + '/api/skill/macchina'
3202 scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in sp.get('skill_scelte') or [] if isinstance(x, dict)}
3203 carte = raccogli_skill(radice, os.path.expanduser(a.versioni_qwen), scelte)
3204 try:
3205 r = json.loads(_get(base, token, metodo='POST', timeout=20, corpo={'host': socket.gethostname(), 'skill': carte, 'plugin': raccogli_plugin(radice, _progetto(radice)), 'ganci': raccogli_ganci(radice, _progetto(radice))}) or b'{}')
3206 except (OSError, ValueError, urllib.error.URLError) as e:
3207 print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
3208 return 2
3209 nuove = r.get('scelte') if isinstance(r.get('scelte'), list) else []
3210 scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in nuove if isinstance(x, dict) and x.get('stato') in ('accesa', 'spenta') and _NOME_OK.fullmatch(str(x.get('nome') or ''))}
3211 chiave = 'skill_applicate:' + (radice or '')
3212 sp[chiave] = applica_skill(radice, scelte, sp.get(chiave) or [])
3213 sp['skill_scelte'] = [{'cli': c, 'nome': n, 'stato': v} for (c, n), v in sorted(scelte.items())]
3214 _scrivi(registro, mio)
3215 print(F('skill_riferite', n=len(carte), scelte=len(scelte)))
3216 for x in r.get('porta') if isinstance(r.get('porta'), list) else []:
3217 cartella = str((x or {}).get('cartella') or '') if isinstance(x, dict) else ''
3218 if not cartella:
3219 continue
3220 file, errore = _pezzo_da_portare(radice, cartella) if x.get('tipo') in ('comando', 'agente') else _file_da_portare(radice, cartella)
3221 try:
3222 e = json.loads(_get(a.url.rstrip('/') + '/api/skill/porto', token, metodo='POST', timeout=30, corpo={'cartella': cartella, **({'file': file} if file else {'errore': errore})}) or b'{}')
3223 print(F('porto_fatto', nome=e.get('nome') or x.get('nome') or '') if e.get('entrata') else F('porto_no', cartella=cartella, errore=e.get('errore') or errore))
3224 except (OSError, ValueError, urllib.error.URLError) as err:
3225 print(F('registro_muto', url=a.url, errore=err), file=sys.stderr)
3226 detto = _squadra(a, token, url, radice, str(r.get('squadra') or ''))
3227 if detto:
3228 print(detto)
3229 return 0
3230_PLUGIN_TETTO = 200
3231
3232def _origine_plugin(fonte):
3233 if not isinstance(fonte, dict):
3234 return ''
3235 tipo = str(fonte.get('source') or fonte.get('source_type') or fonte.get('type') or '')
3236 if tipo == 'github' and re.fullmatch('[\\w.-]+/[\\w.-]+', str(fonte.get('repo') or '')):
3237 return 'github:' + str(fonte['repo'])
3238 valore = str(fonte.get('url') or fonte.get('path') or fonte.get('source') or '')
3239 if re.match('(?i)(https?|ssh|git)://', valore):
3240 try:
3241 u = urllib.parse.urlsplit(valore)
3242 except ValueError:
3243 return ''
3244 return urllib.parse.urlunsplit((u.scheme, u.netloc.rpartition('@')[2], u.path, '', ''))[:300]
3245 if re.fullmatch('[\\w.-]+@[\\w.-]+:[\\w./-]+', valore):
3246 return valore.partition('@')[2][:300]
3247 if valore.startswith(('/', '~')):
3248 return 'cartella:' + _cartella_da_leggere(os.path.expanduser(valore), '')
3249 return ''
3250
3251def _di_delminio(mercato, nome=''):
3252 return mercato == 'delminio' or mercato.startswith('delminio-squadra-') or (not mercato and nome == 'delminio')
3253
3254def _carta_plugin(cli, nome, mercato, *, versione='', acceso=None, livello='personale', dove='personale', origine='', cartella=''):
3255 return {'tipo': 'plugin', 'cli': cli, 'nome': nome, 'mercato': mercato, 'versione': str(versione or '')[:40], 'stato': '' if acceso is None else 'acceso' if acceso else 'spento', 'livello': livello, 'dove': dove, 'origine': origine, 'cartella': cartella, 'di_delminio': _di_delminio(mercato, nome)}
3256
3257def _plugin_claude(radice, progetto, carte):
3258 cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
3259 acceso = {}
3260 impostazioni = [os.path.join(cfg, 'settings.json')]
3261 if radice:
3262 impostazioni += [os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')]
3263 for p in impostazioni:
3264 d = _leggi(p).get('enabledPlugins')
3265 for k, v in d.items() if isinstance(d, dict) else []:
3266 acceso[k] = v is True
3267 installati = _leggi(os.path.join(cfg, 'plugins', 'installed_plugins.json')).get('plugins')
3268 for pid, voci in installati.items() if isinstance(installati, dict) else []:
3269 nome, _, mercato = str(pid).partition('@')
3270 for v in voci if isinstance(voci, list) else []:
3271 if not isinstance(v, dict):
3272 continue
3273 if v.get('scope') == 'user':
3274 livello, dove = ('personale', 'personale')
3275 elif v.get('scope') in ('project', 'local') and radice and (v.get('projectPath') == radice):
3276 livello, dove = ('progetto', progetto)
3277 else:
3278 continue
3279 carte.append(_carta_plugin('claude', nome, mercato, versione=v.get('version'), acceso=acceso.get(pid, False), livello=livello, dove=dove))
3280 mercati = _leggi(os.path.join(cfg, 'plugins', 'known_marketplaces.json'))
3281 for nome, m in mercati.items() if isinstance(mercati, dict) else []:
3282 if isinstance(m, dict):
3283 carte.append({'tipo': 'marketplace', 'cli': 'claude', 'nome': nome, 'origine': _origine_plugin(m.get('source')), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
3284
3285def _plugin_codex(carte):
3286 casa_persona = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
3287 for casa in dict.fromkeys([casa_persona] + _case_codex()):
3288 try:
3289 with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
3290 testo = h.read()
3291 except OSError:
3292 continue
3293 cartella = _cartella_da_leggere(casa, '')
3294 for pid, campi in _toml_tabelle(testo, 'plugins').items():
3295 nome, _, mercato = pid.partition('@')
3296 cache = os.path.join(casa, 'plugins', 'cache', mercato, nome)
3297 versioni = sorted(os.listdir(cache)) if mercato and os.path.isdir(cache) else []
3298 carte.append(_carta_plugin('codex', nome, mercato, versione=versioni[-1] if versioni else '', acceso=campi.get('enabled') is not False, cartella=cartella))
3299 for nome, campi in _toml_tabelle(testo, 'marketplaces').items():
3300 carte.append({'tipo': 'marketplace', 'cli': 'codex', 'nome': nome, 'cartella': cartella, 'origine': _origine_plugin({'source_type': campi.get('source_type'), 'path': campi.get('source')} if campi.get('source_type') == 'local' else {'url': campi.get('source')}), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
3301
3302def _qwen_acceso(regole, qui):
3303 acceso = True
3304 for r in regole if isinstance(regole, list) else []:
3305 r = str(r)
3306 base = r.lstrip('!').rstrip('*').rstrip('/')
3307 if not base or qui == base or qui.startswith(base + '/'):
3308 acceso = not r.startswith('!')
3309 return acceso
3310
3311def _plugin_qwen(radice, carte):
3312 dati = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
3313 base = os.path.join(dati, 'delminio', 'qwen')
3314 case = [os.path.expanduser('~/.qwen')] + sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else [])))
3315 qui = radice or os.path.expanduser('~')
3316 for casa in case:
3317 cartella_ext = os.path.join(casa, 'extensions')
3318 if not os.path.isdir(cartella_ext):
3319 continue
3320 regole = _leggi(os.path.join(cartella_ext, 'extension-enablement.json'))
3321 for nome in sorted(os.listdir(cartella_ext)):
3322 d = os.path.join(cartella_ext, nome)
3323 if not os.path.isdir(d):
3324 continue
3325 inst = _leggi(os.path.join(d, '.qwen-extension-install.json'))
3326 sorgente = str(inst.get('source') or '')
3327 manifesto = _leggi(os.path.join(d, 'qwen-extension.json')) or (_leggi(os.path.join(sorgente, 'qwen-extension.json')) if inst.get('type') == 'link' else {})
3328 nome_vero = str(manifesto.get('name') or inst.get('pluginName') or nome)
3329 origine = _origine_plugin({'path': sorgente} if inst.get('type') in ('link', 'local') else {'url': sorgente})
3330 mercato = str((inst.get('marketplaceConfig') or {}).get('name') or '') if inst.get('pluginName') else ''
3331 carta = _carta_plugin('qwen', nome_vero, mercato, versione=manifesto.get('version'), origine=origine, acceso=_qwen_acceso((regole.get(nome_vero) or {}).get('overrides'), qui), cartella=_cartella_da_leggere(casa, ''))
3332 carta['di_delminio'] = nome_vero == 'delminio' or '/delminio/plugin/' in sorgente or '/delminio/squadre/' in sorgente
3333 carte.append(carta)
3334
3335def _plugin_opencode(radice, progetto, carte):
3336 casa = os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'opencode')
3337 posti = [(casa, 'personale', 'personale')] + ([(radice, 'progetto', progetto)] if radice else [])
3338 for cartella, livello, dove in posti:
3339 sotto = os.path.join(cartella, 'plugins' if cartella == casa else os.path.join('.opencode', 'plugins'))
3340 for f in sorted(os.listdir(sotto)) if os.path.isdir(sotto) else []:
3341 nome, est = os.path.splitext(f)
3342 if est in ('.js', '.ts', '.mjs') and os.path.isfile(os.path.join(sotto, f)):
3343 carta = _carta_plugin('opencode', nome, '', acceso=True, livello=livello, dove=dove, origine='file', cartella=_cartella_da_leggere(sotto, radice))
3344 carta['di_delminio'] = nome == 'delminio'
3345 carte.append(carta)
3346 for nome_conf in ('opencode.json', 'opencode.jsonc'):
3347 conf = _leggi(os.path.join(cartella, nome_conf))
3348 for pacchetto in conf.get('plugin') if isinstance(conf.get('plugin'), list) else []:
3349 m = re.fullmatch('(@?[\\w.-]+(?:/[\\w.-]+)?)(?:@([\\w.^~<>=-]+))?', str(pacchetto))
3350 if m:
3351 carte.append(_carta_plugin('opencode', m.group(1), '', versione=m.group(2) or '', acceso=True, livello=livello, dove=dove, origine='npm:' + m.group(1)))
3352
3353def raccogli_plugin(radice, progetto):
3354 carte = []
3355 for leggi in (lambda: _plugin_claude(radice, progetto, carte), lambda: _plugin_codex(carte), lambda: _plugin_qwen(radice, carte), lambda: _plugin_opencode(radice, progetto, carte)):
3356 try:
3357 leggi()
3358 except (OSError, ValueError, TypeError, AttributeError):
3359 continue
3360 return carte[:_PLUGIN_TETTO]
3361_GANCI_MOMENTI = (('apertura', 'apertura'), ('opening', 'apertura'), ('dove-siamo', 'dove-siamo'), ('status', 'dove-siamo'))
3362
3363def _ganci_git(radice, *argomenti):
3364 try:
3365 return subprocess.run(['git', '-C', radice, *argomenti], capture_output=True, text=True, timeout=5).stdout.strip()
3366 except (OSError, subprocess.SubprocessError):
3367 return ''
3368
3369def _ganci_accettate(radice):
3370 f = os.path.join(_ganci_git(radice, 'rev-parse', '--path-format=absolute', '--git-common-dir'), 'delminio-guardie-accettate')
3371 try:
3372 with open(f, encoding='utf-8') as h:
3373 return sorted({x for x in h.read().split() if re.fullmatch('[0-9a-f]{64}', x)})[:500]
3374 except OSError:
3375 return []
3376
3377def _ganci_script(radice):
3378 codice = os.environ.get('DELMINIO_FIDATI_PY') or ''
3379 if not codice:
3380 return []
3381 fidati = {}
3382 try:
3383 exec(codice, fidati)
3384 except Exception:
3385 return []
3386 gia = fidati['accettati'](radice)
3387 voci = [(f, momento) for cartella, momento in _GANCI_MOMENTI for f in fidati['script_del_progetto'](radice, (cartella,))]
3388 voci += [(f, 'lascito') for f in fidati['lascito_del_progetto'](radice)]
3389 out = []
3390 for f, momento in voci[:50]:
3391 altro = fidati['di_chi'](radice, f)
3392 out.append({'percorso': os.path.relpath(f, radice), 'momento': momento, 'gira': fidati['da_fidarsi'](radice, f, gia), 'di': altro[0] if altro else '', 'quando': altro[1] if altro else ''})
3393 return out
3394
3395def raccogli_ganci(radice, progetto):
3396 if not radice:
3397 return {}
3398 return {'dove': progetto, 'accettate': _ganci_accettate(radice), 'script': _ganci_script(radice)}
3399PROVA_CONTESTO_MIN = 32768
3400PROVA_CONTESTO_COMODO = 65536
3401_PROVA_STRUMENTO = {'nome': 'conta_lettere', 'descrizione': F('prova_strumento'), 'parametri': {'type': 'object', 'properties': {'parola': {'type': 'string'}}, 'required': ['parola']}}
3402_PROVA_CHIEDI = F('prova_chiedi')
3403_PROVA_PREFISSO = ' '.join((F('prova_regola', i=i) for i in range(330)))
3404
3405def _prova_post(url, intestazioni, corpo, timeout=90):
3406 req = urllib.request.Request(url, data=json.dumps(corpo).encode(), method='POST', headers={'Content-Type': 'application/json', **intestazioni})
3407 with urllib.request.urlopen(req, timeout=timeout) as r:
3408 return json.loads(r.read())
3409
3410def _prova_cache_letta(formato, risposta):
3411 u = risposta.get('usage') or {}
3412 if formato == 'anthropic':
3413 letti = u.get('cache_read_input_tokens')
3414 totale = (u.get('input_tokens') or 0) + (letti or 0) + (u.get('cache_creation_input_tokens') or 0)
3415 return (letti, totale)
3416 totale = u.get('prompt_tokens') or 0
3417 for chi in ((u.get('prompt_tokens_details') or {}).get('cached_tokens'), u.get('prompt_cache_hit_tokens'), u.get('cached_tokens'), (risposta.get('timings') or {}).get('cache_n')):
3418 if isinstance(chi, int):
3419 return (chi, totale)
3420 return (None, totale)
3421
3422def _prova_contesto(riga, formato, base, intestazioni, modello):
3423 f = riga.get('fornitore') or {}
3424 if f.get('contesto'):
3425 return int(f['contesto'])
3426 elenco = 'https://openrouter.ai/api/v1/models' if f.get('tipo') == 'openrouter' else base.rstrip('/') + '/models' if formato == 'openai' else ''
3427 if not elenco:
3428 return None
3429 h = {} if f.get('tipo') == 'openrouter' else intestazioni
3430 try:
3431 with urllib.request.urlopen(urllib.request.Request(elenco, headers=h), timeout=30) as r:
3432 dati = json.loads(r.read())
3433 except (OSError, ValueError):
3434 return None
3435 for m in dati.get('data') or dati.get('models') or []:
3436 if m.get('id') == modello or m.get('name') == modello:
3437 for k in ('context_length', 'context_window', 'max_model_len', 'max_context_length'):
3438 if isinstance(m.get(k), int):
3439 return m[k]
3440 meta = m.get('meta') or {}
3441 if isinstance(meta.get('n_ctx_train'), int):
3442 return meta['n_ctx_train']
3443 return None
3444
3445def prova_qwen(riga, dal_motore=''):
3446 imp = impostazioni_qwen(riga)
3447 formato = imp['security']['auth']['selectedType']
3448 p = imp['modelProviders'][formato][0]
3449 modello, base, variabile = (p['id'], p.get('baseUrl') or '', p['envKey'])
3450 tipo = (riga.get('fornitore') or {}).get('tipo')
3451 chiave = dal_motore or os.environ.get(variabile) or ('nessuna' if tipo == 'casa' else '')
3452 if not chiave:
3453 raise RuntimeError(F('prova_senza_chiave', variabile=variabile))
3454 marca = formato == 'anthropic' or 'dashscope' in base
3455 if formato == 'anthropic':
3456 url, intest = (base.rstrip('/') + '/v1/messages', {'x-api-key': chiave, 'anthropic-version': '2023-06-01'})
3457
3458 def corpo(sistema, testo, strumenti=False):
3459 s = {'type': 'text', 'text': sistema, **({'cache_control': {'type': 'ephemeral'}} if marca else {})}
3460 c = {'model': modello, 'max_tokens': 200, 'system': [s], 'messages': [{'role': 'user', 'content': testo}]}
3461 if strumenti:
3462 c['tools'] = [{'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'input_schema': _PROVA_STRUMENTO['parametri']}]
3463 return c
3464
3465 def chiamato(r):
3466 return any((b.get('type') == 'tool_use' and b.get('name') == _PROVA_STRUMENTO['nome'] and ('delminio' in json.dumps(b.get('input') or {}).lower()) for b in r.get('content') or []))
3467 else:
3468 url, intest = (base.rstrip('/') + '/chat/completions', {'Authorization': f'Bearer {chiave}'})
3469
3470 def corpo(sistema, testo, strumenti=False):
3471 s = [{'type': 'text', 'text': sistema, 'cache_control': {'type': 'ephemeral'}}] if marca else sistema
3472 c = {'model': modello, 'max_tokens': 200, 'messages': [{'role': 'system', 'content': s}, {'role': 'user', 'content': testo}]}
3473 if strumenti:
3474 c['tools'] = [{'type': 'function', 'function': {'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'parameters': _PROVA_STRUMENTO['parametri']}}]
3475 return c
3476
3477 def chiamato(r):
3478 for c in ((r.get('choices') or [{}])[0].get('message') or {}).get('tool_calls') or []:
3479 fn = c.get('function') or {}
3480 if fn.get('name') == _PROVA_STRUMENTO['nome'] and 'delminio' in str(fn.get('arguments') or '').lower():
3481 return True
3482 return False
3483 note = []
3484 try:
3485 tool = chiamato(_prova_post(url, intest, corpo(F('prova_sistema'), _PROVA_CHIEDI, True)))
3486 except urllib.error.HTTPError as e:
3487 testo = e.read()[:200].decode(errors='replace')
3488 if e.code in (401, 403):
3489 raise RuntimeError(F('prova_chiave_rifiutata', codice=e.code, testo=testo)) from None
3490 tool = False
3491 note.append(F('prova_strumento_errore', codice=e.code))
3492 letti = totale = None
3493 for attesa in (0, 3, 8):
3494 time.sleep(attesa)
3495 r = _prova_post(url, intest, corpo(_PROVA_PREFISSO, F('prova_ok')))
3496 letti, totale = _prova_cache_letta(formato, r)
3497 if attesa and (letti is None or letti > 0):
3498 break
3499 contesto = _prova_contesto(riga, formato, base, intest, modello)
3500 if not tool:
3501 note.append(F('prova_senza_strumento'))
3502 if contesto is not None and contesto < PROVA_CONTESTO_COMODO:
3503 note.append(F('prova_contesto_stretto', contesto=contesto))
3504 if letti is None:
3505 note.append(F('prova_cache_muta'))
3506 esito = 'non_va' if not tool or (contesto is not None and contesto < PROVA_CONTESTO_MIN) else 'va' if letti else 'senza_cache'
3507 return {'esito': esito, 'tool': tool, 'cache': {'letti': letti, 'totale': totale}, 'contesto': contesto, 'nota': '; '.join(note)}
3508
3509def comando_prova(a, righe, dati, base, token):
3510 riga = next((r for r in righe if a.nomi and r.get('nome') == a.nomi[0]), None)
3511 if riga is None or riga.get('cli') != 'qwen':
3512 print(F('uso_prova'), file=sys.stderr)
3513 return 2
3514 riga = {**riga, '_fornitori': dati.get('fornitori_qwen') or {}}
3515 locale = (riga.get('fornitore') or {}).get('tipo') == 'casa'
3516 print(F('prova_inizio_locale', nome=riga['nome'], modello=riga.get('modello')) if locale else F('prova_inizio_fornitore', nome=riga['nome'], modello=riga.get('modello')))
3517 dal_motore = ''
3518 if (scelta := (riga.get('fornitore') or {}).get('chiave')):
3519 try:
3520 dal_motore = _get(base + '/' + urllib.parse.quote(riga['nome']) + '/chiave', token).decode().strip()
3521 except urllib.error.HTTPError as e:
3522 print(F('prova_chiave_negata', scelta=scelta, errore=e.read()[:400].decode(errors='replace')), file=sys.stderr)
3523 return 1
3524 except (OSError, urllib.error.URLError) as e:
3525 print(F('prova_chiave_negata', scelta=scelta, errore=e), file=sys.stderr)
3526 return 1
3527 try:
3528 v = prova_qwen(riga, dal_motore)
3529 except (RuntimeError, OSError, ValueError) as e:
3530 print(F('prova_non_fatta', errore=e), file=sys.stderr)
3531 return 1
3532 c = v['cache']
3533 print(F('prova_riga_strumenti', valore=F('prova_si') if v['tool'] else F('prova_no')))
3534 print(F('prova_riga_cache', valore=F('prova_cache_non_detta') if c['letti'] is None else F('prova_cache_letti', letti=c['letti'], totale=c['totale'])))
3535 print(F('prova_riga_contesto', valore=v['contesto'] or F('prova_non_lo_dice')))
3536 print(F('prova_riga_verdetto', valore={'va': F('prova_va'), 'senza_cache': F('prova_senza_cache'), 'non_va': F('prova_non_va')}[v['esito']], nota=f" ({v['nota']})" if v['nota'] else ''))
3537 try:
3538 _get(base + '/' + urllib.parse.quote(riga['nome']) + '/prova', token, metodo='POST', corpo=v)
3539 except (OSError, urllib.error.URLError) as e:
3540 print(F('verdetto_perso', errore=e), file=sys.stderr)
3541 return 1
3542 return 0 if v['esito'] != 'non_va' else 1
3543
3544def comando_rinomina(a, righe, base, token):
3545 if len(a.nomi) != 2:
3546 print(F('uso_rinomina'), file=sys.stderr)
3547 return 2
3548 vecchio, nuovo = a.nomi
3549 riga = next((r for r in righe if r['nome'] == vecchio), None)
3550 if riga is None:
3551 print(F('rinomina_assente', nome=vecchio), file=sys.stderr)
3552 return 1
3553 try:
3554 _get(f'{base}/{urllib.parse.quote(vecchio)}/rinomina', token, metodo='POST', corpo={'nuovo': nuovo})
3555 except urllib.error.HTTPError as e:
3556 print(F('rinomina_rifiutata', errore=e.read().decode('utf-8', 'replace')[:300]), file=sys.stderr)
3557 return 1
3558 print(F('rinominato', vecchio=vecchio, nuovo=nuovo))
3559 return 0
3560
3561def comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro):
3562 for r in righe:
3563 p = os.path.join(bin_dir, r['nome'])
3564 try:
3565 voluta = versione_voluta(r, canali)
3566 except Exception as e:
3567 voluta = f'? ({e})'
3568 ora = _del_file(p)
3569 stato = F('stato_assente') if ora is None else F('stato_cambiato') if impronte.get(p) not in (None, ora) else F('stato_non_suo') if impronte.get(p) is None else F('stato_intatto') if url in padroni.get(p, [url]) else F('stato_altro_spazio', spazi=', '.join(padroni[p]))
3570 cli = os.path.join(os.path.expanduser(a.versioni_codex), voluta, 'bin', 'codex') if r.get('cli') == 'codex' else os.path.join(os.path.expanduser(a.versioni_qwen), voluta, 'bin', 'qwen') if r.get('cli') == 'qwen' else os.path.join(os.path.expanduser(a.versioni_opencode), voluta, 'bin', 'opencode') if r.get('cli') == 'opencode' else os.path.join(versioni, voluta)
3571 print(F('stato_riga', nome=r['nome'], versione=voluta, da_scaricare='' if os.path.isfile(cli) or prova else F('da_scaricare'), modello=r.get('modello') or F('modello_di_serie'), porta=r.get('porta') or '—', stato=stato))
3572 if sp.get('rifiutato'):
3573 print(F('stato_rifiutato'))
3574 if not righe:
3575 print(F('registro_vuoto'))
3576 r = riferisci(base, token, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'))
3577 richiesta(base, token, r, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'), mio=mio, file_mio=registro)
3578 return 0
3579
3580def comando_lascia(a, url, padroni, impronte, mio, registro):
3581 tolti = 0
3582 for p in [x for x, chi in padroni.items() if url in chi]:
3583 if lascia_il_nome(p, url, padroni, impronte) == 'tolto':
3584 tolti += 1
3585 mio['spazi'].pop(url, None)
3586 _scrivi(registro, mio)
3587 comando = os.path.join(os.path.expanduser(a.bin), 'delminio')
3588 if not mio['spazi'] and os.path.isfile(comando):
3589 with open(comando, encoding='utf-8', errors='replace') as h:
3590 if '# delminio-comando\n' in h.read():
3591 os.remove(comando)
3592 print(F('lasciati', n=tolti))
3593 return 0
3594
3595def scrivi_il_primo(a, dati, righe, bin_dir, impronte):
3596 cli_voluta = a.vuoi or 'claude'
3597 catalogo = (dati.get('modelli') or {}).get(cli_voluta) or []
3598 ordine = [m.get('id') for m in catalogo]
3599 consigliati = {m.get('id') for m in catalogo if m.get('consigliato')}
3600 candidati = sorted((r for r in righe if (r.get('cli') or 'claude') == cli_voluta and (not personaggio(r))), key=lambda r: (r.get('modello') not in consigliati, ordine.index(r.get('modello')) if r.get('modello') in ordine else len(ordine)))
3601 primo = next((p for p in (os.path.join(bin_dir, r['nome']) for r in candidati) if impronte.get(p) and _del_file(p) == impronte[p]), '')
3602 if not candidati:
3603 print(F('nessun_agente_di', cli=CLI_NOMI.get(cli_voluta, cli_voluta)))
3604 with open(a.primo, 'w', encoding='utf-8') as f:
3605 f.write(primo)
3606
3607def main():
3608 if sys.argv[1:2] == ['posta-ruolo']:
3609 return posta_ruolo(sys.argv[2:])
3610 if sys.argv[1:2] == ['casa']:
3611 return casa(sys.argv[2:])
3612 if sys.argv[1:2] == ['mie-qwen']:
3613 return unisci_mie_qwen(sys.argv[2:])
3614 if sys.argv[1:2] == ['mie-codex']:
3615 return unisci_mie_codex(sys.argv[2:])
3616 if sys.argv[1:2] == ['pulizia']:
3617 return pulizia(sys.argv[2:])
3618 if sys.argv[1:2] == ['errori-registra']:
3619 return errori_registra(sys.argv[2:])
3620 if sys.argv[1:2] == ['errori']:
3621 return errori(sys.argv[2:])
3622 if sys.argv[1:2] == ['pulizia-codex']:
3623 return pulizia_codex(sys.argv[2:])
3624 if sys.argv[1:2] == ['pulizia-opencode']:
3625 return pulizia_opencode(sys.argv[2:])
3626 if sys.argv[1:2] == ['installa-agente']:
3627 return installa_agente(sys.argv[2:])
3628 if sys.argv[1:2] == ['modello-gratuito']:
3629 return modello_gratuito(sys.argv[2:])
3630 if sys.argv[1:2] == ['accetta']:
3631 return accetta(os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json'))
3632 ap = argparse.ArgumentParser(description=F('aiuto_descrizione'))
3633 ap.add_argument('comando', nargs='?', default='allinea', choices=['allinea', 'stato', 'no', 'rinomina', 'lascia', 'spazio', 'prova', 'skill'])
3634 ap.add_argument('nomi', nargs='*', help=F('aiuto_nomi'))
3635 ap.add_argument('--url')
3636 ap.add_argument('--token-file')
3637 ap.add_argument('--da', help=F('aiuto_da'))
3638 ap.add_argument('--modo', choices=['kit', 'casa'], default='kit')
3639 ap.add_argument('--al-lancio', action='store_true', help=F('aiuto_al_lancio'))
3640 ap.add_argument('--converti', action='store_true', help=F('aiuto_converti'))
3641 ap.add_argument('--vuoi', choices=list(CLI_NOMI), help=F('aiuto_vuoi'))
3642 ap.add_argument('--primo', help=F('aiuto_primo'))
3643 ap.add_argument('--bin', default=os.environ.get('DELMINIO_BIN') or '~/.local/bin')
3644 ap.add_argument('--versioni', default=os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions')
3645 ap.add_argument('--versioni-codex', default=os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions')
3646 ap.add_argument('--versioni-qwen', default=os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
3647 ap.add_argument('--versioni-opencode', default=os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions')
3648 ap.add_argument('--registro', default=os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
3649 a = ap.parse_args()
3650 if a.da:
3651 for riga in open(a.da, encoding='utf-8'):
3652 k, _, v = riga.strip().partition('=')
3653 if k in ('URL', 'FILE_TOKEN') and v:
3654 setattr(a, 'url' if k == 'URL' else 'token_file', (shlex.split(v) or [''])[0])
3655 if not a.url or not a.token_file:
3656 ap.error(F('servono_url_token'))
3657 bin_dir, versioni, registro = (os.path.expanduser(x) for x in (a.bin, a.versioni, a.registro))
3658 _DIR_COMANDI[0] = cartella_dei_comandi(registro)
3659 prova = os.environ.get('DELMINIO_CLI_PROVA', '')
3660 mio = _leggi(registro)
3661 if a.vuoi and a.comando == 'allinea':
3662 mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {a.vuoi})
3663 _scrivi(registro, mio)
3664 letto = _del_file(registro)
3665 impronte = mio.setdefault('eseguibili', {})
3666 _ALIASI.update(mio.get('alias') or {})
3667 url = spazio_di(a.url, _token_di(a.token_file))
3668 if a.comando == 'spazio':
3669 if url not in mio.get('spazi', {}) and mio.get('spazi'):
3670 vero = _alias(mio, url, _istanza_di(a.url, _token_di(a.token_file)))
3671 if vero != url:
3672 _scrivi(registro, mio)
3673 url = vero
3674 print(url)
3675 return 0
3676 sp = _spazio(mio, url)
3677 if a.comando == 'skill':
3678 return gesto_skill(a, url, sp, registro, mio)
3679 if a.comando == 'allinea' and a.modo == 'kit':
3680 ricorda_il_progetto(url)
3681 padroni = mio.setdefault('padroni', {})
3682 if a.comando == 'no':
3683 sp['rifiutato'] = True
3684 _scrivi(registro, mio)
3685 print(F('rifiutati'))
3686 return 0
3687 if a.comando == 'lascia':
3688 return comando_lascia(a, url, padroni, impronte, mio, registro)
3689 base = a.url.rstrip('/') + '/api/eseguibili'
3690 try:
3691 token = open(os.path.expanduser(a.token_file)).read().strip()
3692 dati = json.loads(_get(base, token))
3693 righe = dati['eseguibili']
3694 except (OSError, ValueError, KeyError, urllib.error.URLError) as e:
3695 print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
3696 return 2
3697 fuori = [str(r.get('nome')) for r in righe if not _NOME_OK.fullmatch(str(r.get('nome') or ''))]
3698 if fuori:
3699 print(F('nomi_fuori_forma', nomi=', '.join(map(repr, fuori))), file=sys.stderr)
3700 righe = [r for r in righe if _NOME_OK.fullmatch(str(r.get('nome') or ''))]
3701 istanza = dati.get('istanza') or ''
3702 if (vero := _alias(mio, url, istanza)) != url:
3703 url, sp = (vero, _spazio(mio, vero))
3704 if istanza:
3705 sp['istanza'] = istanza
3706 al_lancio = a.comando == 'allinea' and a.al_lancio
3707 if al_lancio and sp.get('registro') == dati.get('impronta'):
3708 return 3 if os.environ.get('DELMINIO_AL_LANCIO_ATTESO') else 0
3709 if al_lancio and (not os.environ.get('DELMINIO_AL_LANCIO_ATTESO')):
3710 print(F('al_lancio'), file=sys.stderr)
3711 if a.comando == 'prova':
3712 return comando_prova(a, righe, dati, base, token)
3713 if a.comando == 'rinomina':
3714 return comando_rinomina(a, righe, base, token)
3715 canali, esito = ({}, 0)
3716 if a.comando == 'stato':
3717 return comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro)
3718 if fcntl is not None:
3719 try:
3720 os.makedirs(os.path.dirname(registro) or '.', exist_ok=True)
3721 lucchetto = open(registro + '.lock', 'w')
3722 fcntl.flock(lucchetto, fcntl.LOCK_EX | fcntl.LOCK_NB)
3723 except OSError:
3724 if not al_lancio or os.environ.get('DELMINIO_AL_LANCIO_ATTESO') or 'lucchetto' not in locals():
3725 print(F('allinea_in_corso'))
3726 return 0
3727 print(F('al_lancio_attesa'), file=sys.stderr)
3728 fcntl.flock(lucchetto, fcntl.LOCK_EX)
3729 lucchetto.close()
3730 os.environ['DELMINIO_AL_LANCIO_ATTESO'] = '1'
3731 sys.stderr.flush()
3732 os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
3733 else:
3734 if _del_file(registro) != letto and (not os.environ.get('DELMINIO_RILETTO')):
3735 lucchetto.close()
3736 os.environ['DELMINIO_RILETTO'] = '1'
3737 sys.stdout.flush()
3738 sys.stderr.flush()
3739 os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
3740 os.makedirs(bin_dir, exist_ok=True)
3741 nomi = set()
3742 senza_cli = set()
3743 detto = [0.0]
3744
3745 def avanza(percento, passo, subito=False):
3746 if not subito and time.time() - detto[0] < 2:
3747 return
3748 detto[0] = time.time()
3749 try:
3750 _get(f'{base}/lavoro', token, metodo='POST', corpo={'host': socket.gethostname(), 'percento': int(percento), 'passo': passo[:120]}, timeout=5)
3751 except (OSError, ValueError, urllib.error.URLError):
3752 pass
3753 nomi_cli = dati.get('cli') or {}
3754 quante = max(1, len(righe))
3755 prima_volta = 'accettati' not in mio
3756 accettati, fermi = (set(mio.get('accettati') or []), [])
3757 for i, r in enumerate(righe):
3758 p = os.path.join(bin_dir, r['nome'])
3759 nomi.add(p)
3760 quota, nome_cli = (100.0 * i / quante, nomi_cli.get(r.get('cli') or 'claude', r.get('cli') or 'claude'))
3761 if not cli_qui(r.get('cli') or 'claude', versioni, os.path.expanduser(a.versioni_codex), prova, os.path.expanduser(a.versioni_qwen), mio.get('cli_volute') or (), os.path.expanduser(a.versioni_opencode)):
3762 senza_cli.add(r['nome'])
3763 print(F('senza_cli_qui', nome=r['nome'], cli=r.get('cli') or 'claude'))
3764 continue
3765 if da_accettare(r, accettati):
3766 if prima_volta and any((impronte.get(x) for x in (p, comando_dello_spazio(url, r['nome'])))):
3767 accettati.add(impronta_libera(r))
3768 else:
3769 fermi.append({'nome': r['nome'], **parte_libera(r)})
3770 print(F('riga_da_accettare', nome=r['nome']))
3771 continue
3772 try:
3773 voluta = versione_voluta(r, canali)
3774 avanza(quota, F('passo_controllo', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
3775 su = lambda f, t, q=quota, n=nome_cli, vv=voluta, nn=r['nome']: avanza(q + 90.0 / quante * (f / t if t else 0), F('passo_scarico', nome=nn, cli=n, versione=vv, mb=f // 1000000) + (F('passo_di', mb=t // 1000000) if t else ''))
3776 cli = assicura_codex(voluta, os.path.expanduser(a.versioni_codex), prova, su=su) if r.get('cli') == 'codex' else assicura_qwen(voluta, os.path.expanduser(a.versioni_qwen), prova, su=su) if r.get('cli') == 'qwen' else assicura_opencode(voluta, os.path.expanduser(a.versioni_opencode), prova, su=su) if r.get('cli') == 'opencode' else assicura_cli(voluta, versioni, prova, su=su)
3777 if personaggio(r) and r.get('cli') in ('claude', 'qwen'):
3778 assicura_canale(a.url, token, r['porta'])
3779 if r.get('cli') == 'claude':
3780 assicura_rito()
3781 except Exception as e:
3782 print(f"❌ {r['nome']}: {e}")
3783 esito = 1
3784 continue
3785 modello = next((m for m in (dati.get('modelli') or {}).get(r.get('cli') or 'claude', []) if m['id'] == r.get('modello')), {})
3786 promemoria = ((dati.get('promemoria') or {}).get('ambiente') or {}).get(r.get('cli') or 'claude') or {}
3787 promemoria = {k: v for k, v in promemoria.items() if k in PROMEMORIA_AMMESSI}
3788 da_lanciare = {**r, '_contesto': modello.get('contesto') or {}, '_promemoria': promemoria, '_fornitori': (dati.get('fornitori_opencode') if r.get('cli') == 'opencode' else dati.get('fornitori_qwen')) or {}, '_skill': dati.get('skill_scelte') or [], '_base': dati.get('parametri_base') or {}}
3789 testo = wrapper(da_lanciare, cli, a.modo, a.url, os.path.expanduser(a.token_file))
3790 ora = _del_file(p)
3791 if ora is not None and p not in impronte:
3792 print(F('non_di_delminio', percorso=p))
3793 esito = 1
3794 continue
3795 if ora is not None and impronte.get(p) != ora:
3796 print(F('toccato_resta', percorso=p))
3797 continue
3798 if a.modo == 'kit' and (not a.converti) and (ora != _impronta(testo)) and _di_casa(p):
3799 testo = wrapper(da_lanciare, cli, 'casa', a.url, os.path.expanduser(a.token_file))
3800 chi = padroni.get(p) or []
3801 altri = [u for u in chi if u != url]
3802 if ora is not None and altri and (not e_smistatore(p)) and (ora == _impronta(testo)):
3803 if url not in chi:
3804 chi.append(url)
3805 sp.setdefault('cli', {})[p] = voluta
3806 continue
3807 if ora is not None and (altri or e_smistatore(p)):
3808 q = comando_dello_spazio(url, r['nome'])
3809 gia = _del_file(q)
3810 if gia is not None and impronte.get(q) not in (None, gia):
3811 print(F('toccato_resta', percorso=q))
3812 continue
3813 vecchio = None
3814 if gia is not None:
3815 with open(q, encoding='utf-8') as f:
3816 vecchio = f.read()
3817 prima = (sp.get('cli') or {}).get(p)
3818 sp.setdefault('cli', {})[p] = voluta
3819 if url in chi and gia == _impronta(testo) and e_smistatore(p):
3820 continue
3821 if dividi(p, url, testo, padroni, impronte):
3822 print(F('smistato', nome=r['nome'], spazi=', '.join((come_si_chiama(u) for u in padroni[p]))))
3823 cambiate = _nel_diario(registro, q, prima, voluta, vecchio, testo)
3824 if gia is None:
3825 print(F('scritto', percorso=q, versione=voluta))
3826 elif gia != _impronta(testo):
3827 print(F('rinfrescato', percorso=q, versione=voluta, righe=cambiate) if prima == voluta else F('aggiornato', percorso=q, prima=prima or '?', versione=voluta))
3828 continue
3829 padroni[p] = [url] + altri
3830 prima = (sp.get('cli') or {}).get(p)
3831 sp.setdefault('cli', {})[p] = voluta
3832 if ora == _impronta(testo):
3833 continue
3834 vecchio = None
3835 if ora is not None:
3836 try:
3837 with open(p, encoding='utf-8') as f:
3838 vecchio = f.read()
3839 except (OSError, UnicodeDecodeError):
3840 pass
3841 with open(p + '.nuovo', 'w', encoding='utf-8') as f:
3842 f.write(testo)
3843 os.chmod(p + '.nuovo', 493)
3844 os.replace(p + '.nuovo', p)
3845 impronte[p] = _impronta(testo)
3846 cambiate = _nel_diario(registro, p, prima, voluta, vecchio, testo)
3847 if ora is None:
3848 print(F('scritto', percorso=p, versione=voluta))
3849 elif prima == voluta:
3850 print(F('rinfrescato', percorso=p, versione=voluta, righe=cambiate))
3851 else:
3852 print(F('aggiornato', percorso=p, prima=prima or '?', versione=voluta))
3853 avanza(100.0 * (i + 1) / quante, F('passo_scritto', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
3854 for p in [x for x in impronte if x not in nomi and os.path.dirname(x) == bin_dir]:
3855 chi = padroni.get(p) or []
3856 if url not in chi:
3857 continue
3858 sp.get('cli', {}).pop(p, None)
3859 com_e = lascia_il_nome(p, url, padroni, impronte)
3860 if com_e == 'tolto':
3861 print(F('tolto', percorso=p))
3862 elif com_e in ('altri', 'tornato'):
3863 print(F('lasciato_ad_altri', percorso=p, spazi=', '.join(padroni.get(p) or [])))
3864 if righe:
3865 sp['rifiutato'] = False
3866 mio['accettati'], sp['fermi'] = (sorted(accettati), fermi)
3867 sp['registro'], sp['quando'] = (dati.get('impronta', ''), int(time.time()))
3868 sp['skill_scelte'] = dati.get('skill_scelte') or []
3869 _scrivi(registro, mio)
3870 if esito == 0 and righe and (not prova):
3871 pota(bin_dir, [versioni] + [os.path.expanduser(c) for c in (a.versioni_codex, a.versioni_qwen, a.versioni_opencode)], nudo(bin_dir, versioni))
3872 r = riferisci(base, token, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), senza_cli=senza_cli)
3873 if richiesta(base, token, r, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), mio=mio, file_mio=registro) and (not os.environ.get('DELMINIO_RIALLINEATO')):
3874 os.environ['DELMINIO_RIALLINEATO'] = '1'
3875 sys.stdout.flush()
3876 os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
3877 cartelle = [os.path.realpath(os.path.expanduser(c)) for c in os.environ.get('PATH', '').split(os.pathsep) if c]
3878 if righe and os.path.realpath(bin_dir) not in cartelle:
3879 print(F('fuori_dal_path', cartella=bin_dir))
3880 if a.primo:
3881 scrivi_il_primo(a, dati, righe, bin_dir, impronte)
3882 return 3 if al_lancio and esito == 0 else esito
3883if __name__ == '__main__':
3884 sys.exit(main())