delminio-client / kit / en / plugin-client
raw · sha256 d56e617ef624f1bf454f8fc77b6f7f3afe17133238dcd0de37c715c12ffd9612
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"""Il pacchetto di Delminio per le CLI degli agenti (F776): i ganci, /apertura e"""
4from __future__ import annotations
5import hashlib
6import json
7import os
8import re
9import runpy
10import shlex
11import shutil
12import subprocess
13import sys
14NOME = 'delminio'
15ID = f'{NOME}@{NOME}'
16SERVER = 'memoria'
17SERVER_DI_PRIMA = ('delminio', 'delminio-ruolo')
18TOOL = ('delminio', 'delminio_write')
19TOOLS_CLAUDE = tuple((f'mcp__plugin_{NOME}_{SERVER}__{t}' for t in TOOL))
20TOOLS_CLAUDE_PROGETTO = tuple((f'mcp__{SERVER}__{t}' for t in TOOL))
21TOOLS_CLAUDE_DI_PRIMA = tuple((f'mcp__plugin_{NOME}_delminio__{t}' for t in TOOL)) + tuple((f'mcp__{s}__{t}' for s in SERVER_DI_PRIMA for t in TOOL))
22SKILL_CLAUDE = {'dataviz': 'on', 'keybindings-help': 'on', 'update-config': 'on', 'claude-api': 'name-only', 'code-review': 'name-only', 'fewer-permission-prompts': 'name-only', 'init': 'name-only', 'plugin-authoring': 'name-only', 'run': 'name-only', 'security-review': 'name-only', 'simplify': 'name-only', 'workflow-authoring': 'name-only', 'loop': 'name-only', 'schedule': 'name-only'}
23SKILL_CLAUDE_F811 = {**{n: 'user-invocable-only' for n in ('claude-api', 'code-review', 'fewer-permission-prompts', 'init', 'plugin-authoring', 'run', 'security-review', 'simplify')}, 'loop': 'off', 'schedule': 'off'}
24CHIEDI_CLAUDE = ('Agent', 'Workflow')
25SKILL_CODEX_SPENTE = ()
26SKILL_CODEX_F811 = ('imagegen', 'skill-creator', 'skill-installer')
27COMANDI = {
28 "riti": {
29 "apertura": "apertura",
30 "chiusura": "chiusura",
31 "closing": "chiusura",
32 "handoff": "chiusura",
33 "opening": "apertura",
34 "start": "apertura"
35 }
36}
37FRASI = {
38 "descrizione": "Delminio: the project's memory, opening and closing sessions, messages between agents and the checks before an action",
39 "apertura": "Delminio: open the session with your role's briefing \u2014 what you write after the command goes as your message",
40 "apertura_suggerimento": "[what you want to tell it right away]",
41 "chiusura": "Delminio: close the session \u2014 what you write after the command goes as your message",
42 "chiusura_suggerimento": "[what to do before closing]",
43 "ciclo_opencode": "Delminio: this is the third time you have made exactly this call, and the last two got the same answer: a fourth will change nothing. Take another route, or stop and tell the person who gave you the work what is blocking you.",
44 "fermo_opencode": "Delminio stopped this run: the model made the same call with the same answer again even after three warnings. Read what it was trying to do and tell it again what you want, or change model.",
45 "permesso_opencode": "Delminio: this agent's rules do not let {rifiutati} through ({permesso}). In a chain (|, ;, &&) each command is checked on its own, and one outside the rules stops the whole chain; redirections pass.{ammessi} Do not retry the same command: run the ones the rules allow on their own, or tell the person who gave you the work what you need.",
46 "ammessi_opencode": " The rules allow: {elenco}.",
47 "opencode_v1": "Delminio does not work with OpenCode 1: the project memory and the checks are not here. Exit and update to OpenCode 2 with \u201copencode upgrade --major\u201d, then reopen OpenCode in this project. To the model: tell the person to update, before working.",
48 "uso": "usage: python3 .claude/plugin.py claude|rimuovi|opencode <repo root> \xb7 codex|qwen <CLI folder> \xb7 app-codex [stato|allinea|via|no|lascia]"
49}
50
51def F(chiave: str, **valori) -> str:
52 testo = FRASI[chiave]
53 for k, v in valori.items():
54 testo = testo.replace('{' + k + '}', str(v))
55 return testo
56
57def cartella() -> str:
58 return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'plugin')
59GANCI_CLAUDE = (('SessionStart', 'apertura', {}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, 'Write|Edit|MultiEdit|NotebookEdit'), ('PreToolUse', 'guardia', {'timeout': 5}, 'Read|Grep|Glob|Write|Edit|MultiEdit|NotebookEdit|Bash'), ('PreToolUse', 'condiviso', {'timeout': 10}, 'Bash'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('PostToolUseFailure', 'errore', {'timeout': 5}, ''), ('Stop', 'attesa', {'asyncRewake': True, 'timeout': 43200}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
60LUNGO = {'additionalContextLimit': 16000}
61FINE_CODEX = {'timeout': 3}
62GANCI_CODEX = (('SessionStart', 'apertura', LUNGO, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(apply_patch|Edit|Write)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(apply_patch|Edit|Write|Bash)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^Bash$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10, **LUNGO}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', FINE_CODEX, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', FINE_CODEX, ''))
63GANCI_QWEN = (('SessionStart', 'apertura', {'timeout': 60}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(edit|write_file|notebook_edit)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(read_file|grep_search|edit|write_file|notebook_edit|run_shell_command)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^run_shell_command$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
64QWEN = NOME + '-qwen'
65PERMESSI_CODEX = tuple((f'[plugins."{ID}".mcp_servers.{SERVER}.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
66PERMESSI_CODEX_DI_PRIMA = tuple((f'[plugins."{ID}".mcp_servers.delminio.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
67
68def _permessi_codex(conf: str) -> None:
69 with open(conf, encoding='utf-8') as h:
70 testo = h.read()
71 nuovo = testo
72 for b in PERMESSI_CODEX_DI_PRIMA:
73 nuovo = nuovo.replace('\n' + b, '').replace(b, '')
74 if (mancano := [b for b in PERMESSI_CODEX if b not in nuovo]):
75 nuovo = nuovo.rstrip('\n') + '\n\n' + '\n'.join(mancano)
76 if nuovo != testo:
77 with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
78 h.write(nuovo)
79 os.replace(conf + '.nuovo', conf)
80LANCIATORE = '#!/usr/bin/env bash\nd=${CLAUDE_PROJECT_DIR:-$PWD}\nr=$(cd "$d" 2>/dev/null && git rev-parse --show-toplevel 2>/dev/null) || exit 0\n[ -f "$r/.claude/delminio.sh" ] || exit 0\nexec bash "$r/.claude/delminio.sh" "$@"\n'
81
82def _skill(nome: str, descrizione: str, suggerimento: str, comando: str) -> str:
83 return f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\nargument-hint: {json.dumps(suggerimento, ensure_ascii=False)}\ndisable-model-invocation: true\nallowed-tools: Bash(bash:*)\n---\n!`{comando}`\n\n$ARGUMENTS\n'
84
85def ganci(chiama: str, lista, matcher_sempre: bool=False) -> dict:
86 g: dict = {}
87 for evento, gesto, extra, matcher in lista:
88 g.setdefault(evento, []).append({**({'matcher': matcher} if matcher or matcher_sempre else {}), 'hooks': [{'type': 'command', 'command': f'{chiama} {gesto}', **extra}]})
89 return g
90
91def contenuti(radice_pacchetto: str) -> dict[str, str]:
92 lanciatore = os.path.join(radice_pacchetto, NOME, 'bin', 'delminio')
93 chiama = 'bash ' + shlex.quote(lanciatore)
94 server = {'command': 'bash', 'args': [lanciatore, 'ponte']}
95 f = {os.path.join(NOME, 'bin', 'delminio'): LANCIATORE, os.path.join(NOME, 'hooks', 'hooks.json'): json.dumps({'hooks': ganci(chiama, GANCI_CLAUDE)}, indent=2) + '\n', os.path.join(NOME, '.mcp.json'): json.dumps({'mcpServers': {SERVER: server}}, indent=2) + '\n', os.path.join(NOME, 'hooks', 'codex.json'): json.dumps({'hooks': ganci(chiama, GANCI_CODEX)}, indent=2) + '\n', os.path.join(NOME, 'mcp-codex.json'): json.dumps({'mcpServers': {SERVER: {**server, 'env_vars': ['DELMINIO_MODELLO', 'DELMINIO_CLI_NOME']}}}, indent=2) + '\n'}
96 riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
97 for nome, rito in sorted(riti.items()):
98 f[os.path.join(QWEN, 'commands', nome + '.md')] = f"---\ndescription: {json.dumps(F('apertura') if rito == 'apertura' else F('chiusura'), ensure_ascii=False)}\n---\n{nome}\n"
99 qwen_server = {**server, 'timeout': 60000, 'trust': True, 'alwaysLoadTools': True}
100 apre = (F('apertura'), F('apertura_suggerimento'), f'{chiama} prompt')
101 chiude = (F('chiusura'), F('chiusura_suggerimento'), f'{chiama} chiusura')
102 for nome, rito in sorted(riti.items()):
103 f[os.path.join(NOME, 'skills', nome, 'SKILL.md')] = _skill(nome, *(apre if rito == 'apertura' else chiude))
104 impronta = hashlib.sha256(''.join((k + v for k, v in sorted(f.items()))).encode()).hexdigest()
105 versione = f'1.0.{int(impronta[:7], 16)}'
106 f[os.path.join(NOME, '.claude-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione')}, ensure_ascii=False, indent=2) + '\n'
107 f[os.path.join(QWEN, 'qwen-extension.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'mcpServers': {SERVER: qwen_server}, 'hooks': ganci(chiama, GANCI_QWEN, matcher_sempre=True)}, ensure_ascii=False, indent=2) + '\n'
108 f[os.path.join(NOME, 'skills-codex', '.vuota')] = ''
109 f[os.path.join(NOME, '.codex-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'skills': './skills-codex/', 'hooks': './hooks/codex.json', 'mcpServers': './mcp-codex.json'}, ensure_ascii=False, indent=2) + '\n'
110 f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': NOME, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': NOME, 'source': {'source': 'local', 'path': './' + NOME}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n'
111 f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': NOME, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': NOME, 'source': './' + NOME, 'description': F('descrizione'), 'version': versione}]}, ensure_ascii=False, indent=2) + '\n'
112 return f
113
114def scrivi() -> str:
115 radice = cartella()
116 for rel, testo in contenuti(radice).items():
117 p = os.path.join(radice, rel)
118 try:
119 with open(p, encoding='utf-8') as h:
120 if h.read() == testo:
121 continue
122 except OSError:
123 pass
124 os.makedirs(os.path.dirname(p), exist_ok=True)
125 with open(p + '.nuovo', 'w', encoding='utf-8') as h:
126 h.write(testo)
127 if rel.endswith(os.path.join('bin', 'delminio')):
128 os.chmod(p + '.nuovo', 493)
129 os.replace(p + '.nuovo', p)
130 return radice
131
132def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
133 return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
134
135def _acceso(radice: str) -> bool:
136 try:
137 with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
138 return (json.load(h).get('enabledPlugins') or {}).get(ID) is True
139 except (OSError, ValueError, AttributeError):
140 return False
141
142def claude(radice: str) -> int:
143 if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
144 return 3
145 try:
146 if _claude('--help', cwd=radice).returncode != 0:
147 return 3
148 pacchetto = scrivi()
149 _claude('marketplace', 'add', pacchetto, '--scope', 'local', cwd=radice)
150 _claude('install', ID, '--scope', 'local', cwd=radice)
151 if not _acceso(radice):
152 _claude('enable', ID, '--scope', 'local', cwd=radice)
153 except (OSError, subprocess.TimeoutExpired):
154 return 3
155 return 0 if _acceso(radice) else 3
156
157def _versione() -> str:
158 return json.loads(contenuti(cartella())[os.path.join(NOME, '.codex-plugin', 'plugin.json')])['version']
159
160def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
161 return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
162
163def _codex_pronto(casa: str) -> bool:
164 try:
165 with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
166 conf = h.read()
167 except OSError:
168 return False
169 acceso = re.search('^\\[plugins\\."' + re.escape(ID) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
170 return bool(acceso) and all((b in conf for b in PERMESSI_CODEX)) and (not any((b in conf for b in PERMESSI_CODEX_DI_PRIMA))) and os.path.isdir(os.path.join(casa, 'plugins', 'cache', NOME, NOME, _versione()))
171
172def _skill_codex(casa: str) -> None:
173 conf = os.path.join(casa, 'config.toml')
174 try:
175 with open(conf, encoding='utf-8') as h:
176 testo = h.read()
177 except FileNotFoundError:
178 testo = ''
179 except OSError:
180 return
181 prima = testo
182 segno = os.path.join(casa, 'delminio-skill-f844')
183 if testo and (not os.path.exists(segno)):
184 for nome in SKILL_CODEX_F811:
185 percorso = json.dumps(os.path.join(casa, 'skills', '.system', nome, 'SKILL.md'))
186 testo = re.sub('(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(percorso) + '\\s*\\nenabled\\s*=\\s*false\\s*\\n?\\n?', '', testo)
187 blocchi = []
188 for nome in SKILL_CODEX_SPENTE:
189 percorso = os.path.join(casa, 'skills', '.system', nome, 'SKILL.md')
190 if json.dumps(percorso) not in testo:
191 blocchi.append(f'[[skills.config]]\npath = {json.dumps(percorso)}\nenabled = false\n')
192 try:
193 os.makedirs(casa, exist_ok=True)
194 if blocchi or testo != prima:
195 with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
196 h.write((testo.rstrip('\n') + '\n\n' if testo.strip() else '') + '\n'.join(blocchi) if blocchi else testo)
197 os.replace(conf + '.nuovo', conf)
198 if not os.path.exists(segno):
199 open(segno, 'w').close()
200 except OSError:
201 pass
202
203def codex(casa: str) -> int:
204 if not shutil.which(os.environ.get('DELMINIO_CODEX') or 'codex'):
205 return 3
206 pacchetto = scrivi()
207 _skill_codex(casa)
208 _squadra('codex', casa)
209 if _codex_pronto(casa):
210 return 0
211 try:
212 os.makedirs(casa, exist_ok=True)
213 _codex(casa, 'marketplace', 'add', pacchetto)
214 _codex(casa, 'remove', ID)
215 _codex(casa, 'add', ID)
216 _permessi_codex(os.path.join(casa, 'config.toml'))
217 except (OSError, subprocess.TimeoutExpired):
218 return 3
219 return 0 if _codex_pronto(casa) else 3
220APP_CODEX = ('/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '~/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '/usr/lib/chatgpt/resources/codex')
221
222def app_codex_cli() -> str:
223 return next((p for p in map(os.path.expanduser, APP_CODEX) if os.access(p, os.X_OK)), '')
224
225def _casa_app() -> str:
226 return os.path.expanduser('~/.codex')
227
228def _no_app() -> str:
229 return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio', 'app-codex-no')
230
231def _app_scelta(casa: str) -> bool:
232 try:
233 with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
234 return bool(re.search('^\\[marketplaces\\.' + re.escape(NOME) + '\\]', h.read(), re.M))
235 except OSError:
236 return False
237
238def app_codex_stato() -> str:
239 if not app_codex_cli():
240 return ''
241 if _app_scelta(_casa_app()):
242 return 'dentro'
243 return 'no' if os.path.exists(_no_app()) else 'manca'
244
245def app_codex() -> int:
246 cli = app_codex_cli()
247 if not cli:
248 return 4
249 casa = _casa_app()
250 vecchio = os.environ.get('DELMINIO_CODEX')
251 os.environ['DELMINIO_CODEX'] = cli
252 try:
253 pacchetto = scrivi()
254 if not _codex_pronto(casa):
255 os.makedirs(casa, exist_ok=True)
256 _codex(casa, 'marketplace', 'add', pacchetto)
257 _codex(casa, 'remove', ID)
258 _codex(casa, 'add', ID)
259 _permessi_codex(os.path.join(casa, 'config.toml'))
260 except (OSError, subprocess.TimeoutExpired):
261 return 3
262 finally:
263 if vecchio is None:
264 os.environ.pop('DELMINIO_CODEX', None)
265 else:
266 os.environ['DELMINIO_CODEX'] = vecchio
267 try:
268 os.remove(_no_app())
269 except OSError:
270 pass
271 return 0 if _codex_pronto(casa) else 3
272
273def app_codex_allinea() -> int:
274 if app_codex_cli() and _app_scelta(_casa_app()) and (not _codex_pronto(_casa_app())):
275 return app_codex()
276 return 0
277
278def app_codex_via() -> int:
279 casa = _casa_app()
280 cli = app_codex_cli() or shutil.which('codex') or ''
281 if cli:
282 vecchio = os.environ.get('DELMINIO_CODEX')
283 os.environ['DELMINIO_CODEX'] = cli
284 try:
285 _codex(casa, 'remove', ID)
286 _codex(casa, 'marketplace', 'remove', NOME)
287 except (OSError, subprocess.TimeoutExpired):
288 pass
289 finally:
290 if vecchio is None:
291 os.environ.pop('DELMINIO_CODEX', None)
292 else:
293 os.environ['DELMINIO_CODEX'] = vecchio
294 conf = os.path.join(casa, 'config.toml')
295 try:
296 with open(conf, encoding='utf-8') as h:
297 testo = h.read()
298 except OSError:
299 return 0
300 nuovo = testo
301 for b in PERMESSI_CODEX + PERMESSI_CODEX_DI_PRIMA:
302 nuovo = nuovo.replace('\n' + b, '').replace(b, '')
303 for intestazione in (f'[plugins."{ID}"]', f'[marketplaces.{NOME}]'):
304 nuovo = re.sub('(?ms)^' + re.escape(intestazione) + '\\n.*?(?=^\\[|\\Z)', '', nuovo)
305 if nuovo != testo:
306 with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
307 h.write(nuovo.rstrip('\n') + '\n')
308 os.replace(conf + '.nuovo', conf)
309 return 0 if not _app_scelta(casa) else 3
310
311def app_codex_lascia() -> int:
312 try:
313 os.remove(_no_app())
314 except OSError:
315 pass
316 if not _app_scelta(_casa_app()):
317 return 0
318 return 2 if app_codex_via() == 0 else 3
319
320def app_codex_no() -> int:
321 os.makedirs(os.path.dirname(_no_app()), exist_ok=True)
322 with open(_no_app(), 'w', encoding='utf-8') as h:
323 h.write('no\n')
324 return 0
325
326def _qwen_pronto(casa: str, estensione: str) -> bool:
327 try:
328 with open(os.path.join(casa, 'extensions', NOME, '.qwen-extension-install.json'), encoding='utf-8') as h:
329 d = json.load(h)
330 except (OSError, ValueError):
331 return False
332 return d.get('type') == 'link' and os.path.realpath(d.get('source') or '') == os.path.realpath(estensione)
333
334def qwen(casa: str) -> int:
335 if not shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
336 return 3
337 estensione = os.path.join(scrivi(), QWEN)
338 _squadra('qwen', casa)
339 if _qwen_pronto(casa, estensione):
340 return 0
341 try:
342 os.makedirs(casa, exist_ok=True)
343 ambiente = {**os.environ, 'QWEN_HOME': casa}
344 q = os.environ.get('DELMINIO_QWEN') or 'qwen'
345 subprocess.run([q, 'extensions', 'uninstall', NOME], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
346 subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
347 except (OSError, subprocess.TimeoutExpired):
348 return 3
349 return 0 if _qwen_pronto(casa, estensione) else 3
350
351def qwen_via(casa: str) -> int:
352 if os.path.exists(os.path.join(casa, 'extensions', NOME)) and shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
353 try:
354 subprocess.run([os.environ.get('DELMINIO_QWEN') or 'qwen', 'extensions', 'uninstall', NOME], env={**os.environ, 'QWEN_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
355 except (OSError, subprocess.TimeoutExpired):
356 pass
357 return 1 if os.path.exists(os.path.join(casa, 'extensions', NOME)) else 0
358
359def claude_al_lancio(radice: str) -> int:
360 if _acceso(radice):
361 scrivi()
362 return 0
363 try:
364 with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
365 ganci = json.load(h).get('hooks') or {}
366 if any(('delminio.sh' in x.get('command', '') for l in ganci.values() for b in l for x in b.get('hooks', []))):
367 return 0
368 except (OSError, ValueError, AttributeError):
369 pass
370 return claude(radice)
371
372def _squadra(gesto: str, dove: str) -> None:
373 p = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'squadra.py')
374 if not os.path.isfile(p):
375 return
376 try:
377 runpy.run_path(p)[gesto](dove)
378 except Exception:
379 pass
380
381def rimuovi(radice: str) -> int:
382 _squadra('stacca', radice)
383 opencode_via(radice)
384 if shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
385 try:
386 _claude('uninstall', ID, '--scope', 'local', cwd=radice)
387 _claude('marketplace', 'remove', NOME, '--scope', 'local', cwd=radice)
388 except (OSError, subprocess.TimeoutExpired):
389 pass
390 p = os.path.join(radice, '.claude', 'settings.local.json')
391 try:
392 with open(p, encoding='utf-8') as h:
393 s = json.load(h)
394 except (OSError, ValueError):
395 return 0
396 cambiato = False
397 if isinstance(s.get('enabledPlugins'), dict) and ID in s['enabledPlugins']:
398 del s['enabledPlugins'][ID]
399 cambiato = True
400 if not s['enabledPlugins']:
401 del s['enabledPlugins']
402 mercati = s.get('extraKnownMarketplaces')
403 for m in [m for m in mercati or {} if m == NOME] if isinstance(mercati, dict) else []:
404 del mercati[m]
405 cambiato = True
406 if isinstance(mercati, dict) and (not mercati):
407 del s['extraKnownMarketplaces']
408 if cambiato:
409 with open(p + '.nuovo', 'w', encoding='utf-8') as h:
410 h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
411 os.replace(p + '.nuovo', p)
412 return 0
413OPENCODE_PLUGIN = os.path.join('.opencode', 'plugins', 'delminio.js')
414OPENCODE_SORGENTE = os.path.join('.claude', 'opencode.js')
415
416def _nostro_opencode(testo: str) -> bool:
417 return 'delminio.sh' in testo and 'attesa-codex' in testo
418
419def opencode(radice: str) -> int:
420 try:
421 with open(os.path.join(radice, OPENCODE_SORGENTE), encoding='utf-8') as h:
422 testo = h.read()
423 except OSError:
424 return 3
425 riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
426 frasi = {'apertura': F('apertura'), 'chiusura': F('chiusura'), 'ciclo': F('ciclo_opencode'), 'fermo': F('fermo_opencode'), 'v1': F('opencode_v1'), 'permesso': F('permesso_opencode', rifiutati='{rifiutati}', permesso='{permesso}', ammessi='{ammessi}'), 'ammessi': F('ammessi_opencode', elenco='{elenco}')}
427 testo = re.sub('const RITI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const RITI = ' + json.dumps(riti, ensure_ascii=False), testo, count=1)
428 testo = re.sub('const FRASI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const FRASI = ' + json.dumps(frasi, ensure_ascii=False), testo, count=1)
429 dove = os.path.join(radice, OPENCODE_PLUGIN)
430 try:
431 with open(dove, encoding='utf-8') as h:
432 prima = h.read()
433 except OSError:
434 prima = None
435 if prima == testo:
436 return 0
437 if prima is not None and (not _nostro_opencode(prima)):
438 return 3
439 os.makedirs(os.path.dirname(dove), exist_ok=True)
440 with open(dove + '.nuovo', 'w', encoding='utf-8') as h:
441 h.write(testo)
442 os.replace(dove + '.nuovo', dove)
443 return 0
444
445def opencode_via(radice: str) -> None:
446 dove = os.path.join(radice, OPENCODE_PLUGIN)
447 try:
448 with open(dove, encoding='utf-8') as h:
449 if not _nostro_opencode(h.read()):
450 return
451 os.remove(dove)
452 os.rmdir(os.path.dirname(dove))
453 os.rmdir(os.path.dirname(os.path.dirname(dove)))
454 except OSError:
455 pass
456
457def main(argv: list[str]) -> int:
458 if argv[:1] == ['app-codex'] and len(argv) <= 2:
459 quale = argv[1] if len(argv) == 2 else ''
460 if quale == 'stato':
461 print(app_codex_stato())
462 return 0
463 gesti = {'': app_codex, 'allinea': app_codex_allinea, 'via': app_codex_via, 'no': app_codex_no, 'lascia': app_codex_lascia}
464 if quale in gesti:
465 return gesti[quale]()
466 if len(argv) != 2 or argv[0] not in ('claude', 'claude-al-lancio', 'codex', 'qwen', 'qwen-via', 'rimuovi', 'opencode'):
467 print(F('uso'), file=sys.stderr)
468 return 1
469 if argv[0] in ('codex', 'qwen', 'qwen-via'):
470 return {'codex': codex, 'qwen': qwen, 'qwen-via': qwen_via}[argv[0]](os.path.realpath(argv[1]))
471 radice = os.path.realpath(argv[1])
472 return {'claude': claude, 'claude-al-lancio': claude_al_lancio, 'rimuovi': rimuovi, 'opencode': opencode}[argv[0]](radice)
473if __name__ == '__main__':
474 sys.exit(main(sys.argv[1:]))