#!/usr/bin/env python3 # © 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. """Il pacchetto di Delminio per le CLI degli agenti (F776): i ganci, /apertura e""" from __future__ import annotations import hashlib import json import os import re import runpy import shlex import shutil import subprocess import sys NOME = 'delminio' ID = f'{NOME}@{NOME}' SERVER = 'memoria' SERVER_DI_PRIMA = ('delminio', 'delminio-ruolo') TOOL = ('delminio', 'delminio_write') TOOLS_CLAUDE = tuple((f'mcp__plugin_{NOME}_{SERVER}__{t}' for t in TOOL)) TOOLS_CLAUDE_PROGETTO = tuple((f'mcp__{SERVER}__{t}' for t in TOOL)) TOOLS_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)) SKILL_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'} SKILL_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'} CHIEDI_CLAUDE = ('Agent', 'Workflow') SKILL_CODEX_SPENTE = () SKILL_CODEX_F811 = ('imagegen', 'skill-creator', 'skill-installer') COMANDI = { "riti": { "apertura": "apertura", "chiusura": "chiusura", "closing": "chiusura", "handoff": "chiusura", "opening": "apertura", "start": "apertura" } } FRASI = { "descrizione": "Delminio: la memoria del progetto, l'apertura e la chiusura delle sessioni, i messaggi fra gli agenti e i controlli prima di un'azione", "apertura": "Delminio: apri la sessione col briefing del tuo ruolo \u2014 ci\xf2 che scrivi dopo il comando parte come tuo messaggio", "apertura_suggerimento": "[cosa vuoi dirgli subito]", "chiusura": "Delminio: chiudi la sessione \u2014 ci\xf2 che scrivi dopo il comando parte come tuo messaggio", "chiusura_suggerimento": "[cosa fare prima di chiudere]", "ciclo_opencode": "Delminio: \xe8 la terza volta che fai esattamente questa chiamata, e le ultime due hanno avuto la stessa risposta: una quarta non cambier\xe0 niente. Cambia strada, oppure fermati e scrivi a chi ti ha dato il lavoro cosa ti blocca.", "fermo_opencode": "Delminio ha fermato questo giro: il modello ha rifatto la stessa chiamata con la stessa risposta anche dopo tre avvisi. Leggi cosa cercava di fare e riscrivigli cosa vuoi, o cambia modello.", "permesso_opencode": "Delminio: le regole di questo agente non lasciano passare {rifiutati} ({permesso}). In una catena (|, ;, &&) ogni comando si controlla da solo, e ne basta uno fuori dalle regole per fermare tutto; le redirezioni passano.{ammessi} Non riprovare lo stesso comando: lancia da soli quelli che le regole ammettono, o di' a chi ti ha dato il lavoro cosa ti serve.", "ammessi_opencode": " Le regole ammettono: {elenco}.", "opencode_v1": "Delminio non funziona con OpenCode 1: qui non ci sono la memoria del progetto n\xe9 i controlli. Esci e aggiorna a OpenCode 2 con \xabopencode upgrade --major\xbb, poi riapri OpenCode in questo progetto. Al modello: di' alla persona di aggiornare, prima di lavorare.", "uso": "uso: python3 .claude/plugin.py claude|rimuovi|opencode \xb7 codex|qwen \xb7 app-codex [stato|allinea|via|no|lascia]" } def F(chiave: str, **valori) -> str: testo = FRASI[chiave] for k, v in valori.items(): testo = testo.replace('{' + k + '}', str(v)) return testo def cartella() -> str: return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'plugin') GANCI_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}, '')) LUNGO = {'additionalContextLimit': 16000} FINE_CODEX = {'timeout': 3} GANCI_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, '')) GANCI_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}, '')) QWEN = NOME + '-qwen' PERMESSI_CODEX = tuple((f'[plugins."{ID}".mcp_servers.{SERVER}.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL)) PERMESSI_CODEX_DI_PRIMA = tuple((f'[plugins."{ID}".mcp_servers.delminio.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL)) def _permessi_codex(conf: str) -> None: with open(conf, encoding='utf-8') as h: testo = h.read() nuovo = testo for b in PERMESSI_CODEX_DI_PRIMA: nuovo = nuovo.replace('\n' + b, '').replace(b, '') if (mancano := [b for b in PERMESSI_CODEX if b not in nuovo]): nuovo = nuovo.rstrip('\n') + '\n\n' + '\n'.join(mancano) if nuovo != testo: with open(conf + '.nuovo', 'w', encoding='utf-8') as h: h.write(nuovo) os.replace(conf + '.nuovo', conf) LANCIATORE = '#!/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' def _skill(nome: str, descrizione: str, suggerimento: str, comando: str) -> str: 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' def ganci(chiama: str, lista, matcher_sempre: bool=False) -> dict: g: dict = {} for evento, gesto, extra, matcher in lista: g.setdefault(evento, []).append({**({'matcher': matcher} if matcher or matcher_sempre else {}), 'hooks': [{'type': 'command', 'command': f'{chiama} {gesto}', **extra}]}) return g def contenuti(radice_pacchetto: str) -> dict[str, str]: lanciatore = os.path.join(radice_pacchetto, NOME, 'bin', 'delminio') chiama = 'bash ' + shlex.quote(lanciatore) server = {'command': 'bash', 'args': [lanciatore, 'ponte']} 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'} riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'} for nome, rito in sorted(riti.items()): 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" qwen_server = {**server, 'timeout': 60000, 'trust': True, 'alwaysLoadTools': True} apre = (F('apertura'), F('apertura_suggerimento'), f'{chiama} prompt') chiude = (F('chiusura'), F('chiusura_suggerimento'), f'{chiama} chiusura') for nome, rito in sorted(riti.items()): f[os.path.join(NOME, 'skills', nome, 'SKILL.md')] = _skill(nome, *(apre if rito == 'apertura' else chiude)) impronta = hashlib.sha256(''.join((k + v for k, v in sorted(f.items()))).encode()).hexdigest() versione = f'1.0.{int(impronta[:7], 16)}' f[os.path.join(NOME, '.claude-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione')}, ensure_ascii=False, indent=2) + '\n' 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' f[os.path.join(NOME, 'skills-codex', '.vuota')] = '' 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' 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' 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' return f def scrivi() -> str: radice = cartella() for rel, testo in contenuti(radice).items(): p = os.path.join(radice, rel) try: with open(p, encoding='utf-8') as h: if h.read() == testo: continue except OSError: pass os.makedirs(os.path.dirname(p), exist_ok=True) with open(p + '.nuovo', 'w', encoding='utf-8') as h: h.write(testo) if rel.endswith(os.path.join('bin', 'delminio')): os.chmod(p + '.nuovo', 493) os.replace(p + '.nuovo', p) return radice def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess: return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) def _acceso(radice: str) -> bool: try: with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h: return (json.load(h).get('enabledPlugins') or {}).get(ID) is True except (OSError, ValueError, AttributeError): return False def claude(radice: str) -> int: if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'): return 3 try: if _claude('--help', cwd=radice).returncode != 0: return 3 pacchetto = scrivi() _claude('marketplace', 'add', pacchetto, '--scope', 'local', cwd=radice) _claude('install', ID, '--scope', 'local', cwd=radice) if not _acceso(radice): _claude('enable', ID, '--scope', 'local', cwd=radice) except (OSError, subprocess.TimeoutExpired): return 3 return 0 if _acceso(radice) else 3 def _versione() -> str: return json.loads(contenuti(cartella())[os.path.join(NOME, '.codex-plugin', 'plugin.json')])['version'] def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess: 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) def _codex_pronto(casa: str) -> bool: try: with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h: conf = h.read() except OSError: return False acceso = re.search('^\\[plugins\\."' + re.escape(ID) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M) 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())) def _skill_codex(casa: str) -> None: conf = os.path.join(casa, 'config.toml') try: with open(conf, encoding='utf-8') as h: testo = h.read() except FileNotFoundError: testo = '' except OSError: return prima = testo segno = os.path.join(casa, 'delminio-skill-f844') if testo and (not os.path.exists(segno)): for nome in SKILL_CODEX_F811: percorso = json.dumps(os.path.join(casa, 'skills', '.system', nome, 'SKILL.md')) testo = re.sub('(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(percorso) + '\\s*\\nenabled\\s*=\\s*false\\s*\\n?\\n?', '', testo) blocchi = [] for nome in SKILL_CODEX_SPENTE: percorso = os.path.join(casa, 'skills', '.system', nome, 'SKILL.md') if json.dumps(percorso) not in testo: blocchi.append(f'[[skills.config]]\npath = {json.dumps(percorso)}\nenabled = false\n') try: os.makedirs(casa, exist_ok=True) if blocchi or testo != prima: with open(conf + '.nuovo', 'w', encoding='utf-8') as h: h.write((testo.rstrip('\n') + '\n\n' if testo.strip() else '') + '\n'.join(blocchi) if blocchi else testo) os.replace(conf + '.nuovo', conf) if not os.path.exists(segno): open(segno, 'w').close() except OSError: pass def codex(casa: str) -> int: if not shutil.which(os.environ.get('DELMINIO_CODEX') or 'codex'): return 3 pacchetto = scrivi() _skill_codex(casa) _squadra('codex', casa) if _codex_pronto(casa): return 0 try: os.makedirs(casa, exist_ok=True) _codex(casa, 'marketplace', 'add', pacchetto) _codex(casa, 'remove', ID) _codex(casa, 'add', ID) _permessi_codex(os.path.join(casa, 'config.toml')) except (OSError, subprocess.TimeoutExpired): return 3 return 0 if _codex_pronto(casa) else 3 APP_CODEX = ('/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '~/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '/usr/lib/chatgpt/resources/codex') def app_codex_cli() -> str: return next((p for p in map(os.path.expanduser, APP_CODEX) if os.access(p, os.X_OK)), '') def _casa_app() -> str: return os.path.expanduser('~/.codex') def _no_app() -> str: return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio', 'app-codex-no') def _app_scelta(casa: str) -> bool: try: with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h: return bool(re.search('^\\[marketplaces\\.' + re.escape(NOME) + '\\]', h.read(), re.M)) except OSError: return False def app_codex_stato() -> str: if not app_codex_cli(): return '' if _app_scelta(_casa_app()): return 'dentro' return 'no' if os.path.exists(_no_app()) else 'manca' def app_codex() -> int: cli = app_codex_cli() if not cli: return 4 casa = _casa_app() vecchio = os.environ.get('DELMINIO_CODEX') os.environ['DELMINIO_CODEX'] = cli try: pacchetto = scrivi() if not _codex_pronto(casa): os.makedirs(casa, exist_ok=True) _codex(casa, 'marketplace', 'add', pacchetto) _codex(casa, 'remove', ID) _codex(casa, 'add', ID) _permessi_codex(os.path.join(casa, 'config.toml')) except (OSError, subprocess.TimeoutExpired): return 3 finally: if vecchio is None: os.environ.pop('DELMINIO_CODEX', None) else: os.environ['DELMINIO_CODEX'] = vecchio try: os.remove(_no_app()) except OSError: pass return 0 if _codex_pronto(casa) else 3 def app_codex_allinea() -> int: if app_codex_cli() and _app_scelta(_casa_app()) and (not _codex_pronto(_casa_app())): return app_codex() return 0 def app_codex_via() -> int: casa = _casa_app() cli = app_codex_cli() or shutil.which('codex') or '' if cli: vecchio = os.environ.get('DELMINIO_CODEX') os.environ['DELMINIO_CODEX'] = cli try: _codex(casa, 'remove', ID) _codex(casa, 'marketplace', 'remove', NOME) except (OSError, subprocess.TimeoutExpired): pass finally: if vecchio is None: os.environ.pop('DELMINIO_CODEX', None) else: os.environ['DELMINIO_CODEX'] = vecchio conf = os.path.join(casa, 'config.toml') try: with open(conf, encoding='utf-8') as h: testo = h.read() except OSError: return 0 nuovo = testo for b in PERMESSI_CODEX + PERMESSI_CODEX_DI_PRIMA: nuovo = nuovo.replace('\n' + b, '').replace(b, '') for intestazione in (f'[plugins."{ID}"]', f'[marketplaces.{NOME}]'): nuovo = re.sub('(?ms)^' + re.escape(intestazione) + '\\n.*?(?=^\\[|\\Z)', '', nuovo) if nuovo != testo: with open(conf + '.nuovo', 'w', encoding='utf-8') as h: h.write(nuovo.rstrip('\n') + '\n') os.replace(conf + '.nuovo', conf) return 0 if not _app_scelta(casa) else 3 def app_codex_lascia() -> int: try: os.remove(_no_app()) except OSError: pass if not _app_scelta(_casa_app()): return 0 return 2 if app_codex_via() == 0 else 3 def app_codex_no() -> int: os.makedirs(os.path.dirname(_no_app()), exist_ok=True) with open(_no_app(), 'w', encoding='utf-8') as h: h.write('no\n') return 0 def _qwen_pronto(casa: str, estensione: str) -> bool: try: with open(os.path.join(casa, 'extensions', NOME, '.qwen-extension-install.json'), encoding='utf-8') as h: d = json.load(h) except (OSError, ValueError): return False return d.get('type') == 'link' and os.path.realpath(d.get('source') or '') == os.path.realpath(estensione) def qwen(casa: str) -> int: if not shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'): return 3 estensione = os.path.join(scrivi(), QWEN) _squadra('qwen', casa) if _qwen_pronto(casa, estensione): return 0 try: os.makedirs(casa, exist_ok=True) ambiente = {**os.environ, 'QWEN_HOME': casa} q = os.environ.get('DELMINIO_QWEN') or 'qwen' subprocess.run([q, 'extensions', 'uninstall', NOME], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n') except (OSError, subprocess.TimeoutExpired): return 3 return 0 if _qwen_pronto(casa, estensione) else 3 def qwen_via(casa: str) -> int: if os.path.exists(os.path.join(casa, 'extensions', NOME)) and shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'): try: 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) except (OSError, subprocess.TimeoutExpired): pass return 1 if os.path.exists(os.path.join(casa, 'extensions', NOME)) else 0 def claude_al_lancio(radice: str) -> int: if _acceso(radice): scrivi() return 0 try: with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h: ganci = json.load(h).get('hooks') or {} if any(('delminio.sh' in x.get('command', '') for l in ganci.values() for b in l for x in b.get('hooks', []))): return 0 except (OSError, ValueError, AttributeError): pass return claude(radice) def _squadra(gesto: str, dove: str) -> None: p = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'squadra.py') if not os.path.isfile(p): return try: runpy.run_path(p)[gesto](dove) except Exception: pass def rimuovi(radice: str) -> int: _squadra('stacca', radice) opencode_via(radice) if shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'): try: _claude('uninstall', ID, '--scope', 'local', cwd=radice) _claude('marketplace', 'remove', NOME, '--scope', 'local', cwd=radice) except (OSError, subprocess.TimeoutExpired): pass p = os.path.join(radice, '.claude', 'settings.local.json') try: with open(p, encoding='utf-8') as h: s = json.load(h) except (OSError, ValueError): return 0 cambiato = False if isinstance(s.get('enabledPlugins'), dict) and ID in s['enabledPlugins']: del s['enabledPlugins'][ID] cambiato = True if not s['enabledPlugins']: del s['enabledPlugins'] mercati = s.get('extraKnownMarketplaces') for m in [m for m in mercati or {} if m == NOME] if isinstance(mercati, dict) else []: del mercati[m] cambiato = True if isinstance(mercati, dict) and (not mercati): del s['extraKnownMarketplaces'] if cambiato: with open(p + '.nuovo', 'w', encoding='utf-8') as h: h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n') os.replace(p + '.nuovo', p) return 0 OPENCODE_PLUGIN = os.path.join('.opencode', 'plugins', 'delminio.js') OPENCODE_SORGENTE = os.path.join('.claude', 'opencode.js') def _nostro_opencode(testo: str) -> bool: return 'delminio.sh' in testo and 'attesa-codex' in testo def opencode(radice: str) -> int: try: with open(os.path.join(radice, OPENCODE_SORGENTE), encoding='utf-8') as h: testo = h.read() except OSError: return 3 riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'} 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}')} testo = re.sub('const RITI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const RITI = ' + json.dumps(riti, ensure_ascii=False), testo, count=1) testo = re.sub('const FRASI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const FRASI = ' + json.dumps(frasi, ensure_ascii=False), testo, count=1) dove = os.path.join(radice, OPENCODE_PLUGIN) try: with open(dove, encoding='utf-8') as h: prima = h.read() except OSError: prima = None if prima == testo: return 0 if prima is not None and (not _nostro_opencode(prima)): return 3 os.makedirs(os.path.dirname(dove), exist_ok=True) with open(dove + '.nuovo', 'w', encoding='utf-8') as h: h.write(testo) os.replace(dove + '.nuovo', dove) return 0 def opencode_via(radice: str) -> None: dove = os.path.join(radice, OPENCODE_PLUGIN) try: with open(dove, encoding='utf-8') as h: if not _nostro_opencode(h.read()): return os.remove(dove) os.rmdir(os.path.dirname(dove)) os.rmdir(os.path.dirname(os.path.dirname(dove))) except OSError: pass def main(argv: list[str]) -> int: if argv[:1] == ['app-codex'] and len(argv) <= 2: quale = argv[1] if len(argv) == 2 else '' if quale == 'stato': print(app_codex_stato()) return 0 gesti = {'': app_codex, 'allinea': app_codex_allinea, 'via': app_codex_via, 'no': app_codex_no, 'lascia': app_codex_lascia} if quale in gesti: return gesti[quale]() if len(argv) != 2 or argv[0] not in ('claude', 'claude-al-lancio', 'codex', 'qwen', 'qwen-via', 'rimuovi', 'opencode'): print(F('uso'), file=sys.stderr) return 1 if argv[0] in ('codex', 'qwen', 'qwen-via'): return {'codex': codex, 'qwen': qwen, 'qwen-via': qwen_via}[argv[0]](os.path.realpath(argv[1])) radice = os.path.realpath(argv[1]) return {'claude': claude, 'claude-al-lancio': claude_al_lancio, 'rimuovi': rimuovi, 'opencode': opencode}[argv[0]](radice) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))