#!/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. """Gli eseguibili di Delminio su questa macchina, in pari col registro.""" import argparse import base64 import collections import datetime import difflib import hashlib import io import json import math import os import platform import re import runpy import shlex import shutil import socket import subprocess import sys import tarfile import tempfile import time import urllib.error import urllib.parse import urllib.request try: import fcntl except ImportError: fcntl = None RILASCI = 'https://downloads.claude.ai/claude-code-releases' CANALI = {'stabile': 'stable', 'latest': 'latest'} CODEX_RILASCI = 'https://releases.openai.com/codex/releases' CODEX_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'} NODE_QWEN = '22.23.4' CLI_NOMI = {'claude': 'Claude Code', 'codex': 'Codex', 'qwen': 'Qwen Code', 'opencode': 'OpenCode'} SERVER_RUOLO = 'memoria-ruolo' NODE_RILASCI = 'https://nodejs.org/dist' NODE_TARGET = {'linux-x64': 'linux-x64', 'linux-arm64': 'linux-arm64', 'darwin-x64': 'darwin-x64', 'darwin-arm64': 'darwin-arm64'} _VERSIONE = re.compile('^\\d+\\.\\d+\\.\\d+$') _NOME_OK = re.compile('[A-Za-z0-9][A-Za-z0-9._-]{0,63}') FRASI = { "modello_gratuito_nessuno": "none of the {n} free OpenCode models answers right now: a provider's key is needed", "modello_gratuito_risposta": "ready", "modello_gratuito_domanda": "Answer only with the word: ready", "modello_gratuito_uso": "usage: modello-gratuito ", "installa_agente_uso": "usage: installa-agente claude|codex|qwen|opencode ", "installa_agente_no": "{cli} did not install: {errore}", "skill_riferite": "\U0001f9e9 This machine's skills told to Delminio, with commands, agents and MCP servers: {n}; the Skills view choices applied: {scelte}.", "posta_arrivata": "\U0001f4ec Delminio: a message has arrived from another session \u2014 you'll find it below.", "riga_senza_numero": "the {cli} row doesn't have a version number yet: save it again in the Agents view", "non_versione": "\u201c{versione}\u201d isn't a version", "senza_cli_ufficiale": "this machine ({sistema}) has no official CLI: Linux or macOS (on Windows, inside WSL)", "versione_assente": "version {versione} doesn't exist for {piattaforma}", "scarico_cli": " downloading CLI {versione} for {piattaforma} ({mb} MB)\u2026", "checksum_cli": "the checksum of CLI {versione} doesn't match: I won't install it", "senza_codex_ufficiale": "this machine ({sistema}) has no official Codex: Linux or macOS (on Windows, inside WSL)", "codex_senza_pacchetto": "Codex version {versione} has no package for {piattaforma}", "scarico_codex": " downloading Codex {versione} for {piattaforma}\u2026", "digest_codex": "the digest of Codex {versione} doesn't match: I won't install it", "pacchetto_fuori": "the {chi} package reaches outside its folder: I won't install it", "codex_senza_binario": "there's no bin/codex in the Codex {versione} package", "senza_node_ufficiale": "this machine ({sistema}) has no official Node for Qwen Code: Linux or macOS with glibc (on Windows, inside WSL)", "node_senza_pacchetto": "Node {versione} has no package for {piattaforma}", "scarico_node": " downloading Node {versione} for Qwen Code\u2026", "checksum_node": "the checksum of Node {versione} doesn't match: I won't install it", "installo_qwen": " installing Qwen Code {versione}\u2026", "installo_opencode": " installing OpenCode {versione}\u2026", "opencode_integrita": "OpenCode {versione}: the package does not match the npm registry integrity, and is not installed", "opencode_senza_binario": "the OpenCode {versione} package has no bin/opencode", "opencode_solo_v2": "OpenCode {versione} is version 1, which Delminio no longer supports: choose a version 2 in the Agents view", "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.", "commento_config_opencode": "The OpenCode configuration for this agent: provider and model, no self-updates. The client adds the role prompt at launch.", "qwen_non_installato": "Qwen Code {versione} didn't install: {perche}", "npm_muto": "npm silent", "cosa_posta_ruolo": "the agent role's messages", "settings_file": "\u26a0\ufe0f this row's --settings are a file: {cosa} doesn't fit in", "cosa_ricerca_spenta": "web search switched off", "rito_apertura_descrizione": "Opens the session with the user: Delminio brings you your role's steps", "rito_apertura_corpo": "I'm opening the session.", "rito_chiusura_descrizione": "Ends the session with the user: Delminio brings you your role's steps", "rito_chiusura_corpo": "I'm ending the session.", "rito_plugin": "/opening and /closing for agents with a Delminio agent role", "rito_negato": "\u26a0\ufe0f Delminio didn't provide the text of /{parola}: {perche}. Tell the user.", "rito_muto": "\u26a0\ufe0f Delminio is not responding: the text of /{parola} didn't arrive. Tell the user.", "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.", "chiudi_niente": "nothing new to put in the history", "chiudi_nella_storia": "\u2705 in the history: {commit}", "chiudi_senza_repo": "your workspace has no repository to send it to: the history stays here", "chiudi_mandata": "\u2705 sent to its repository", "chiudi_push_fallito": "\u26a0\ufe0f the push didn't go through, tell the user: {errore}", "non_si_clona": "can't be cloned", "pull_fallito": "the pull didn't go through", "altri_file": "- \u2026 and {n} more files", "repo_ruolo_lontano_nuova": "the agent role's repository ({repo}) can't be reached from here: the history stays in the workspace", "repo_ruolo_cambiato": "the agent role's repository has changed: now {repo}", "repo_ruolo_lontano": "the agent role's repository can't be reached from here: you're working on the previous workspace", "casa_ferma": "the workspace doesn't update from its repository: you're working on the previous one", "uso_casa": "usage: casa []", "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.", "casa_non_detta": "\u26a0\ufe0f {agente}: Delminio didn't say where the workspace is ({errore}): you're working on the previous one.", "casa_senza_repo": "\u26a0\ufe0f {agente}: Delminio didn't say which repositories the agent role sees ({errore}): the workspace isn't created.", "novita_titolo": "What has changed", "novita_uscito": "Your agent role doesn't see it any more: it has left the workspace.", "novita_non_si_clona": "\u26a0\ufe0f It can't be cloned from this machine ({repo}): {perche}. Tell the user.", "novita_copia_repo": "The copy was created just now: it's the repository as it is.", "avviso_non_si_clona": "{repo} can't be cloned: {perche}", "avviso_non_si_aggiorna": "{repo} doesn't update: {perche}", "novita_non_si_aggiorna": "\u26a0\ufe0f It doesn't update ({perche}): you're working on the previous copy.", "novita_niente": "Nothing new since last time.", "novita_uscito_spazio": "(The repository \u201c{repo}\u201d no longer belongs to the space: it isn't copied.)", "copia_progetto_ferma": "the project's copy doesn't update: {perche}", "progetto_non_si_copia": "\u26a0\ufe0f {agente}: I can't copy the project into {casa}", "novita_copia_progetto": "The copy was created just now: it's the project as it is, in the progetto/ folder.", "novita_al_tecnico": "To tell the user", "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.", "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.", "prompt_negato": "\u26a0\ufe0f {nome}: Delminio didn't provide the system prompt of the agent role \u201c{porta}\u201d (HTTP {codice}).", "commento_hook_sistema": "The hooks read it: the rules are already at the top.", "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", "wrapper_descrizione_serie": "a Delminio command", "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.", "commento_login_codex": "The login belongs to the person: that of their Codex, with a link (never a copy).", "wrapper_senza_repo": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone.", "fornitore_ignoto": "this Delminio doesn't know the Qwen Code provider \u201c{fornitore}\u201d", "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.", "commento_settings_qwen": "Qwen Code's settings for this agent: provider and model, and nothing that talks to Alibaba.", "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.", "mie_qwen_illeggibili": "\u26a0\ufe0f {file} is not valid JSON, and the agent starts with Delminio's settings only: {errore}", "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.", "mie_di_delminio": "\u26a0\ufe0f {nome} stays Delminio's: in your settings it does not count, and the agent uses Delminio's.", "mie_della_riga": "\u26a0\ufe0f {nome} is chosen by the agent (Agents view): in your settings it does not count.", "mie_codex_illeggibili": "\u26a0\ufe0f {file} cannot be read as TOML, and the agent starts with Delminio's settings only: {errore}", "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})", "mie_codex_scontro": "\u26a0\ufe0f {file} clashes with the configuration Delminio prepares for Codex, and the agent starts without your settings: {errore}", "mie_toml_chiave": "line {riga}: a key or a header is needed here", "mie_toml_aperta": "line {riga}: a multi-line string that never closes", "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\".", "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.", "commento_casa": "The isolated workspace: the repositories its agent role sees, up to date, and `consegne/` where it writes.", "commento_autoupdater": "the version is decided by the register, not by the CLI", "commento_catalogo_opencode": "the model list is the one built into OpenCode: no requests to models.opencode.ai", "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).", "wrapper_senza_repo_claude": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone, or open claude.", "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.", "spazio_principale": "main", "pulizia": " clean-up: removed {n} versions ({tolte}), kept {tenute}{riparo}", "potate": " versions nobody uses, deleted: {tolte}", "errori_testa": "Tool calls that failed on this computer in the last {giorni} days: {n} (the log: {file})", "errori_nascosti": " {n} are not errors (an Esc, a command that says no by design): --tutti shows them", "errori_nessuno": " none.", "errori_per_specie": "By kind:", "errori_per_programma": "By tool and program:", "errori_ultime": "The latest:", "nessuna": "none", "al_riparo": " (rollback version: {versione})", "installo_chiesta": " the admin asks for {cli} on this machine: installing it", "prova_strumento": "Counts the letters of a word.", "prova_chiedi": "Use the conta_lettere tool on the word \u201cDelminio\u201d. Don't answer in words.", "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.", "prova_senza_chiave": "the key is missing: put it in the environment as {variabile}=\u2026 and start again", "prova_sistema": "You are an assistant that uses tools.", "prova_chiave_rifiutata": "the provider rejects the key ({codice}): {testo}", "prova_strumento_errore": "the request with the tool answers {codice}", "prova_ok": "Reply only: ok.", "prova_senza_strumento": "the model didn't call the tool: it can't work with Delminio", "prova_contesto_stretto": "context of {contesto} tokens: tight", "prova_cache_muta": "the provider doesn't say what it reads from the cache", "aiuto_descrizione": "Delminio's commands on this machine, synced with the register.", "aiuto_nomi": "for rinomina: the old and the new", "aiuto_da": "for the space: the .claude/delminio.sh client of a connected project", "aiuto_converti": "with --modo kit, also rewrites the wrappers written with `--modo casa`", "aiuto_vuoi": "the CLI the person chose when connecting: it is installed even if it is not here", "aiuto_primo": "a file to write the command of that CLI's first agent into, to launch it", "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.", "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", "servono_url_token": "--url and --token-file (or --da) are needed", "rifiutati": "noted: Delminio's commands are no longer offered on this machine", "lasciati": " this space's commands: {n} removed from this machine", "registro_muto": "\u26a0\ufe0f the command register doesn't arrive from {url}: {errore}", "nomi_fuori_forma": "\u26a0\ufe0f register rows with a malformed name, skipped: {nomi}", "uso_prova": "prova NAME \u2014 the name of a Qwen Code agent in the register (Agents view)", "prova_inizio_locale": "Test of {nome} ({modello}): three requests to the local server\u2026", "prova_inizio_fornitore": "Test of {nome} ({modello}): three requests to the provider, a few cents\u2026", "prova_non_fatta": "\u26a0\ufe0f the test didn't run: {errore}", "prova_riga_strumenti": " tools: {valore}", "prova_si": "yes", "prova_no": "NO", "prova_riga_cache": " cache: {valore}", "prova_cache_non_detta": "the provider doesn't say", "prova_cache_letti": "{letti} tokens read out of {totale}", "prova_riga_contesto": " context: {valore}", "prova_non_lo_dice": "doesn't say", "prova_riga_verdetto": " verdict: {valore}{nota}", "prova_va": "works", "prova_senza_cache": "works, but without cache: every request is paid in full", "prova_non_va": "doesn't work", "verdetto_perso": "\u26a0\ufe0f the verdict didn't reach Delminio: {errore}", "uso_rinomina": "rinomina OLD NEW", "rinomina_assente": "\u274c \u201c{nome}\u201d isn't in the register", "rinomina_rifiutata": "\u274c Delminio won't rename: {errore}", "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", "stato_assente": "missing", "stato_cambiato": "changed by its user: it stays theirs", "stato_non_suo": "present, but not Delminio's", "stato_intatto": "untouched", "stato_altro_spazio": "untouched, but it's the command of another space ({spazi})", "stato_riga": "{nome}: CLI {versione}{da_scaricare} \xb7 {modello} \xb7 role {porta} \xb7 {stato}", "da_scaricare": " (to download)", "modello_di_serie": "default model", "stato_rifiutato": "the user said they don't want them on this machine (allinea writes them anyway)", "registro_vuoto": "the register is empty: no commands", "allinea_in_corso": " another sync is in progress on this machine: I'll let it finish", "al_lancio": "\u23f3 The Agents view has changed: updating the agent commands before starting\u2026", "al_lancio_attesa": "\u23f3 a sync is already running on this machine: waiting for it to finish, then starting on the new version\u2026", "senza_cli_qui": " {nome}: {cli} isn't on this machine, I won't download it", "passo_controllo": "{nome}: checking {cli} {versione}", "passo_scarico": "{nome}: downloading {cli} {versione}, {mb} MB", "passo_di": " of {mb}", "non_di_delminio": "\u274c {percorso} already exists and isn't Delminio's: choose another name in the Agents view.", "toccato_resta": " {percorso}: changed by its user, it stays as it is", "smista_testa": "agent of more than one space on this machine: the folder you launch it from decides the space", "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.", "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.", "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.", "scritto": "\u2705 {percorso}: written (CLI {versione})", "aggiornato": "\u2705 {percorso}: updated, CLI {prima} \u2192 {versione}", "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)", "passo_scritto": "{nome}: written, {cli} {versione}", "lasciato_ad_altri": " {percorso}: this space lets it go, it stays for {spazi}", "tolto": " {percorso}: removed, it's no longer in the register", "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.", "wrapper_chiave_negata": "\u26a0\ufe0f {nome}: Delminio won't give me the key \u201c{scelta}\u201d chosen in the Agents view. The answer:", "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.", "commento_chiave_di_qwen": "The key given to Qwen Code at its first start, if the environment doesn't have it.", "prova_chiave_negata": "Delminio won't give the key \u201c{scelta}\u201d chosen in the Agents view: {errore}", "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.", "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.", "commento_plugin_codex": "Delminio's plugin in this agent's Codex folder: the hooks come from there.", "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.", "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.", "porto_troppo": "\U0001f4e6 \u201c{cartella}\u201d is too big for the team: at most {file} files and {peso} bytes of text.", "porto_fatto": "\U0001f4e6 \u201c{nome}\u201d is in the team: from the next start every agent gets it.", "porto_no": "\U0001f4e6 \u201c{cartella}\u201d stays out of the team: {errore}", "squadra_muta": "\U0001f465 The team skills did not arrive ({errore}): the previous ones stay, and it retries at the next start.", "squadra_qui": "\U0001f465 The team on this computer, in the \u201c{plugin}\u201d plugin: {skill} skills, {comandi} commands, {agenti} agents, {mcp} MCP servers.", "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).", "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", "accetta_senza_terminale": "delminio accept runs from a terminal: an agent can't accept on your behalf.", "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] ", "accetta_si": "y yes s si s\xec", "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." } def F(chiave, **sost): t = FRASI.get(chiave, chiave) for k, v in sost.items(): t = t.replace('{' + k + '}', str(v)) return t def _esc(t): return re.sub('([\\\\"$`])', '\\\\\\1', t) def _sh(t, **codice): q = '"' + _esc(t) + '"' for k, v in codice.items(): q = q.replace('{' + k + '}', v) return q def _printf(t, **args): ordine = sorted(((t.index('{' + k + '}'), k) for k in args if '{' + k + '}' in t)) fmt = _esc(t.replace('%', '%%')) for k in args: fmt = fmt.replace('{' + k + '}', '%s') return f'printf "{fmt}\\n" ' + ' '.join((args[k] for _, k in ordine)) def _commento(testo): return ['# ' + r for r in testo.split('\n')] def _v(t): return tuple((int(x) for x in t.split('.'))) def _get(url, token=None, timeout=30, metodo='GET', corpo=None, nome=False): h = {'Authorization': f'Bearer {token}'} if token else {} if nome: h['User-Agent'] = 'delminio-eseguibili' dati = None if corpo is not None: dati, h['Content-Type'] = (json.dumps(corpo).encode(), 'application/json') req = urllib.request.Request(url, data=dati, headers=h, method=metodo) with urllib.request.urlopen(req, timeout=timeout) as r: return r.read() def _scarica(url, timeout, su=None, nome=False): h = {'User-Agent': 'delminio-eseguibili'} if nome else {} with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r: totale = int(r.headers.get('Content-Length') or 0) pezzi, fatti, detti = ([], 0, 0) while True: pezzo = r.read(1 << 20) if not pezzo: break pezzi.append(pezzo) fatti += len(pezzo) if su and fatti - detti >= 4 << 20: detti = fatti su(fatti, totale) return b''.join(pezzi) def piattaforma(): s, m = (platform.system().lower(), platform.machine().lower()) arch = {'x86_64': 'x64', 'amd64': 'x64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(m) if s not in ('linux', 'darwin') or not arch: return None p = f'{s}-{arch}' if s == 'linux': try: ldd = subprocess.run(['ldd', '--version'], capture_output=True, text=True).stdout ldd += subprocess.run(['ldd', '--version'], capture_output=True, text=True).stderr except OSError: ldd = '' if 'musl' in ldd.lower() or any((f.startswith('ld-musl-') for f in os.listdir('/lib') if os.path.isdir('/lib'))): p += '-musl' return p def versione_voluta(riga, canali): v = riga['versione'] if v in CANALI and _VERSIONE.match(str(riga.get('versione_oggi') or '')): v = riga['versione_oggi'] if v in CANALI and riga.get('cli') != 'claude': chi = CLI_NOMI.get(riga.get('cli'), riga.get('cli')) raise RuntimeError(F('riga_senza_numero', cli=chi)) if v in CANALI: if v not in canali: canali[v] = _get(f'{RILASCI}/{CANALI[v]}', timeout=15).decode().strip() v = canali[v] if riga.get('minimo') and _VERSIONE.match(riga['minimo']) and _VERSIONE.match(v) and (_v(v) < _v(riga['minimo'])): v = riga['minimo'] if not _VERSIONE.match(v): raise RuntimeError(F('non_versione', versione=v)) return v def assicura_cli(versione, cartella, prova, su=None): if prova: return prova dove = os.path.join(cartella, versione) if os.path.isfile(dove) and os.access(dove, os.X_OK): return dove p = piattaforma() if not p: raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}')) manifesto = json.loads(_get(f'{RILASCI}/{versione}/manifest.json', timeout=20)) voce = (manifesto.get('platforms') or {}).get(p) if not voce: raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p)) print(F('scarico_cli', versione=versione, piattaforma=p, mb=voce.get('size', 0) // 1000000), flush=True) dati = _scarica(f"{RILASCI}/{versione}/{p}/{voce.get('binary', 'claude')}", 600, su=su) if hashlib.sha256(dati).hexdigest() != voce.get('checksum'): raise RuntimeError(F('checksum_cli', versione=versione)) os.makedirs(cartella, exist_ok=True) with open(dove + '.nuovo', 'wb') as f: f.write(dati) os.chmod(dove + '.nuovo', 493) os.replace(dove + '.nuovo', dove) return dove def assicura_codex(versione, cartella, prova, su=None): if prova: return prova dove = os.path.join(cartella, versione) binario = os.path.join(dove, 'bin', 'codex') if os.path.isfile(binario) and os.access(binario, os.X_OK): return binario target = CODEX_TARGET.get(piattaforma() or '') if not target: raise RuntimeError(F('senza_codex_ufficiale', sistema=f'{platform.system()} {platform.machine()}')) rilascio = json.loads(_get(f'{CODEX_RILASCI}/{versione}/release.json', timeout=20, nome=True)) nome = f'codex-package-{target}.tar.gz' voce = next((x for x in rilascio.get('assets') or [] if x.get('name') == nome), None) if not voce or not str(voce.get('digest') or '').startswith('sha256:'): raise RuntimeError(F('codex_senza_pacchetto', versione=versione, piattaforma=target)) print(F('scarico_codex', versione=versione, piattaforma=target), flush=True) dati = _scarica(f'{CODEX_RILASCI}/{versione}/{nome}', 600, su=su, nome=True) if hashlib.sha256(dati).hexdigest() != voce['digest'].split(':', 1)[1]: raise RuntimeError(F('digest_codex', versione=versione)) tappa = dove + '.nuovo' shutil.rmtree(tappa, ignore_errors=True) os.makedirs(cartella, exist_ok=True) with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t: for m in t.getmembers(): fuori = lambda x: x.startswith('/') or '..' in x.split('/') if fuori(m.name) or m.islnk() or m.isdev() or (m.issym() and fuori(m.linkname)): raise RuntimeError(F('pacchetto_fuori', chi=f'Codex {versione}')) t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {}) if not os.path.isfile(os.path.join(tappa, 'bin', 'codex')): shutil.rmtree(tappa, ignore_errors=True) raise RuntimeError(F('codex_senza_binario', versione=versione)) for f in ('bin/codex', 'bin/codex-code-mode-host', 'codex-path/rg', 'codex-resources/bwrap'): if os.path.isfile(os.path.join(tappa, f)): os.chmod(os.path.join(tappa, f), 493) shutil.rmtree(dove, ignore_errors=True) os.replace(tappa, dove) return binario def _estrai(dati, tappa, chi): with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t: for m in t.getmembers(): dentro = os.path.normpath(m.name) if m.name.startswith('/') or dentro.startswith('..') or m.islnk() or m.isdev(): raise RuntimeError(F('pacchetto_fuori', chi=chi)) if m.issym(): dove = os.path.normpath(os.path.join(os.path.dirname(dentro), m.linkname)) if m.linkname.startswith('/') or dove.startswith('..'): raise RuntimeError(F('pacchetto_fuori', chi=chi)) t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {}) def node_di(versioni_qwen): return os.path.join(os.path.dirname(os.path.normpath(versioni_qwen)), f'node-{NODE_QWEN}') def assicura_node(versioni_qwen, su=None): dove = node_di(versioni_qwen) if os.access(os.path.join(dove, 'bin', 'node'), os.X_OK): return dove target = NODE_TARGET.get(piattaforma() or '') if not target: raise RuntimeError(F('senza_node_ufficiale', sistema=f'{platform.system()} {platform.machine()}')) nome = f'node-v{NODE_QWEN}-{target}' somme = _get(f'{NODE_RILASCI}/v{NODE_QWEN}/SHASUMS256.txt', timeout=20).decode() attesa = next((r.split()[0] for r in somme.splitlines() if r.endswith(f' {nome}.tar.gz')), '') if not attesa: raise RuntimeError(F('node_senza_pacchetto', versione=NODE_QWEN, piattaforma=target)) print(F('scarico_node', versione=NODE_QWEN), flush=True) dati = _scarica(f'{NODE_RILASCI}/v{NODE_QWEN}/{nome}.tar.gz', 600, su=su) if hashlib.sha256(dati).hexdigest() != attesa: raise RuntimeError(F('checksum_node', versione=NODE_QWEN)) tappa = dove + '.nuovo' shutil.rmtree(tappa, ignore_errors=True) os.makedirs(tappa) _estrai(dati, tappa, f'Node {NODE_QWEN}') shutil.rmtree(dove, ignore_errors=True) os.replace(os.path.join(tappa, nome), dove) shutil.rmtree(tappa, ignore_errors=True) return dove def assicura_qwen(versione, cartella, prova, su=None): if prova: return prova dove = os.path.join(cartella, versione) binario = os.path.join(dove, 'bin', 'qwen') if os.path.isfile(binario): return binario node = assicura_node(cartella, su=su) tappa = dove + '.nuovo' shutil.rmtree(tappa, ignore_errors=True) os.makedirs(cartella, exist_ok=True) print(F('installo_qwen', versione=versione), flush=True) 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'} 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) if r.returncode != 0 or not os.path.isfile(os.path.join(tappa, 'bin', 'qwen')): shutil.rmtree(tappa, ignore_errors=True) coda = (r.stderr or r.stdout or '').strip().splitlines()[-3:] raise RuntimeError(F('qwen_non_installato', versione=versione, perche=' / '.join(coda) or F('npm_muto'))) shutil.rmtree(dove, ignore_errors=True) os.replace(tappa, dove) return binario OPENCODE_NPM = 'https://registry.npmjs.org' OPENCODE_PACCHETTO = '@opencode/cli-{p}' def assicura_opencode(versione, cartella, prova, su=None): if prova: return prova if not opencode_v2(versione): raise RuntimeError(F('opencode_solo_v2', versione=versione)) dove = os.path.join(cartella, versione) binario = os.path.join(dove, 'bin', 'opencode') if os.path.isfile(binario) and os.access(binario, os.X_OK): return binario p = piattaforma() if not p: raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}')) pacchetto = OPENCODE_PACCHETTO.format(p=p) try: meta = json.loads(_get(f"{OPENCODE_NPM}/{pacchetto.replace('/', '%2F')}/{versione}", timeout=20)) except Exception: raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p)) from None dist = meta.get('dist') or {} integrity = str(dist.get('integrity') or '') if not integrity.startswith('sha512-') or not dist.get('tarball'): raise RuntimeError(F('opencode_integrita', versione=versione)) print(F('installo_opencode', versione=versione), flush=True) dati = _scarica(dist['tarball'], 600, su=su) if 'sha512-' + base64.b64encode(hashlib.sha512(dati).digest()).decode() != integrity: raise RuntimeError(F('opencode_integrita', versione=versione)) tappa = dove + '.nuovo' shutil.rmtree(tappa, ignore_errors=True) os.makedirs(cartella, exist_ok=True) _estrai(dati, tappa, f'OpenCode {versione}') dentro = os.path.join(tappa, 'package', 'bin', 'opencode') if not os.path.isfile(dentro): shutil.rmtree(tappa, ignore_errors=True) raise RuntimeError(F('opencode_senza_binario', versione=versione)) os.makedirs(os.path.join(tappa, 'bin'), exist_ok=True) os.replace(dentro, os.path.join(tappa, 'bin', 'opencode')) os.chmod(os.path.join(tappa, 'bin', 'opencode'), 493) shutil.rmtree(os.path.join(tappa, 'package'), ignore_errors=True) shutil.rmtree(dove, ignore_errors=True) os.replace(tappa, dove) return binario def _q(s): return shlex.quote(str(s)) def cli_qui(cli, versioni, versioni_codex, prova, versioni_qwen='', volute=(), versioni_opencode=''): if prova: return True nome = cli if cli in CLI_NOMI else 'claude' if shutil.which(nome) or cli in volute: return True cartella = {'codex': versioni_codex, 'qwen': versioni_qwen, 'opencode': versioni_opencode}.get(cli) or versioni try: return any((_VERSIONE.match(f) for f in os.listdir(cartella))) except OSError: return False def installa_agente(argv): if len(argv) != 2 or argv[0] not in ('claude', 'codex', 'qwen', 'opencode'): print(F('installa_agente_uso'), file=sys.stderr) return 2 cli, versione = argv prova = os.environ.get('DELMINIO_CLI_PROVA', '') registro = os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json') try: v = versione if cli in ('qwen', 'opencode') else versione_voluta({'versione': versione, 'cli': cli}, {}) if not _VERSIONE.match(v): raise RuntimeError(F('non_versione', versione=v)) if cli == 'claude': binario = assicura_cli(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions'), prova) elif cli == 'codex': binario = assicura_codex(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions'), prova) elif cli == 'qwen': versioni_qwen = os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions') binario = assicura_qwen(v, versioni_qwen, prova) if not prova: print('DELMINIO_NODE=' + os.path.join(node_di(versioni_qwen), 'bin'), flush=True) else: binario = assicura_opencode(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions'), prova) except (RuntimeError, OSError, ValueError, urllib.error.URLError) as e: print(F('installa_agente_no', cli=CLI_NOMI[cli], errore=e), file=sys.stderr) return 1 mio = _leggi(registro) mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {cli}) _scrivi(registro, mio) print(binario) return 0 def modello_gratuito(argv): if len(argv) != 1 or not os.access(argv[0], os.X_OK): print(F('modello_gratuito_uso'), file=sys.stderr) return 2 oc = argv[0] try: elenco = subprocess.run([oc, '--standalone', 'models'], capture_output=True, text=True, timeout=60).stdout except (OSError, subprocess.TimeoutExpired): elenco = '' candidati = [r.strip() for r in elenco.splitlines() if r.strip().startswith('opencode/') and r.strip().endswith('-free')] for m in candidati: try: r = subprocess.run([oc, '--standalone', 'run', '-m', m, F('modello_gratuito_domanda')], capture_output=True, text=True, timeout=90, cwd=tempfile.gettempdir()) except (OSError, subprocess.TimeoutExpired): continue if r.returncode == 0 and F('modello_gratuito_risposta').lower() in r.stdout.lower(): print(m) return 0 print(F('modello_gratuito_nessuno', n=len(candidati)), file=sys.stderr) return 1 def personaggio(riga): return bool(riga.get('porta')) and riga.get('nascita') == 'porta' def spazio_di(url, token): u = url.rstrip('/') try: pezzo = token.split('.')[1] cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or '' except (IndexError, ValueError, AttributeError): cli = '' k = u if cli in ('', 'unico') else f'{u}#{cli}' return _ALIASI.get(k, k) _ALIASI = {} def _alias(mio, chiave, istanza): if not istanza: return chiave for k, sp in list((mio.get('spazi') or {}).items()): if k != chiave and sp.get('istanza') == istanza and (k not in (mio.get('alias') or {})): mio.setdefault('alias', {})[chiave] = k _ALIASI[chiave] = k mio.get('spazi', {}).pop(chiave, None) for chi in (mio.get('padroni') or {}).values(): if chiave in chi: chi[:] = list(dict.fromkeys((k if c == chiave else c for c in chi))) return k return chiave def _istanza_di(url, token): try: return json.loads(_get(url.rstrip('/') + '/api/eseguibili', token, timeout=10)).get('istanza') or '' except (OSError, ValueError, AttributeError, urllib.error.URLError): return '' def nome_spazio(spazio): return spazio.rsplit('#', 1)[1] if '#' in spazio else F('spazio_principale') def _token_di(token_file): try: with open(os.path.expanduser(token_file), encoding='utf-8') as f: return f.read().strip() except OSError: return '' def canale_del_ruolo(spazio, porta): spazio = hashlib.sha256(spazio.encode()).hexdigest()[:12] chiave = re.sub('[^a-z0-9._-]+', '-', porta.lower()).strip('-') or 'ruolo' return os.path.join(os.path.expanduser('~/.config/delminio/ruoli'), spazio, chiave + '.json') def progetto_dello_spazio(spazio): return os.path.join(os.path.dirname(canale_del_ruolo(spazio, 'x')), 'progetto') def ricorda_il_progetto(spazio): qui = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) try: c = subprocess.run(['git', '-C', qui, 'rev-parse', '--path-format=absolute', '--git-common-dir'], capture_output=True, text=True, timeout=10) if c.returncode == 0 and c.stdout.strip(): qui = os.path.dirname(c.stdout.strip()) except (OSError, subprocess.SubprocessError): pass if not os.access(os.path.join(qui, '.claude', 'delminio.sh'), os.X_OK): return f = progetto_dello_spazio(spazio) try: with open(f, encoding='utf-8') as fh: if fh.read().strip() == qui: return except OSError: pass os.makedirs(os.path.dirname(f), mode=448, exist_ok=True) tmp = f + '.nuovo' with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as fh: fh.write(qui + '\n') os.replace(tmp, f) def _righe_del_repo(riga, spazio, avviso): 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'] if (riga.get('scelte') or {}).get('casa') == 'separata' or riga.get('cartella'): 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'] avviso = F('wrapper_casa_senza_repo', nome=riga['nome']) return righe + ['if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' echo ' + _sh(avviso) + ' >&2', ' exit 1', 'fi'] def assicura_canale(base_url, token, porta): f = canale_del_ruolo(spazio_di(base_url, token), porta) precedente, col_nome = ('', False) if os.path.isfile(f): try: with open(f, encoding='utf-8') as h: srv = json.load(h)['mcpServers'] col_nome = SERVER_RUOLO in srv precedente = (srv.get(SERVER_RUOLO) or srv['delminio-ruolo'])['headers']['Authorization'].removeprefix('Bearer ') except (ValueError, KeyError, TypeError, FileNotFoundError): pass d = json.loads(_get(base_url.rstrip('/') + '/api/porte/' + urllib.parse.quote(porta) + '/token', token, metodo='POST', corpo={'precedente': precedente})) if precedente and d['token'] == precedente and col_nome: return f os.makedirs(os.path.dirname(f), mode=448, exist_ok=True) conf = {'mcpServers': {SERVER_RUOLO: {'type': 'http', 'url': base_url.rstrip('/') + '/mcp', 'headers': {'Authorization': 'Bearer ' + d['token']}}}} fd = os.open(f + '.nuovo', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384) with os.fdopen(fd, 'w', encoding='utf-8') as h: json.dump(conf, h) os.replace(f + '.nuovo', f) return f def ganci_della_posta(canale): def cmd(momento): return f'python3 "$DELMINIO_POSTA_CLIENT" posta-ruolo {_q(canale)} {momento}' pulizia = {'type': 'command', 'command': 'python3 "$DELMINIO_POSTA_CLIENT" pulizia', 'timeout': 10} 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)]}]} def con_i_ganci(args, ganci): return con_le_impostazioni(args, {'hooks': ganci}, F('cosa_posta_ruolo')) def _unisci(s, extra): for k, v in extra.items(): if isinstance(v, dict) and isinstance(s.get(k), dict): _unisci(s[k], v) elif isinstance(v, list) and isinstance(s.get(k), list): s[k].extend((x for x in v if x not in s[k])) else: s.setdefault(k, v) def con_le_impostazioni(args, extra, cosa): args = list(args) for i, a in enumerate(args[:-1]): if a == '--settings' and args[i + 1].lstrip().startswith('{'): try: s = json.loads(args[i + 1]) except ValueError: break _unisci(s, json.loads(json.dumps(extra))) args[i + 1] = json.dumps(s, ensure_ascii=False, separators=(',', ':')) return args if '--settings' in args: sys.stderr.write(F('settings_file', cosa=cosa) + '\n') return args return args + ['--settings', json.dumps(extra, ensure_ascii=False, separators=(',', ':'))] PERMESSI = {'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']}} def ambiente_della_riga(riga): return {k: v for k, v in (riga.get('ambiente') or {}).items() if not str(k).startswith('DELMINIO_')} def lancio_delle_scelte(riga): sc, cli = (riga.get('scelte') or {}, riga.get('cli') or 'claude') args, env = (list(PERMESSI.get(cli, {}).get(sc.get('permessi'), [])), {}) if sc.get('conversazioni') in CONVERSAZIONI: env['DELMINIO_CONVERSAZIONI'] = sc['conversazioni'] if cli == 'opencode': return (args, env) if cli == 'qwen': if sc.get('ricerca_web') == 'spenta': args += ['--exclude-tools', 'web_search', '--exclude-tools', 'web_fetch'] return (args, env) if cli == 'codex': if sc.get('ricerca_web') == 'spenta': args += ['-c', 'web_search="disabled"'] if sc.get('telemetria') == 'spenta': args += ['-c', 'analytics.enabled=false', '-c', 'feedback.enabled=false'] if sc.get('velocita') == 'fast': args += ['-c', 'service_tier="fast"', '-c', 'features.fast_mode=true'] return (args, env) if sc.get('ricerca_web') == 'spenta': args = con_le_impostazioni(args, {'permissions': {'deny': ['WebSearch', 'WebFetch']}}, F('cosa_ricerca_spenta')) if sc.get('telemetria') == 'spenta': env.update({'DISABLE_TELEMETRY': '1', 'DISABLE_ERROR_REPORTING': '1', 'CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY': '1'}) if sc.get('classificatore'): env['CLAUDE_CODE_AUTO_MODE_MODEL'] = sc['classificatore'] if sc.get('casa') == 'separata': args += ['--restricted', '--allowedTools=Edit(consegne/**)'] return (args, env) def _pid_della_cli(): pid = os.getppid() for _ in range(4): try: exe = os.path.basename(os.readlink(f'/proc/{pid}/exe')) if _VERSIONE.match(exe) or exe == 'claude': return pid with open(f'/proc/{pid}/stat', encoding='utf-8') as f: pid = int(f.read().rsplit(')', 1)[1].split()[1]) except (OSError, ValueError, IndexError): break return os.getppid() def _rito_del_ruolo(): return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'rito-del-ruolo') _SKILL_DEL_RITO = {'apertura': (F('rito_apertura_descrizione'), F('rito_apertura_corpo')), 'chiusura': (F('rito_chiusura_descrizione'), F('rito_chiusura_corpo'))} COMANDI = { "riti": { "apertura": "apertura", "chiusura": "chiusura", "closing": "chiusura", "handoff": "chiusura", "opening": "apertura", "start": "apertura" } } _SINONIMI_DEL_RITO = dict(COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}) _SKILL_DEL_RITO.update({nome: _SKILL_DEL_RITO[nostra] for nome, nostra in _SINONIMI_DEL_RITO.items()}) def assicura_rito(): voluti = {os.path.join('.claude-plugin', 'plugin.json'): json.dumps({'name': 'delminio', 'description': F('rito_plugin')}, ensure_ascii=False, indent=2) + '\n'} for nome, (descrizione, corpo) in _SKILL_DEL_RITO.items(): 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' for rel, testo in voluti.items(): p = os.path.join(_rito_del_ruolo(), rel) try: with open(p, encoding='utf-8') as f: if f.read() == testo: continue except OSError: pass os.makedirs(os.path.dirname(p), exist_ok=True) with open(p + '.nuovo', 'w', encoding='utf-8') as f: f.write(testo) os.replace(p + '.nuovo', p) return _rito_del_ruolo() _NOMI_DEL_RITO = '|'.join((re.escape(n) for n in sorted(_SINONIMI_DEL_RITO, key=len, reverse=True))) _GESTO_DEL_RITO = re.compile('(?:/(?:delminio:)?(' + _NOMI_DEL_RITO + ')(?:\\s.*)?|(' + _NOMI_DEL_RITO + ')\\s*(?::.*)?)', re.I | re.S) def _rito_del_messaggio(base, token, radice, evento): prima = (evento.get('prompt') or '').strip().split('\n', 1)[0].strip() m = _GESTO_DEL_RITO.fullmatch(prima) parola = (m.group(1) or m.group(2)).lower() if m else '' parola = _SINONIMI_DEL_RITO.get(parola, parola) segno = radice + '.aperta' if not parola and os.path.exists(segno): return '' q = urllib.parse.urlencode({'parola': parola or 'apertura', 'da_se': '' if parola else '1'}) try: testo = json.loads(_get(f'{base}/api/canale/ruolo/rito?{q}', token, timeout=15)).get('testo') or '' open(segno, 'w').close() return testo except urllib.error.HTTPError as e: if not parola: return '' try: perche = json.loads(e.read()).get('error') or str(e) except ValueError: perche = str(e) return F('rito_negato', parola=parola, perche=perche) except (OSError, ValueError, urllib.error.URLError): return F('rito_muto', parola=parola) if parola else '' CHIUDI_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', '']) _IGNORATI_DELLA_CASA = ('/repo/', '/progetto/', '/NOVITA.md', '/.visto*') def _riga_exec(*pezzi): return 'exec ' + ' '.join((p for p in pezzi if p)) def _chiave_repo(remoto): r = (remoto or '').strip() if not r or r.startswith('locale:'): return r if '://' in r: r = r.split('://', 1)[1] autorita, separatore, percorso = r.partition('/') r = autorita.rsplit('@', 1)[-1] + separatore + percorso host, _, percorso = r.partition('/') host = host.split(':', 1)[0] elif ':' in r and (not r.startswith('/')): host, _, percorso = r.partition(':') host = host.split('@', 1)[-1] else: return r.rstrip('/').removesuffix('.git') return f"{host.lower()}/{percorso.strip('/').removesuffix('.git').rstrip('/')}" def _git(*args, cwd=None): env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'} return subprocess.run(['git', *args], cwd=cwd, env=env, capture_output=True, text=True) def _origine(cartella): o = _git('remote', 'get-url', 'origin', cwd=cartella).stdout.strip() if o and os.path.isdir(o): o = _git('remote', 'get-url', 'origin', cwd=o).stdout.strip() or o return o def _https(remoto): c = _chiave_repo(remoto) return f'https://{c}.git' if '/' in c and '.' in c.split('/', 1)[0] else '' def _clona(remoto, progetto, dest, cartelle): fonti = [] if progetto and _chiave_repo(_origine(progetto)) == _chiave_repo(remoto): fonti.append(progetto) fonti += [remoto] + ([_https(remoto)] if _https(remoto) else []) ultimo = '' for f in fonti: r = _git('clone', '-q', '--no-checkout', f, dest) if r.returncode == 0: if cartelle: _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest) c = _git('checkout', '-q', cwd=dest) if c.returncode == 0: return '' ultimo = c.stderr.strip() else: ultimo = r.stderr.strip() shutil.rmtree(dest, ignore_errors=True) return ultimo.splitlines()[-1] if ultimo else F('non_si_clona') def _aggiorna(dest, cartelle): if cartelle: _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest) elif _git('config', 'core.sparseCheckout', cwd=dest).stdout.strip() == 'true': _git('sparse-checkout', 'disable', cwd=dest) r = _git('pull', '-q', '--ff-only', cwd=dest) return '' if r.returncode == 0 else (r.stderr.strip().splitlines() or [F('pull_fallito')])[-1] def _testa(cartella): return _git('rev-parse', 'HEAD', cwd=cartella).stdout.strip() def _uscito(cartella, prima, cartelle=(), quanti=40): spec = [f":(exclude){c[1:].lstrip('/')}" if c.startswith('!') else c.lstrip('/') or '*' for c in cartelle] file = _git('diff', '--name-only', f'{prima}..HEAD', '--', *spec, cwd=cartella).stdout.splitlines() righe = [f'- {f}' for f in file[:quanti]] if len(file) > quanti: righe.append(F('altri_file', n=len(file) - quanti)) return righe def _la_casa_e_un_repo(casa, suo, agente): avvisi = [] if not os.path.isdir(os.path.join(casa, '.git')): vuota = not os.path.isdir(casa) or not os.listdir(casa) if suo and vuota and (_git('clone', '-q', suo, casa).returncode == 0): pass else: os.makedirs(casa, exist_ok=True) _git('init', '-q', '-b', 'main', cwd=casa) if suo: _git('remote', 'add', 'origin', suo, cwd=casa) if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0: avvisi.append(F('repo_ruolo_lontano_nuova', repo=suo)) elif _git('rev-parse', '-q', '--verify', 'origin/main', cwd=casa).returncode == 0: _git('checkout', '-q', '-B', 'main', 'origin/main', cwd=casa) else: ora = _git('remote', 'get-url', 'origin', cwd=casa).stdout.strip() if suo and (not ora): _git('remote', 'add', 'origin', suo, cwd=casa) elif suo and _chiave_repo(ora) != _chiave_repo(suo): _git('remote', 'set-url', 'origin', suo, cwd=casa) avvisi.append(F('repo_ruolo_cambiato', repo=suo)) if suo or ora: ramo = _git('rev-parse', '--abbrev-ref', 'HEAD', cwd=casa).stdout.strip() or 'main' if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0: avvisi.append(F('repo_ruolo_lontano')) 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: avvisi.append(F('casa_ferma')) if not _git('config', '--local', 'user.name', cwd=casa).stdout.strip(): _git('config', 'user.name', agente, cwd=casa) _git('config', 'user.email', f'{agente}@ruoli.delminio', cwd=casa) return avvisi def _scrivi_se_cambia(percorso, testo, modo=None): try: with open(percorso, encoding='utf-8') as f: if f.read() == testo: return except OSError: pass with open(percorso + '.nuovo', 'w', encoding='utf-8') as f: f.write(testo) if modo: os.chmod(percorso + '.nuovo', modo) os.replace(percorso + '.nuovo', percorso) def casa(argv): if len(argv) not in (3, 4): sys.stderr.write(F('uso_casa') + '\n') return 2 client, ruolo, agente = argv[:3] url = token_file = '' for riga in open(client, encoding='utf-8'): k, _, v = riga.strip().partition('=') if k == 'URL' and v: url = (shlex.split(v) or [''])[0] elif k == 'FILE_TOKEN' and v: token_file = (shlex.split(v) or [''])[0] token = _token_di(token_file) progetto = os.path.dirname(os.path.dirname(os.path.abspath(client))) spazio = spazio_di(url, token) 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) vero = os.path.realpath(progetto) if os.path.realpath(casa) == vero or os.path.realpath(casa).startswith(vero + os.sep) or vero.startswith(os.path.realpath(casa) + os.sep): sys.stderr.write(F('casa_nel_progetto', agente=agente) + '\n') return 1 try: conf = json.loads(_get(f"{url.rstrip('/')}/api/porte/{urllib.parse.quote(ruolo)}/casa", token, timeout=15)) except (OSError, ValueError, urllib.error.URLError) as e: if os.path.isdir(casa): sys.stderr.write(F('casa_non_detta', agente=agente, errore=e) + '\n') print(casa) return 0 sys.stderr.write(F('casa_senza_repo', agente=agente, errore=e) + '\n') return 1 avvisi = _la_casa_e_un_repo(casa, conf.get('suo') or '', agente) if len(argv) == 3: os.chmod(casa, 448) os.makedirs(os.path.join(casa, 'consegne'), exist_ok=True) scelti = {r['nome']: r for r in conf.get('repo') or []} novita = ['# ' + F('novita_titolo'), ''] if scelti: base = os.path.join(casa, 'repo') os.makedirs(base, exist_ok=True) shutil.rmtree(os.path.join(casa, 'progetto'), ignore_errors=True) for d in sorted(os.listdir(base)): if d not in scelti and os.path.isdir(os.path.join(base, d, '.git')): shutil.rmtree(os.path.join(base, d), ignore_errors=True) novita += [f'## repo/{d}', '', F('novita_uscito'), ''] for nome, r in scelti.items(): dest, cartelle = (os.path.join(base, nome), r.get('cartelle') or []) if os.path.isdir(os.path.join(dest, '.git')) and _chiave_repo(_origine(dest)) != _chiave_repo(r['chiave']): shutil.rmtree(dest, ignore_errors=True) novita += [f'## repo/{nome}', ''] if not os.path.isdir(os.path.join(dest, '.git')): perche = _clona(r['chiave'], progetto, dest, cartelle) novita += [F('novita_non_si_clona', repo=r['chiave'], perche=perche) if perche else F('novita_copia_repo'), ''] if perche: avvisi.append(F('avviso_non_si_clona', repo=f'repo/{nome}', perche=perche)) continue prima = _testa(dest) perche = _aggiorna(dest, cartelle) if perche: avvisi.append(F('avviso_non_si_aggiorna', repo=f'repo/{nome}', perche=perche)) novita.append(F('novita_non_si_aggiorna', perche=perche)) righe = _uscito(dest, prima, cartelle) if prima and prima != _testa(dest) else [] novita += (righe or ([F('novita_niente')] if not perche else [])) + [''] for nome in conf.get('usciti') or []: novita += [F('novita_uscito_spazio', repo=nome), ''] else: base = os.path.join(casa, 'repo') if os.path.isdir(base): shutil.rmtree(base, ignore_errors=True) dest = os.path.join(casa, 'progetto') if os.path.isdir(os.path.join(dest, '.git')): prima = _testa(dest) perche = _aggiorna(dest, []) if perche: avvisi.append(F('copia_progetto_ferma', perche=perche)) righe = _uscito(dest, prima, quanti=60) if prima != _testa(dest) else [] novita += righe or [F('novita_niente')] else: r = _git('clone', '-q', progetto, dest) if r.returncode != 0: sys.stderr.write(F('progetto_non_si_copia', agente=agente, casa=casa) + '\n') return 1 novita.append(F('novita_copia_progetto')) if avvisi: novita += ['', '## ' + F('novita_al_tecnico'), ''] + [f'- {a}' for a in avvisi] _scrivi_se_cambia(os.path.join(casa, 'NOVITA.md'), '\n'.join(novita).rstrip() + '\n') _scrivi_se_cambia(os.path.join(casa, 'chiudi.sh'), CHIUDI_SH, 493) ignorati = os.path.join(casa, '.gitignore') try: ci_sono = open(ignorati, encoding='utf-8').read().splitlines() except OSError: ci_sono = [] mancano = [x for x in _IGNORATI_DELLA_CASA if x not in ci_sono] if mancano: _scrivi_se_cambia(ignorati, '\n'.join(ci_sono + mancano).strip() + '\n') for a in avvisi: sys.stderr.write(f'⚠️ {agente}: {a}\n') print(casa) return 0 def posta_ruolo(argv): if len(argv) != 2 or argv[1] not in ('umano', 'volo', 'attesa'): return 0 canale, momento = argv try: with open(canale, encoding='utf-8') as f: srv = json.load(f)['mcpServers'] srv = srv.get(SERVER_RUOLO) or srv['delminio-ruolo'] base = srv['url'].rsplit('/mcp', 1)[0] token = srv['headers']['Authorization'].split(' ', 1)[1] except (OSError, ValueError, KeyError, IndexError): return 0 evento = {} if not sys.stdin.isatty(): try: evento = json.loads(sys.stdin.read() or '{}') except ValueError: pass if momento == 'volo' and evento.get('agent_id'): return 0 cli = _pid_della_cli() sid = re.sub('[^A-Za-z0-9_-]', '', str(evento.get('session_id') or cli))[:64] stato = os.path.join(os.path.dirname(canale), 'posta') os.makedirs(stato, mode=448, exist_ok=True) radice = os.path.join(stato, os.path.splitext(os.path.basename(canale))[0] + '-' + sid) if momento == 'volo': try: if time.time() - os.path.getmtime(radice + '.volo') < 10: return 0 except OSError: pass open(radice + '.volo', 'w').close() def guarda(segna=True): with open(radice + '.lock', 'w') as lk: if fcntl is not None: fcntl.flock(lk, fcntl.LOCK_EX) try: with open(radice + '.visto', encoding='utf-8') as f: dopo = f.read().strip() except OSError: dopo = '' q = urllib.parse.urlencode({'dopo': dopo, 'momento': momento}) try: r = json.loads(_get(f'{base}/api/canale/ruolo?{q}', token, timeout=10)) except urllib.error.HTTPError as e: if segna and e.code in (401, 403) and (not os.path.exists(radice + '.rifiutato')): open(radice + '.rifiutato', 'w').close() return F('posta_ruolo_rifiutata', codice=e.code) return '' except (OSError, ValueError, urllib.error.URLError): return '' if os.path.exists(radice + '.rifiutato'): os.remove(radice + '.rifiutato') if segna and r.get('ultimo') and (r['ultimo'] != dopo): with open(radice + '.visto', 'w', encoding='utf-8') as f: f.write(r['ultimo']) if not segna and r.get('testo'): return r.get('ultimo') or '' return r.get('testo') or '' if momento != 'attesa': testo = guarda() if momento == 'umano': testo = '\n\n'.join((t for t in (_rito_del_messaggio(base, token, radice, evento), testo) if t)) if testo: nome = 'UserPromptSubmit' if momento == 'umano' else 'PostToolUse' print(json.dumps({'hookSpecificOutput': {'hookEventName': nome, 'additionalContext': testo}})) return 0 posta_qwen = os.environ.get('DELMINIO_QWEN_POSTA') or '' if posta_qwen: m = re.search('-(\\d+)\\.jsonl$', posta_qwen) if m: cli = int(m.group(1)) if not os.path.isfile(posta_qwen) or os.fork(): return 0 os.setsid() nulla = os.open(os.devnull, os.O_RDWR) for fd in (0, 1, 2): os.dup2(nulla, fd) with open(radice + '.attesa', 'w', encoding='utf-8') as f: f.write(str(os.getpid())) giri = 0 while True: testo = guarda(segna=not posta_qwen) if testo and posta_qwen: with open(radice + '.avviso.lock', 'w') as lk: if fcntl is not None: fcntl.flock(lk, fcntl.LOCK_EX) mia, gia = (False, '') try: with open(radice + '.attesa', encoding='utf-8') as f: mia = f.read().strip() == str(os.getpid()) except OSError: pass try: with open(radice + '.avvisato', encoding='utf-8') as f: gia = f.read().strip() except OSError: pass if not mia: return 0 if testo != gia: with open(posta_qwen, 'a', encoding='utf-8') as f: f.write(json.dumps({'type': 'submit', 'text': F('posta_arrivata')}, ensure_ascii=False) + '\n') with open(radice + '.avvisato', 'w', encoding='utf-8') as f: f.write(testo) return 0 elif testo: sys.stderr.write(testo + '\n') return 2 try: os.kill(cli, 0) with open(radice + '.attesa', encoding='utf-8') as f: if f.read().strip() != str(os.getpid()): return 0 except (OSError, ValueError): return 0 giri += 1 time.sleep(3 if giri < 40 else 15 if giri < 80 else 30) GIORNI_DOPO_UN_CRASH = 3 CONVERSAZIONI = ('subito', 'fine_sessione') def _pid_vivo(pid): try: os.kill(int(pid), 0) return True except ProcessLookupError: return False except (PermissionError, ValueError, TypeError, OverflowError): return True def _sessioni_vive(registro): vive = set() for f in glob_ordinato(os.path.join(registro, '*.json')): try: with open(f, encoding='utf-8') as h: d = json.load(h) if _pid_vivo(d.get('pid') or os.path.basename(f).split('.')[0]) and d.get('sessionId'): vive.add(str(d['sessionId'])) except (OSError, ValueError, AttributeError): continue return vive def glob_ordinato(schema): import glob return sorted(glob.glob(schema)) def _vecchia(percorsi, giorni): if giorni <= 0: return True soglia = time.time() - giorni * 86400 for p in percorsi: try: if os.path.getmtime(p) >= soglia: return False except OSError: continue return True def _via(p): try: if os.path.isdir(p) and (not os.path.islink(p)): shutil.rmtree(p, ignore_errors=True) elif os.path.lexists(p): os.unlink(p) except OSError: pass def _ancora_dopo(percorsi, secondi=15): if not percorsi or os.fork(): return try: os.setsid() nulla = os.open(os.devnull, os.O_RDWR) for fd in (0, 1, 2): os.dup2(nulla, fd) time.sleep(secondi) for p in percorsi: _via(p) finally: os._exit(0) def _da_togliere(sessioni, vive, mia, fine, subito, giorni): via = set() for sid, percorsi in sessioni.items(): if sid == mia: if fine or subito: via.add(sid) continue if sid in vive: continue if _vecchia(percorsi, giorni): via.add(sid) return via def _pulisci_claude(evento, mia, fine, subito, giorni): casa = os.path.realpath(os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')) progetti = os.path.join(casa, 'projects') trascritto = str(evento.get('transcript_path') or '') if trascritto: cartella = os.path.dirname(os.path.realpath(trascritto)) else: dove = os.environ.get('CLAUDE_PROJECT_DIR') or str(evento.get('cwd') or '') if not dove: return cartella = os.path.join(progetti, re.sub('[^A-Za-z0-9]', '-', dove)) if os.path.dirname(cartella) != progetti or not os.path.isdir(cartella): return sessioni = {} for nome in os.listdir(cartella): sid = nome[:-6] if nome.endswith('.jsonl') else nome if sid == 'memory' or not re.fullmatch('[0-9a-fA-F-]{8,}', sid): continue sessioni.setdefault(sid, []).append(os.path.join(cartella, nome)) via = _da_togliere(sessioni, _sessioni_vive(os.path.join(casa, 'sessions')), mia, fine, subito, giorni) for sid in via: for p in sessioni[sid]: _via(p) 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 + '*'))): _via(p) if via: _togli_dalla_cronologia(os.path.join(casa, 'history.jsonl'), via) if fine and mia in via: _ancora_dopo([os.path.join(cartella, mia + '.jsonl'), os.path.join(cartella, mia)]) def _togli_dalla_cronologia(f, via): try: with open(f, encoding='utf-8') as h: righe = h.readlines() except OSError: return tenute = [] for r in righe: try: if str(json.loads(r).get('sessionId') or '') in via: continue except (ValueError, AttributeError): pass tenute.append(r) if len(tenute) == len(righe): return tmp = f + '.delminio' try: with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as h: h.writelines(tenute) os.replace(tmp, f) except OSError: _via(tmp) def _casa_delminio(var, sotto): h = os.environ.get(var) if not h: return None casa = os.path.realpath(h) base = os.path.realpath(os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', sotto)) return casa if os.path.dirname(casa) == base and os.path.isdir(casa) else None def _pulisci_qwen(mia, fine, subito, giorni): casa = _casa_delminio('QWEN_HOME', 'qwen') if not casa: return eta, tutto = ({}, {}) for p in glob_ordinato(os.path.join(casa, 'projects', '*', 'chats', '*')): sid = os.path.basename(p).split('.', 1)[0] eta.setdefault(sid, []).append(p) tutto.setdefault(sid, []).append(p) degli_agenti = {} for d in glob_ordinato(os.path.join(casa, 'projects', '*', 'subagents', '*')): sid = os.path.basename(d) tutto.setdefault(sid, []).append(d) degli_agenti.setdefault(sid, []).extend([d, *glob_ordinato(os.path.join(d, '*'))]) for sid, percorsi in degli_agenti.items(): eta.setdefault(sid, percorsi) for p in [*glob_ordinato(os.path.join(casa, 'file-history', '*')), *glob_ordinato(os.path.join(casa, 'tmp', '*', 'background-shells', '*'))]: tutto.setdefault(os.path.basename(p), []).append(p) for sid, percorsi in tutto.items(): eta.setdefault(sid, percorsi) vive = _sessioni_vive(os.path.join(casa, 'sessions')) via = _da_togliere(eta, vive, mia, fine, subito, giorni) for sid in via: for p in tutto[sid]: _via(p) if fine and mia in via: _ancora_dopo(tutto[mia]) for f in glob_ordinato(os.path.join(casa, 'sessions', '*.json')): if not _pid_vivo(os.path.basename(f).split('.')[0]): _via(f) if not vive - ({mia} if fine else set()): for d in glob_ordinato(os.path.join(casa, 'tmp', '*')): for x in ('logs.json', 'tool-results', 'checkpoints'): _via(os.path.join(d, x)) def _pulisci_codex(mia, fine, giorni): casa = _casa_delminio('CODEX_HOME', 'codex') cli = os.environ.get('DELMINIO_CLI') or '' if not casa or os.path.basename(cli) != 'codex' or (not os.path.isfile(cli)): return stato = os.path.join(casa, 'delminio-pulizia') os.makedirs(stato, mode=448, exist_ok=True) 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): open(os.path.join(stato, mia + '.pending'), 'a').close() if not fine and giorni > 0: return 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} 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) def _codex_vivi(casa): for p in glob_ordinato('/proc/[0-9]*'): try: if os.path.basename(os.path.realpath(os.path.join(p, 'exe'))) != 'codex': continue with open(os.path.join(p, 'environ'), 'rb') as h: v = h.read().split(b'\x00') c = next((x.split(b'=', 1)[1] for x in v if x.startswith(b'CODEX_HOME=')), None) if c is None or os.path.realpath(os.fsdecode(c)) == casa: return True except FileNotFoundError: continue except OSError: return True return False def pulizia_codex(argv): import fcntl, sqlite3, uuid from contextlib import closing casa = _casa_delminio('CODEX_HOME', 'codex') cli = os.environ.get('DELMINIO_CLI') or '' if not casa or os.path.basename(cli) != 'codex': return 0 giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH stato = os.path.join(casa, 'delminio-pulizia') os.makedirs(stato, mode=448, exist_ok=True) with open(os.path.join(stato, 'lock'), 'w') as lk: try: fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return 0 while _codex_vivi(casa): time.sleep(3) via = {os.path.basename(p)[:-8] for p in glob_ordinato(os.path.join(stato, '*.pending'))} db = os.path.join(casa, 'state_5.sqlite') if os.path.isfile(db) and glob_ordinato(os.path.join(casa, 'state_*.sqlite')) == [db]: soglia = time.time() - giorni * 86400 with closing(sqlite3.connect('file:' + db + '?mode=ro', uri=True)) as c: for sid, ultima in c.execute('SELECT id, updated_at FROM threads').fetchall(): if isinstance(ultima, (int, float)) and 0 < ultima < soglia: via.add(str(sid)) tolte = [] for sid in sorted(via): try: sid = str(uuid.UUID(sid)) except ValueError: continue if _codex_vivi(casa): return 0 r = subprocess.run([cli, 'delete', '--force', sid], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=120) if r.returncode == 0: tolte.append(sid) _via(os.path.join(stato, sid + '.pending')) for s in glob_ordinato(os.path.join(casa, 'shell_snapshots', sid + '.*.sh')): _via(s) if tolte and (not _codex_vivi(casa)): for prefisso in ('state', 'thread_history', 'queue', 'logs', 'goals', 'memories'): for p in glob_ordinato(os.path.join(casa, prefisso + '_*.sqlite')): try: with closing(sqlite3.connect(p, timeout=5)) as c: if c.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]: continue c.execute('VACUUM') c.execute('PRAGMA wal_checkpoint(TRUNCATE)') except sqlite3.Error: continue return 0 _SESSIONE_OPENCODE = re.compile('ses_[A-Za-z0-9]{8,64}') def _segni_opencode(): d = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'opencode', 'conversazioni') os.makedirs(d, mode=448, exist_ok=True) return d def _pulisci_opencode(mia, fine, giorni): cli = os.environ.get('DELMINIO_CLI') or '' if os.path.basename(cli) != 'opencode' or not os.path.isfile(cli) or (not _SESSIONE_OPENCODE.fullmatch(mia)): return stato = _segni_opencode() pid = os.environ.get('DELMINIO_CLI_PID') or str(os.getppid()) with open(os.path.join(stato, mia + '.json'), 'w', encoding='utf-8') as h: json.dump({'pid': pid, 'cli': cli, 'linea': '2'}, h) if fine: open(os.path.join(stato, mia + '.fine'), 'a').close() 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} 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) def pulizia_opencode(argv): import fcntl giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH stato = _segni_opencode() with open(os.path.join(stato, 'lock'), 'w') as lk: try: fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return 0 while True: segnate, attese = ({}, False) for f in glob_ordinato(os.path.join(stato, 'ses_*.json')): sid = os.path.basename(f)[:-5] try: with open(f, encoding='utf-8') as h: segnate[sid] = (json.load(h), f) except (OSError, ValueError): continue via = [] for sid, (d, f) in segnate.items(): finita = os.path.exists(os.path.join(stato, sid + '.fine')) if _pid_vivo(d.get('pid')): attese = attese or finita continue if finita or _vecchia([f], giorni): via.append((sid, d)) for sid, d in via: cli = d.get('cli') if os.path.isfile(str(d.get('cli') or '')) else '' if d.get('linea') != '2': for x in ('.json', '.fine'): _via(os.path.join(stato, sid + x)) continue if not cli: continue cmd = [cli, 'session', 'delete', sid, '--standalone'] try: r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=120) except (OSError, subprocess.TimeoutExpired): continue if r.returncode == 0 or b'Session not found' in r.stdout + r.stderr: for x in ('.json', '.fine'): _via(os.path.join(stato, sid + x)) if not attese: return 0 time.sleep(3) def pulizia(argv): modo = os.environ.get('DELMINIO_CONVERSAZIONI') or '' if modo not in CONVERSAZIONI: return 0 try: evento = json.loads(sys.stdin.read() or '{}') if not sys.stdin.isatty() else {} if not isinstance(evento, dict): evento = {} except ValueError: evento = {} fine = evento.get('hook_event_name') == 'SessionEnd' or argv[:1] == ['fine'] mia = str(evento.get('session_id') or '') subito = modo == 'subito' giorni = 0 if subito else GIORNI_DOPO_UN_CRASH cli = os.environ.get('DELMINIO_CLI_NOME') or 'claude' try: if cli == 'qwen': _pulisci_qwen(mia, fine, subito, giorni) elif cli == 'codex': _pulisci_codex(mia, fine, giorni) elif cli == 'opencode': _pulisci_opencode(mia, fine, giorni) elif cli == 'claude': _pulisci_claude(evento, mia, fine, subito, giorni) except Exception: pass return 0 ERRORI_TETTO_BYTE = 2000000 ERRORI_RIGHE = 3 ERRORI_CARATTERI = 300 _USCITA = re.compile('^Exit code (\\d+)\\s*') _DICE_NO = {'grep', 'egrep', 'fgrep', 'rg', 'diff', 'cmp', 'test', '[', '[['} _SEGRETO = re.compile('(?i)\\b(token|password|passwd|secret|segreto|bearer|api[_-]?key|authorization)\\b(\\S*?)([=:]\\s*|\\s+)\\S+') _LUNGO = re.compile('[A-Za-z0-9_\\-+=]{24,}') _ESADECIMALE = re.compile('[0-9a-fA-F]{32,}') ENTROPIA_DI_UNA_CHIAVE = 4.3 _FERMATO_CLI = re.compile('^blocked|isolated\\sin\\sthe\\sworktree|permission|denied|rejected') _TEMPO = re.compile('timed\\sout|timeout') def _registro_errori(): casa = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state') return os.path.join(casa, 'delminio', 'errori-strumenti.jsonl') def _entropia(s): return -sum((k / len(s) * math.log2(k / len(s)) for k in collections.Counter(s).values())) def _maschera(t): t = _SEGRETO.sub(lambda m: m.group(1) + m.group(2) + m.group(3) + '…', t) t = _ESADECIMALE.sub('…', t) return _LUNGO.sub(lambda m: '…' if _entropia(m.group(0)) > ENTROPIA_DI_UNA_CHIAVE else m.group(0), t) def _programma(comando): pezzi = [p for p in re.split('&&|\\|\\||;|\\||\\n', comando or '') if p.strip()] if not pezzi: return '' for parola in pezzi[-1].split(): if re.match('^[A-Za-z_][A-Za-z0-9_]*=', parola) or parola in ('sudo', 'timeout', 'time', '!'): continue if re.fullmatch('\\d+[smh]?', parola): continue return os.path.basename(parola.strip('\'"()'))[:40] return '' def _specie(evento, programma, errore): if evento.get('is_interrupt'): return ('interrotto', True) m = _USCITA.match(errore) if m: resto = errore[m.end():].strip() if m.group(1) == '1' and (not resto or programma in _DICE_NO): return ('uscita_senza_errore', True) return ('uscita', False) basso = errore.lower() if '' in basso or 'inputvalidationerror' in basso: return ('tool', False) if 'delminio' in basso or '🔒' in errore: return ('fermato_da_delminio', False) if _FERMATO_CLI.search(basso): return ('fermato_dalla_cli', False) if _TEMPO.search(basso): return ('tempo', False) return ('altro', False) def errori_registra(_argv): try: evento = json.loads(sys.stdin.read() or '{}') tool = str(evento.get('tool_name') or '')[:60] entrata = evento.get('tool_input') or {} comando = entrata.get('command') if isinstance(entrata, dict) else '' programma = _programma(comando) if isinstance(comando, str) else '' errore = str(evento.get('error') or '').strip() specie, non_errore = _specie(evento, programma, errore) righe = [r for r in errore.splitlines() if r.strip()][:ERRORI_RIGHE] 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')} dove = _registro_errori() os.makedirs(os.path.dirname(dove), mode=448, exist_ok=True) with open(dove, 'a', encoding='utf-8') as f: f.write(json.dumps(voce, ensure_ascii=False) + '\n') if os.path.getsize(dove) > ERRORI_TETTO_BYTE: with open(dove, encoding='utf-8', errors='replace') as f: tenute = f.readlines() tenute = tenute[len(tenute) // 2:] nuovo = dove + f'.{os.getpid()}.tmp' with open(nuovo, 'w', encoding='utf-8') as f: f.writelines(tenute) os.replace(nuovo, dove) except Exception: pass return 0 def errori(argv): tutti = '--tutti' in argv or '--all' in argv numeri = [a for a in argv if a.isdigit()] giorni = int(numeri[0]) if numeri else 7 dal = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=giorni) dove = _registro_errori() voci = [] try: with open(dove, encoding='utf-8', errors='replace') as f: for r in f: try: v = json.loads(r) if datetime.datetime.fromisoformat(v['quando']) >= dal: voci.append(v) except (ValueError, KeyError, TypeError): continue except FileNotFoundError: pass nascoste = [v for v in voci if v.get('non_errore')] mostrate = voci if tutti else [v for v in voci if not v.get('non_errore')] print(F('errori_testa', giorni=giorni, n=len(mostrate), file=dove)) if nascoste and (not tutti): print(F('errori_nascosti', n=len(nascoste))) if not mostrate: print(F('errori_nessuno')) return 0 print(F('errori_per_specie')) for specie, n in collections.Counter((v.get('specie', '') for v in mostrate)).most_common(): print(f' {n:4} {specie}') print(F('errori_per_programma')) for (tool, prog), n in collections.Counter(((v.get('tool', ''), v.get('programma', '')) for v in mostrate)).most_common(12): print(f" {n:4} {tool}{(' ' + prog if prog else '')}") print(F('errori_ultime')) for v in mostrate[-15:]: 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]}") return 0 def _righe_del_prompt(riga, url, token_file): nome, porta = (riga['nome'], riga.get('porta')) rotta = 'nascita' if riga.get('nascita') == 'intera' else 'sistema' 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"'] def _righe_al_lancio(modo, url, token_file): if modo == 'kit': 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'] else: 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'] return [*_commento(F('commento_al_lancio')), 'if [ -z "${DELMINIO_AL_LANCIO:-}" ]; then', *chi, 'fi', 'unset DELMINIO_AL_LANCIO'] def _testa_del_wrapper(riga): chi = ' '.join(str(riga.get('descrizione') or F('wrapper_descrizione_serie')).split()) return ['#!/bin/sh', f"# {riga['nome']} — {chi}", *_commento(F('wrapper_commento'))] def wrapper_codex(riga, cli, modo, url, token_file): nome, porta = (riga['nome'], riga.get('porta')) if personaggio(riga): raise RuntimeError(F('codex_ruolo_solo')) di_serie = [] if modo == 'kit' else ['--no-daemon', '-c', 'check_for_update_on_startup=false'] della_riga = [] if riga.get('modello'): della_riga += ['-m', riga['modello']] if riga.get('effort'): della_riga += ['-c', f'''model_reasoning_effort="{riga['effort']}"'''] contesto = riga.get('_contesto') or {} espliciti = riga.get('argomenti') or [] if contesto.get('massimo') and (not any((x.startswith('model_context_window=') for x in espliciti))): di_serie += ['-c', f"model_context_window={int(contesto['massimo'])}"] if contesto.get('compatta') and (not any((x.startswith('model_auto_compact_token_limit=') for x in espliciti))): di_serie += ['-c', f"model_auto_compact_token_limit={int(contesto['compatta'])}"] delle_scelte, env_scelte = lancio_delle_scelte(riga) della_riga += delle_scelte + list(riga.get('argomenti') or []) casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12] 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)}'] if riga.get('ordine'): righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}") for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()): if re.fullmatch('[A-Z_][A-Z0-9_]*', k): righe.append(f'export {k}={_q(v)}') 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"'] def strato(client): 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')] if modo == 'kit' and porta: 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)}"] righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file))) if (tetto := (riga.get('_base') or {}).get('codex.tetto_uscite')): righe.append(f'export DELMINIO_TETTO_USCITE={int(tetto)}') righe += _righe_al_lancio(modo, url, token_file) righe += strato('"$r/.claude/eseguibili.py"') righe.append(_riga_exec('bash "$r/.claude/delminio.sh" codex', '"$@"')) return '\n'.join(righe) + '\n' if porta: righe += _righe_del_prompt(riga, url, token_file) righe.append(f'export DELMINIO_PORTA={_q(porta)}') if riga.get('cartella'): righe.append(f"cd {_q(riga['cartella'])} || exit 1") prompt = ' -c "model_instructions_file=\\"$F\\""' if porta else '' righe += _righe_al_lancio(modo, url, token_file) pacchetto = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugin.py') 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'] righe += strato(_q(os.path.abspath(__file__))) righe.append(_riga_exec(_q(cli), prompt.strip(), '"$@"')) return '\n'.join(righe) + '\n' MIE_QWEN = 'mie-qwen.json' MIE_CODEX = 'mie-codex.toml' QWEN_DI_DELMINIO = ('hooks', 'general.enableAutoUpdate', 'mcpServers.delminio', 'mcpServers.memoria') CODEX_DI_DELMINIO = (('hooks',), ('mcp_servers', 'delminio'), ('mcp_servers', 'memoria'), ('plugins', 'delminio@delminio'), ('marketplaces', 'delminio'), ('model_instructions_file',), ('check_for_update_on_startup',)) OPZIONI_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'}} def cartella_mie(): return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio') def _percorsi_json(d, dove=()): for k, v in d.items(): if isinstance(v, dict): yield from _percorsi_json(v, dove + (k,)) else: yield (dove + (k,)) def _stampa_chiavi(percorsi): print('|' + '|'.join(sorted({'.'.join(p) for p in percorsi})) + '|') def _della_riga(argomenti): if '--della-riga' in argomenti: i = argomenti.index('--della-riga') return (argomenti[:i] + argomenti[i + 2:], [tuple(k.split('.')) for k in argomenti[i + 1].split(',') if k]) return (argomenti, []) def _sotto(percorso, chiavi): return any((percorso[:len(k)] == k for k in chiavi)) def _sopra(percorso, chiavi): return [k for k in chiavi if len(k) > len(percorso) and k[:len(percorso)] == percorso] def unisci_mie_qwen(argomenti): argomenti, della_riga = _della_riga(argomenti) casa = argomenti[0] base = json.load(open(os.path.join(casa, 'settings.json'), encoding='utf-8')) scritte = [] di_delminio = [tuple(x.split('.')) for x in QWEN_DI_DELMINIO] def unisci(a, b, dove=''): for k, v in b.items(): if dove + k in QWEN_DI_DELMINIO: print(F('mie_di_delminio', nome=dove + k), file=sys.stderr) continue percorso = tuple((dove + k).split('.')) if _sotto(percorso, della_riga): print(F('mie_della_riga', nome=dove + k), file=sys.stderr) continue dentro_d, dentro_r = (_sopra(percorso, di_delminio), _sopra(percorso, della_riga)) if isinstance(v, dict) and (isinstance(a.get(k), dict) or dentro_d or dentro_r): if not isinstance(a.get(k), dict): a[k] = {} unisci(a[k], v, dove + k + '.') elif dentro_d or dentro_r: for x in dentro_d: print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr) for x in dentro_r: print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr) else: a[k] = v scritte.extend([percorso + p for p in _percorsi_json(v)] if isinstance(v, dict) else [percorso]) for file in (os.path.join(cartella_mie(), MIE_QWEN), os.path.join(casa, 'mie.json')): if not os.path.isfile(file): continue try: mie = json.load(open(file, encoding='utf-8')) if not isinstance(mie, dict): raise ValueError(type(mie).__name__) except (OSError, ValueError) as e: print(F('mie_qwen_illeggibili', file=file, errore=e), file=sys.stderr) continue unisci(base, mie) with open(os.path.join(casa, 'settings.json'), 'w', encoding='utf-8') as h: json.dump(base, h, indent=2, ensure_ascii=False) _stampa_chiavi(scritte) return 0 def _toml_chiave(s, i): parti = [] while True: while i < len(s) and s[i] in ' \t': i += 1 if i < len(s) and s[i] in '"\'': q, j = (s[i], i + 1) while j < len(s) and s[j] != q and (s[j] != '\n'): j += 2 if q == '"' and s[j] == '\\' else 1 nome = s[i + 1:j] if q == '"': try: nome = json.loads('"' + nome + '"') except ValueError: pass parti.append(nome) i = j + 1 else: j = i while j < len(s) and (s[j].isalnum() or s[j] in '_-'): j += 1 if j == i: raise ValueError(F('mie_toml_chiave', riga=s.count('\n', 0, i) + 1)) parti.append(s[i:j]) i = j while i < len(s) and s[i] in ' \t': i += 1 if s[i:i + 1] != '.': return (tuple(parti), i) i += 1 def _toml_fine_valore(s, i): profondo = 0 while i < len(s): if s.startswith('"""', i) or s.startswith("'''", i): q, j = (s[i:i + 3], i + 3) while True: k = s.find(q, j) if k < 0: raise ValueError(F('mie_toml_aperta', riga=s.count('\n', 0, i) + 1)) barre = len(s[:k]) - len(s[:k].rstrip('\\')) if q == '"""' and barre % 2: j = k + 1 continue i = k + 3 while s[i:i + 1] == q[0]: i += 1 break continue c = s[i] if c in '"\'': j = i + 1 while j < len(s) and s[j] != c and (s[j] != '\n'): j += 2 if c == '"' and s[j] == '\\' else 1 i = j + 1 continue if c == '#': k = s.find('\n', i) i = len(s) if k < 0 else k continue if c in '[{': profondo += 1 elif c in ']}': profondo -= 1 elif c == '\n' and profondo <= 0: return i + 1 i += 1 return i def toml_pezzi(testo): pezzi, i, tabella = ([], 0, ()) while i < len(testo): j = i while j < len(testo) and testo[j] in ' \t\r': j += 1 if j >= len(testo) or testo[j] in '\n#': k = testo.find('\n', j) fine = len(testo) if k < 0 else k + 1 pezzi.append(('altro', None, testo[i:fine])) i = fine continue if testo[j] == '[': lista = testo.startswith('[[', j) percorso, k = _toml_chiave(testo, j + (2 if lista else 1)) if not testo.startswith(']]' if lista else ']', k): raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1)) k = testo.find('\n', k) fine = len(testo) if k < 0 else k + 1 tabella = percorso pezzi.append(('lista' if lista else 'tabella', percorso, testo[i:fine])) i = fine continue percorso, k = _toml_chiave(testo, j) if testo[k:k + 1] != '=': raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1)) fine = _toml_fine_valore(testo, k + 1) pezzi.append(('chiave', tabella + percorso, testo[i:fine])) i = fine return pezzi def _toml_parti(pezzi): cima, sezioni = ([], []) for p in pezzi: if p[0] in ('tabella', 'lista'): sezioni.append([p]) elif sezioni: sezioni[-1].append(p) else: cima.append(p) return (cima, sezioni) def _di_delminio_codex(percorso): return any((percorso[:len(r)] == r for r in CODEX_DI_DELMINIO)) SEGNO_MIE = '# delminio-strato:' + MIE_CODEX SEGNO_DA_PARTE = '# delminio-strato:da-parte' SEGNO_FINE = '# delminio-strato:fine' _TRATTO = re.compile('(?ms)^(' + re.escape(SEGNO_MIE) + '|' + re.escape(SEGNO_DA_PARTE) + ')[^\\n]*\\n(.*?)^' + re.escape(SEGNO_FINE) + '[^\\n]*\\n?') def _unito(pezzi): t = ''.join((p[2] for p in pezzi)) return t if not t or t.endswith('\n') else t + '\n' def _tratto(segno, testo, prefisso=''): if not testo.strip(): return '' return segno + '\n' + ''.join((prefisso + r for r in testo.splitlines(keepends=True))) + SEGNO_FINE + '\n' def _casa_codex(testo): da_parte = [] def via(m): if m.group(1) == SEGNO_DA_PARTE: da_parte.extend((r[3:] if r.startswith('#= ') else r[2:] if r.startswith('#=') else '' for r in m.group(2).splitlines(keepends=True))) return '' cima, sezioni = _toml_parti(toml_pezzi(_TRATTO.sub(via, testo))) try: cima_p, sezioni_p = _toml_parti(toml_pezzi(''.join(da_parte))) except ValueError: cima_p, sezioni_p = ([], []) chiavi = {p[1] for p in cima + [x for s in sezioni for x in s] if p[0] == 'chiave'} cima += [p for p in cima_p if p[0] == 'chiave' and p[1] not in chiavi] for s in sezioni_p: torna = [p for p in s[1:] if p[0] != 'chiave' or p[1] not in chiavi] gemella = next((x for x in sezioni if x[0][0] == 'tabella' and x[0][1] == s[0][1]), None) if gemella is None: sezioni.append([s[0]] + torna) else: gemella.extend((p for p in torna if p[0] == 'chiave')) return (cima, sezioni) def unisci_mie_codex(argomenti): argomenti, della_riga = _della_riga(argomenti) casa = argomenti[0] conf, file = (os.path.join(casa, 'config.toml'), os.path.join(cartella_mie(), MIE_CODEX)) try: with open(conf, encoding='utf-8') as h: testo = h.read() except FileNotFoundError: testo = '' try: cima_r, sezioni_r = _casa_codex(testo) except ValueError as e: print(F('mie_codex_casa_illeggibile', file=conf, errore=e), file=sys.stderr) _stampa_chiavi([]) return 0 senza = _unito(cima_r) + _unito([p for s in sezioni_r for p in s]) nuovo, scritte = (senza, []) pezzi = None if os.path.isfile(file): try: with open(file, encoding='utf-8') as h: pezzi = toml_pezzi(h.read()) except (OSError, ValueError, UnicodeDecodeError) as e: print(F('mie_codex_illeggibili', file=file, errore=e), file=sys.stderr) if pezzi: cima_m, sezioni_m = _toml_parti(pezzi) def fuori(percorso): return _di_delminio_codex(percorso) or _sotto(percorso, della_riga) def fuori_c(percorso): return fuori(percorso) or bool(_sopra(percorso, CODEX_DI_DELMINIO) or _sopra(percorso, della_riga)) def dillo(percorso): if fuori(percorso): print(F('mie_di_delminio' if _di_delminio_codex(percorso) else 'mie_della_riga', nome='.'.join(percorso)), file=sys.stderr) return for x in _sopra(percorso, CODEX_DI_DELMINIO): print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr) for x in _sopra(percorso, della_riga): print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr) 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])]: dillo(p[1]) cima_m = [p for p in cima_m if not (p[0] == 'chiave' and fuori_c(p[1]))] 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])] scritte = [p[1] for p in cima_m + [x for s in sezioni_m for x in s] if p[0] == 'chiave'] tabelle_m = {s[0][1] for s in sezioni_m if s[0][0] == 'tabella'} coppie_m = set(scritte) | tabelle_m def coperta(p): return p[0] == 'chiave' and (p[1] in coppie_m or any((p[1][:len(t)] == t for t in tabelle_m))) fuori = [p for p in cima_r if coperta(p)] cima_r = [p for p in cima_r if not coperta(p)] dentro, fuori_sezioni = ([], []) for s in sezioni_r: if s[0][0] == 'tabella' and s[0][1] in tabelle_m: fuori_sezioni.append(s) elif s[0][0] == 'lista': dentro.append(s) else: dentro.append([s[0]] + [p for p in s[1:] if not coperta(p)]) if any((coperta(p) for p in s[1:])): fuori_sezioni.append([s[0]] + [p for p in s[1:] if coperta(p)]) fuori += [p for s in sorted(fuori_sezioni, key=lambda s: s[0][1]) for p in s] 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), '#= ') try: import tomllib except ImportError: tomllib = None if tomllib: try: tomllib.loads(nuovo) except tomllib.TOMLDecodeError as e: print(F('mie_codex_scontro', file=file, errore=e), file=sys.stderr) nuovo, scritte = (senza, []) if nuovo != testo: os.makedirs(casa, exist_ok=True) with open(conf + '.nuovo', 'w', encoding='utf-8') as h: h.write(nuovo) os.chmod(conf + '.nuovo', 384) os.replace(conf + '.nuovo', conf) _stampa_chiavi(scritte) return 0 def opzioni_dello_strato(cli, args): gruppi, i, chiavi = ([], 0, OPZIONI_CHIAVE.get(cli, {})) while i < len(args): a = args[i] nome, _, valore = a.partition('=') if cli == 'codex' and a in ('-c', '--config') and (i + 1 < len(args)): gruppi.append((args[i + 1].split('=', 1)[0].strip(), args[i:i + 2])) i += 2 elif nome in chiavi and valore: gruppi.append((chiavi[nome], [a])) i += 1 elif a in chiavi and i + 1 < len(args): gruppi.append((chiavi[a], args[i:i + 2])) i += 2 else: gruppi.append((None, [a])) i += 1 return gruppi def chiavi_della_riga(cli, della_riga): return ','.join(sorted({k for k, _ in opzioni_dello_strato(cli, della_riga) if k})) def righe_dello_strato(cli, di_serie, della_riga, variabile): righe = ['set -- ' + ' '.join((_q(a) for a in della_riga)) + ' "$@"'] if della_riga else [] for chiave, gruppo in reversed(opzioni_dello_strato(cli, di_serie)): metti = 'set -- ' + ' '.join((_q(a) for a in gruppo)) + ' "$@"' if not chiave: righe.append(metti) continue parti = chiave.split('.') casi = '|'.join(('*"|' + '.'.join(parti[:n]) + '|"*' for n in range(1, len(parti) + 1))) righe.append(f'case "${{{variabile}:-}}" in {casi}) ;; *) {metti} ;; esac') return righe def chiave_qwen(riga): tipo = (riga.get('fornitore') or {}).get('tipo') fisso = ((riga.get('_fornitori') or {}).get(tipo) or {}).get('chiave') return fisso if fisso else re.sub('[^A-Z0-9]+', '_', riga['nome'].upper()).strip('_') + '_API_KEY' def impostazioni_qwen(riga): f = riga.get('fornitore') or {} info = (riga.get('_fornitori') or {}).get(f.get('tipo')) or {} if not info: raise RuntimeError(F('fornitore_ignoto', fornitore=f.get('tipo') or '')) spente = {} if (riga.get('scelte') or {}).get('telemetria') == 'accesa' else {'privacy': {'usageStatisticsEnabled': False}, 'telemetry': {'enabled': False}} auth, modello = (info['auth'], riga.get('modello') or '') indirizzo = f.get('indirizzo') or info.get('indirizzo') or '' fa = info.get('formato_anthropic') or {} if fa.get('prefisso') and modello.startswith(fa['prefisso']): auth, indirizzo = ('anthropic', fa['indirizzo']) contesto = int(f.get('contesto') or 0) memoria = (riga.get('scelte') or {}).get('memoria') == 'accesa' base = riga.get('_base') or {} attesa = int(base.get('qwen.prima_parola_ms') or QWEN_PRIMA_PAROLA_MS) generazione = {'timeout': attesa, 'streamIdleTimeoutMs': attesa, **({'contextWindowSize': contesto} if contesto else {})} compatta, voluto = ({}, int(f.get('compatta') or 0)) finestra = contesto or (1000000 if auth == 'anthropic' and QWEN_CLAUDE_1M.search(modello) else 0) if finestra: soglia = min(1.0, voluto / finestra) if voluto else min(0.85, int(base.get('qwen.compatta') or QWEN_SOGLIA) / finestra) if voluto or soglia < 0.85: generazione['contextWindowSize'] = finestra compatta = {'context': {'autoCompactThreshold': round(soglia, 3)}} if info.get('auth') == 'anthropic': generazione['cacheRetention'] = '1h' fornitori = {auth: [{'id': modello, 'name': modello, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo} if indirizzo else {}), **({'generationConfig': generazione} if generazione else {})}]} veloce, extra = ((riga.get('scelte') or {}).get('classificatore') or '', {}) if veloce and veloce != modello: auth_v, indirizzo_v = (info['auth'], f.get('indirizzo') or info.get('indirizzo') or '') if fa.get('prefisso') and veloce.startswith(fa['prefisso']): auth_v, indirizzo_v = ('anthropic', fa['indirizzo']) fornitori.setdefault(auth_v, []).append({'id': veloce, 'name': veloce, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo_v} if indirizzo_v else {})}) extra = {'fastModel': veloce if auth_v == auth else f'{auth_v}:{veloce}'} 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'))} def della_riga_qwen(riga): sc, f = (riga.get('scelte') or {}, riga.get('fornitore') or {}) chiavi = ['modelProviders', 'model.name', 'security.auth'] if sc.get('classificatore'): chiavi.append('fastModel') if sc.get('telemetria'): chiavi += ['privacy.usageStatisticsEnabled', 'telemetry.enabled'] if sc.get('memoria'): chiavi += ['memory.enableManagedAutoMemory', 'memory.enableManagedAutoDream'] if f.get('compatta'): chiavi.append('context.autoCompactThreshold') if any(((x or {}).get('cli') == 'qwen' for x in riga.get('_skill') or [])): chiavi.append('skills') return ','.join(chiavi) def skill_qwen(scelte): spente, a_scelta = (list(QWEN_SKILL_SPENTE), list(QWEN_SKILL_A_SCELTA)) for x in scelte or []: nome = (x or {}).get('nome') if (x or {}).get('cli') != 'qwen' or not nome: continue if x.get('stato') == 'accesa': spente = [n for n in spente if n != nome] a_scelta = [n for n in a_scelta if n != nome] elif x.get('stato') == 'spenta' and nome not in spente and (nome not in a_scelta): a_scelta.append(nome) return {'disabled': spente, 'defaultDisabled': a_scelta} QWEN_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') QWEN_TOOL_LARGHI = ('agent', 'enter_plan_mode', 'exit_plan_mode') QWEN_SKILL_ACCESE = ('agent-delegation', 'batch', 'dataviz', 'extension-creator', 'new-app', 'review', 'simplify', 'stuck', 'zvec-grep-install') QWEN_SKILL_A_SCELTA = () QWEN_SKILL_SPENTE = ('auto-memory', 'autofix-pr', 'batch-api', 'coordinate', 'goal-draft', 'loop', 'qc-helper', 'workflow-authoring', 'workflow-creator') QWEN_CHIEDI = ('agent', 'workflow') QWEN_REVIEW = {'effort': 'low'} QWEN_SOGLIA = 300000 QWEN_PRIMA_PAROLA_MS = 60000 QWEN_CLAUDE_1M = re.compile('claude-(opus|sonnet|fable)-(5|4-[6-9])') def explore_qwen(): return '\n'.join(['---', 'name: Explore', 'description: ' + json.dumps(F('explore_descrizione'), ensure_ascii=False), 'tools:', ' - read_file', ' - grep_search', ' - glob', '---', '', F('explore_prompt')]) def _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file): out = [] if (scelta := (riga.get('fornitore') or {}).get('chiave')): if dal_repo: 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"' out += [f'T=$({leggi} FILE_TOKEN 2>/dev/null)', f'U=$({leggi} URL 2>/dev/null)'] 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""" else: 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')}""" 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 '')] elif tipo == 'casa': out.append(f'[ -n "${{{chiave}:-}}" ] || export {chiave}=nessuna') else: 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}""" 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'] return out def wrapper_qwen(riga, cli, modo, url, token_file): nome, porta = (riga['nome'], riga.get('porta')) impostazioni = impostazioni_qwen(riga) canale = canale_del_ruolo(spazio_di(url, _token_di(token_file)), porta) if personaggio(riga) else '' if canale: impostazioni['hooks'] = ganci_della_posta(canale) for g in impostazioni['hooks']['Stop'][0]['hooks']: g.pop('asyncRewake', None) g['timeout'] = 10 tipo = (riga.get('fornitore') or {}).get('tipo') chiave = chiave_qwen(riga) delle_scelte, env_scelte = lancio_delle_scelte(riga) fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or []))) casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12] node = os.path.join(node_di(os.path.dirname(os.path.dirname(os.path.dirname(cli)))), 'bin') 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)}'] if riga.get('ordine'): righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}") for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()): if re.fullmatch('[A-Z_][A-Z0-9_]*', k): righe.append(f'export {k}={_q(v)}') dal_repo = modo == 'kit' and bool(porta) if dal_repo: righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome)) righe += _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file) 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'] if canale: righe.append('mkdir -p "$QWEN_HOME/commands"') for gesto, (descrizione, _corpo) in _SKILL_DEL_RITO.items(): righe += [f"""cat > "$QWEN_HOME/commands/{gesto}.md" <<'RITO'""", f'---\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\n---\n{gesto}', 'RITO'] righe += [f'export DELMINIO_CANALE_RUOLO={_q(canale)}'] if dal_repo: righe += [f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}"] if canale: righe += _fuori_dal_suo_spazio(nome, spazio_di(url, _token_di(token_file))) righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"') righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file))) righe += _righe_al_lancio(modo, url, token_file) righe.append(_riga_exec('bash "$r/.claude/delminio.sh" qwen', fissi, '"$@"')) return '\n'.join(righe) + '\n' if porta: righe += _righe_del_prompt(riga, url, token_file) righe += [f'export DELMINIO_PORTA={_q(porta)}', 'export QWEN_SYSTEM_MD="$F"'] if canale: righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}') if riga.get('cartella'): righe.append(f"cd {_q(riga['cartella'])} || exit 1") righe += _righe_al_lancio(modo, url, token_file) righe.append(_riga_exec(_q(cli), fissi, '"$@"')) return '\n'.join(righe) + '\n' def opencode_v2(versione): return str(versione).split('.', 1)[0] == '2' OPENCODE_SOGLIA = 300000 OPENCODE_PRIMA_PAROLA_MS = 60000 def config_opencode(riga, versione): f = riga.get('fornitore') or {} tipo = f.get('tipo') info = (riga.get('_fornitori') or {}).get(tipo) or {} if not info: raise RuntimeError(F('fornitore_ignoto', fornitore=tipo or '')) modello = riga.get('modello') or '' anthropic = info.get('auth') == 'anthropic' contesto = int(f.get('contesto') or 0) finestra = contesto or (1000000 if anthropic and QWEN_CLAUDE_1M.search(modello) else 0) base_spazio = riga.get('_base') or {} voluto = int(f.get('compatta') or 0) if finestra: soglia = min(voluto, finestra) if voluto else min(int(finestra * 0.85), int(base_spazio.get('opencode.compatta') or OPENCODE_SOGLIA)) riserva = finestra - soglia else: riserva = '15%' base = {'update': 'disable', 'share': 'disabled', 'compaction': {'background': False, 'buffer': riserva}} if tipo == 'zen': return {**base, 'model': f'opencode/{modello}'} if modello else base chiave = chiave_qwen(riga) indirizzo = '' if anthropic else f.get('indirizzo') or info.get('indirizzo') or '' attesa = int(base_spazio.get('opencode.prima_parola_ms') or OPENCODE_PRIMA_PAROLA_MS) impostazioni = {**({'baseURL': indirizzo} if indirizzo else {}), 'headerTimeout': attesa, 'chunkTimeout': attesa} 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 {})}}} return {**base, 'providers': {'delminio': fornitore}, 'model': f'delminio/{modello}'} def wrapper_opencode(riga, cli, modo, url, token_file): nome, porta = (riga['nome'], riga.get('porta')) if modo != 'kit': return '\n'.join([*_testa_del_wrapper(riga), 'echo ' + _sh(F('wrapper_opencode_solo_kit', nome=nome)) + ' >&2', 'exit 1']) + '\n' versione = os.path.basename(os.path.dirname(os.path.dirname(cli))) tipo = (riga.get('fornitore') or {}).get('tipo') delle_scelte, env_scelte = lancio_delle_scelte(riga) fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or []))) 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)}'] if riga.get('ordine'): righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}") for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()): if re.fullmatch('[A-Z_][A-Z0-9_]*', k): righe.append(f'export {k}={_q(v)}') righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome)) if tipo != 'zen': righe.append('export OPENCODE_DISABLE_MODELS_FETCH=1 # ' + F('commento_catalogo_opencode')) righe += _righe_della_chiave(riga, chiave_qwen(riga), tipo, nome, True, url, token_file) if porta: righe.append(f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}") righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file))) elif riga.get('cartella'): righe.append(f"cd {_q(riga['cartella'])} || exit 1") righe += _righe_al_lancio(modo, url, token_file) righe.append(_riga_exec('bash "$r/.claude/delminio.sh" opencode', fissi, '"$@"')) return '\n'.join(righe) + '\n' def _fuori_dal_suo_spazio(nome, spazio): 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'] def righe_della_casa(riga, nome, spazio): if (riga.get('scelte') or {}).get('casa') != 'separata': return [f"cd {_q(riga['cartella'])} || exit 1"] if riga.get('cartella') else [] dove = _q(riga['cartella']) if riga.get('cartella') else '' 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'] def wrapper(riga, cli, modo, url, token_file): if riga.get('cli') == 'codex': return wrapper_codex(riga, cli, modo, url, token_file) if riga.get('cli') == 'qwen': return wrapper_qwen(riga, cli, modo, url, token_file) if riga.get('cli') == 'opencode': return wrapper_opencode(riga, cli, modo, url, token_file) nome = riga['nome'] args = [] if riga.get('modello'): args += ['--model', riga['modello']] if riga.get('effort'): args += ['--effort', riga['effort']] delle_scelte, env_scelte = lancio_delle_scelte(riga) env_scelte = {**(riga.get('_promemoria') or {}), **env_scelte} args += delle_scelte + list(riga.get('argomenti') or []) if personaggio(riga): spazio = spazio_di(url, _token_di(token_file)) canale = canale_del_ruolo(spazio, riga['porta']) args = con_i_ganci(args, ganci_della_posta(canale)) args += ['--mcp-config', canale, '--allowedTools', f'mcp__{SERVER_RUOLO}__delminio,mcp__{SERVER_RUOLO}__delminio_write'] args += ['--plugin-dir', _rito_del_ruolo()] fissi = ' '.join((_q(a) for a in args)) righe = [*_testa_del_wrapper(riga), 'export DISABLE_AUTOUPDATER=1 # ' + F('commento_autoupdater')] if riga.get('ordine'): righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}") for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()): if re.fullmatch('[A-Z_][A-Z0-9_]*', k): righe.append(f'export {k}={_q(v)}') porta = riga.get('porta') if modo == 'kit': if porta: 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)}"] if personaggio(riga): righe += _fuori_dal_suo_spazio(nome, spazio) righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file))) if personaggio(riga): righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"') righe += _righe_al_lancio(modo, url, token_file) righe.append(_riga_exec('bash "$r/.claude/delminio.sh" claude', fissi, '"$@"')) return '\n'.join(righe) + '\n' elif porta: righe += _righe_del_prompt(riga, url, token_file) righe.append(f'export DELMINIO_PORTA={_q(porta)}') if personaggio(riga): righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}') if riga.get('cartella'): righe.append(f"cd {_q(riga['cartella'])} || exit 1") prompt = ' --system-prompt-file "$F"' if porta and modo != 'kit' else '' righe += _righe_al_lancio(modo, url, token_file) righe.append(_riga_exec(_q(cli), fissi, prompt.strip(), '"$@"')) return '\n'.join(righe) + '\n' PROMEMORIA_AMMESSI = frozenset({'CLAUDE_CODE_SILENT_TURN_REMINDER_TEXT', 'CLAUDE_CODE_SILENT_TURN_REMINDER'}) def parte_libera(riga): 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()}} def impronta_libera(riga): return hashlib.sha256(json.dumps([str(riga.get('nome') or ''), parte_libera(riga)], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24] def da_accettare(riga, accettati): p = parte_libera(riga) return bool(p['argomenti'] or p['ambiente']) and impronta_libera(riga) not in accettati def _visibile_riga(v): return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v))) def accetta(registro): mio = _leggi(registro) fermi = [(url, x) for url, sp in (mio.get('spazi') or {}).items() for x in sp.get('fermi') or [] if isinstance(x, dict)] if not fermi: return 0 try: tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w')) except OSError: print(F('accetta_senza_terminale'), file=sys.stderr) return 1 accettati, presi, restano = (set(mio.get('accettati') or []), set(), 0) for url, x in fermi: p = parte_libera(x) 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 '—'))) tty.flush() if tty_in.readline().strip().lower() in F('accetta_si').split(): accettati.add(impronta_libera(x)) presi.add(url) else: restano += 1 mio = _leggi(registro) mio['accettati'] = sorted(set(mio.get('accettati') or []) | accettati) for url in presi: (mio.get('spazi') or {}).get(url, {})['registro'] = '' _scrivi(registro, mio) print(F('accetta_righe_esito', nuovi=len(fermi) - restano, restano=restano)) return 0 def _impronta(testo): return hashlib.sha256(testo.encode('utf-8')).hexdigest()[:16] def _del_file(p): try: with open(p, encoding='utf-8') as f: return _impronta(f.read()) except (OSError, UnicodeDecodeError): return None _DIARIO_MAX = 1000000 def _nel_diario(registro, percorso, prima, dopo, vecchio, nuovo): diario = os.path.join(os.path.dirname(registro) or '.', 'eseguibili-diario.log') righe = [r for r in difflib.unified_diff((vecchio or '').splitlines(), nuovo.splitlines(), lineterm='', n=0) if not r.startswith(('---', '+++'))] testa = f"── {time.strftime('%Y-%m-%d %H:%M:%S')} {percorso} · CLI {prima or '—'} → {dopo}" try: if os.path.exists(diario) and os.path.getsize(diario) > _DIARIO_MAX: with open(diario, encoding='utf-8', errors='replace') as f: resto = f.read()[-_DIARIO_MAX // 2:] with open(diario, 'w', encoding='utf-8') as f: f.write(resto[resto.find('\n── ') + 1:] if '\n── ' in resto else resto) with open(os.open(diario, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384), 'a', encoding='utf-8') as f: f.write('\n'.join([testa, *righe]) + '\n') except OSError: pass return sum((1 for r in righe if r.startswith(('+', '-')))) _SEGNO_CASA = 'export DELMINIO_SISTEMA="$F"' def _di_casa(p): try: with open(p, encoding='utf-8') as f: return _SEGNO_CASA in f.read() except (OSError, UnicodeDecodeError): return False def _leggi(path): try: with open(path, encoding='utf-8') as f: return json.load(f) except (OSError, ValueError): return {} _CHIAVE_PER_SPAZIO = 1792090627 def _spazio(mio, url): spazi = mio.setdefault('spazi', {}) base = url.split('#', 1)[0] 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))): spazi[url] = spazi.pop(base) for chi in mio.get('padroni', {}).values(): chi[:] = [url if u == base else u for u in chi] if url not in spazi: s = spazi[url] = {} if len(spazi) == 1: for k in ('registro', 'quando', 'rifiutato', 'cli'): if k in mio: s[k] = mio.pop(k) for p in mio.get('eseguibili', {}): mio.setdefault('padroni', {}).setdefault(p, [url]) return spazi[url] def _scrivi(path, dati): os.makedirs(os.path.dirname(path), mode=448, exist_ok=True) with open(path + '.nuovo', 'w', encoding='utf-8') as f: json.dump(dati, f, ensure_ascii=False, indent=1) os.replace(path + '.nuovo', path) def _cli_del_wrapper(p): try: with open(p, encoding='utf-8') as f: testo = f.read() except OSError: return '' m = re.search('/versions(?:-pinned)?/(\\d+\\.\\d+\\.\\d+)', testo) return m.group(1) if m else '?' def sul_disco(versioni): try: return sorted((f for f in os.listdir(versioni) if _VERSIONE.match(f)), key=_v, reverse=True) except OSError: return [] def nudo(bin_dir, versioni): p = os.path.join(bin_dir, 'claude') if not os.path.lexists(p): return '' vero = os.path.realpath(p) if os.path.dirname(vero) == os.path.realpath(versioni) and _VERSIONE.match(os.path.basename(vero)): return os.path.basename(vero) return 'altro' def pulisci(bin_dir, versioni, scelte=None): usate = set() cartelle = {os.path.realpath(versioni), os.path.abspath(os.path.expanduser(versioni))} voce = re.compile('(?:%s|/versions(?:-pinned)?)/(\\d+\\.\\d+\\.\\d+)' % '|'.join((re.escape(c) for c in cartelle))) try: nomi = [os.path.join(bin_dir, n) for n in os.listdir(bin_dir)] except OSError: nomi = [] for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else (): nomi += [os.path.join(radice, n) for n in file] for p in nomi: if os.path.islink(p): vero = os.path.realpath(p) if os.path.dirname(vero) == os.path.realpath(versioni): usate.add(os.path.basename(vero)) continue try: if os.path.isfile(p) and os.path.getsize(p) < 200000: with open(p, encoding='utf-8', errors='ignore') as f: usate.update(voce.findall(f.read())) except OSError: pass if (n := nudo(bin_dir, versioni)) and n != 'altro': usate.add(n) libere = [v for v in sul_disco(versioni) if v not in usate] alta = max((v for v in usate if _VERSIONE.match(v)), key=_v, default=None) prima = [v for v in libere if alta and _v(v) < _v(alta)] riparo = (prima or libere)[:1] if scelte is not None: riparo = [v for v in libere if v not in scelte] tolte, errori = ([], []) for v in [x for x in libere if x not in riparo]: try: os.remove(os.path.join(versioni, v)) tolte.append(v) except OSError as e: errori.append(f'{v}: {e.strerror}') esito = {'tolte': tolte, 'tenute': sorted(usate | set(riparo), key=_v, reverse=True)} if scelte is not None: riparo = [] if errori: esito['errore'] = '; '.join(errori)[:300] 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 '')) return esito def _cosa_lancia(bin_dir): nomi = [os.path.join(bin_dir, n) for n in (os.listdir(bin_dir) if os.path.isdir(bin_dir) else ())] for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else (): nomi += [os.path.join(radice, n) for n in file] testi = [] for p in nomi: try: if os.path.islink(p): testi.append(os.path.realpath(p)) elif os.path.isfile(p) and os.path.getsize(p) < 200000: with open(p, encoding='utf-8', errors='ignore') as f: testi.append(f.read()) except OSError: pass if os.path.isdir('/proc'): for pid in os.listdir('/proc'): if pid.isdigit(): try: with open(f'/proc/{pid}/cmdline', 'rb') as f: testi.append(f.read().replace(b'\x00', b' ').decode(errors='ignore')) testi.append(os.readlink(f'/proc/{pid}/exe')) except OSError: pass else: try: testi.append(subprocess.run(['ps', '-axww', '-o', 'comm=', '-o', 'command='], capture_output=True, text=True, errors='ignore', timeout=20, check=True).stdout) except (OSError, subprocess.SubprocessError): return None return '\n'.join(testi) def pota(bin_dir, cartelle, nudo_claude=''): testo, tolte = (_cosa_lancia(bin_dir), []) if testo is None: return tolte def via(dove, nome): try: shutil.rmtree(dove) if os.path.isdir(dove) and (not os.path.islink(dove)) else os.remove(dove) tolte.append(nome) except OSError: pass for cartella in [c for c in cartelle if c and os.path.isdir(c)]: radici = '|'.join((re.escape(c) for c in {os.path.realpath(cartella), os.path.abspath(cartella)})) usate = set(re.findall('(?:%s)/(\\d+\\.\\d+\\.\\d+)' % radici, testo)) | {nudo_claude} for v in sul_disco(cartella): if v not in usate: via(os.path.join(cartella, v), v) sopra = os.path.realpath(os.path.dirname(os.path.normpath(cartella))) nodi = set(re.findall('%s/(node-\\d[\\w.]*)' % re.escape(sopra), testo)) for n in os.listdir(sopra) if nodi else (): if n.startswith('node-') and n not in nodi and os.path.isdir(os.path.join(sopra, n)): via(os.path.join(sopra, n), n) if tolte: print(F('potate', tolte=', '.join(tolte)), flush=True) return tolte def riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte=None, esito=None, senza_cli=()): stato = [] for r in righe: p = os.path.join(bin_dir, r['nome']) ora = _del_file(p) intatto = ora is not None and impronte.get(p) == ora cli = (scritte or {}).get(p, '') if intatto else _cli_del_wrapper(p) if ora else '' 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'}) corpo = {'host': socket.gethostname(), 'righe': stato, 'registro': registro, 'disco': sul_disco(versioni), 'nudo': nudo(bin_dir, versioni)} if esito: corpo['esito'] = esito try: return json.loads(_get(f'{base}/macchina', token, metodo='POST', corpo=corpo, timeout=10) or b'{}') except (OSError, ValueError, urllib.error.URLError): return {} INSTALLABILI = tuple(CLI_NOMI) def richiesta(base, token, risposta, righe, impronte, bin_dir, versioni, registro, scritte, mio=None, file_mio=''): r = (risposta or {}).get('richiesta') or {} if r.get('pulizia'): scelte = r.get('versioni') esito = pulisci(bin_dir, versioni, scelte if isinstance(scelte, list) else None) riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito=esito) nuove = {c for c in r.get('installa') or [] if c in INSTALLABILI} if nuove and mio is not None and file_mio: mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | nuove) _scrivi(file_mio, mio) print(F('installo_chiesta', cli=', '.join(sorted(nuove))), flush=True) riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito={'installate': sorted(nuove)}) return True return False SEGNO_SMISTA = '# delminio-più-spazi' _DIR_COMANDI = [''] def cartella_dei_comandi(registro): return os.path.join(os.path.dirname(registro) or '.', 'comandi') def comando_dello_spazio(spazio, nome): return os.path.join(_DIR_COMANDI[0], cartella_dello_spazio(spazio), nome) def cartella_dello_spazio(spazio): return re.sub('[^A-Za-z0-9._-]', '_', spazio) def come_si_chiama(spazio): if '#' in spazio: return spazio.rsplit('#', 1)[1] return urllib.parse.urlsplit(spazio).netloc or spazio def e_smistatore(p): try: with open(p, encoding='utf-8') as f: return SEGNO_SMISTA in f.read() except (OSError, UnicodeDecodeError): return False def smistatore(nome, spazi): elenco = ', '.join((come_si_chiama(s) for s in spazi)) dove = _q(_DIR_COMANDI[0]) 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' def _scrivi_eseguibile(p, testo): os.makedirs(os.path.dirname(p), mode=448, exist_ok=True) with open(p + '.nuovo', 'w', encoding='utf-8') as f: f.write(testo) os.chmod(p + '.nuovo', 493) os.replace(p + '.nuovo', p) def dividi(p, url, testo, padroni, impronte): chi = padroni.get(p) or [] nuovo = not e_smistatore(p) if nuovo: with open(p, encoding='utf-8') as f: di_prima = f.read() for u in chi: if u != url: q = comando_dello_spazio(u, os.path.basename(p)) _scrivi_eseguibile(q, di_prima) impronte[q] = _impronta(di_prima) q = comando_dello_spazio(url, os.path.basename(p)) _scrivi_eseguibile(q, testo) impronte[q] = _impronta(testo) if url not in chi: chi.append(url) padroni[p] = chi rifai_smistatore(p, chi, impronte) return nuovo def rifai_smistatore(p, chi, impronte): t = smistatore(os.path.basename(p), chi) if _del_file(p) != _impronta(t): _scrivi_eseguibile(p, t) impronte[p] = _impronta(t) def lascia_il_nome(p, url, padroni, impronte): chi = padroni.get(p) or [] if url in chi: chi.remove(url) smista = e_smistatore(p) and impronte.get(p) == _del_file(p) if smista: q = comando_dello_spazio(url, os.path.basename(p)) if impronte.get(q) and _del_file(q) == impronte[q]: os.remove(q) impronte.pop(q, None) if not chi: tolto = os.path.exists(p) and _del_file(p) == impronte.get(p) if tolto: os.remove(p) impronte.pop(p, None) padroni.pop(p, None) return 'tolto' if tolto else 'resta' if not smista: return 'altri' if len(chi) > 1: rifai_smistatore(p, chi, impronte) return 'altri' q = comando_dello_spazio(chi[0], os.path.basename(p)) if impronte.get(q) and _del_file(q) == impronte[q]: with open(q, encoding='utf-8') as f: suo = f.read() _scrivi_eseguibile(p, suo) impronte[p] = _impronta(suo) os.remove(q) impronte.pop(q, None) return 'tornato' rifai_smistatore(p, chi, impronte) return 'altri' _SKILL_PROGETTO = (('.claude/skills', ('claude',)), ('.agents/skills', ('codex', 'qwen')), ('.qwen/skills', ('qwen',))) _SKILL_TETTO = 300 def _skill_testa(percorso): try: with open(percorso, 'rb') as h: crudo = h.read(200000) except OSError: return None testo = crudo.decode('utf-8', errors='replace') m = re.match('^---\\s*\\n(.*?)\\n---\\s*(\\n|$)', testo, re.S) testa = m.group(1) if m else '' def campo(nome): c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M) if not c: return '' v = ' '.join(c.group(1).split()) if v[:1] in '"\'' and v[-1:] == v[:1]: v = v[1:-1] return '' if v in ('>', '|', '>-', '|-') else v nome = campo('name') or os.path.basename(os.path.dirname(percorso)) return {'nome': nome, 'descrizione': campo('description')[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16]} def _skill_in(cartella): if not os.path.isdir(cartella): return [] out = [] for n in sorted(os.listdir(cartella)): p = os.path.join(cartella, n, 'SKILL.md') if not n.startswith('.') and os.path.isfile(p): t = _skill_testa(p) if t: out.append((t, p)) return out def _da_leggere(p, radice): casa = os.path.expanduser('~') if radice and p.startswith(radice + os.sep): return os.path.relpath(os.path.dirname(p), radice) if p.startswith(casa + os.sep): return '~/' + os.path.relpath(os.path.dirname(p), casa) return os.path.dirname(p) def _case_codex(): base = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'codex') 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')))) def _blocchi_codex(testo): out = {} for b in re.split('(?m)^\\[\\[skills\\.config\\]\\]\\s*$', testo)[1:]: corpo = re.split('(?m)^\\[', b, maxsplit=1)[0] p = re.search('(?m)^path\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"', corpo) e = re.search('(?m)^enabled\\s*=\\s*(true|false)', corpo) if p: out[json.loads('"' + p.group(1) + '"')] = not (e and e.group(1) == 'false') return out def _claude_scelte(radice): out = {} cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') for f in (os.path.join(cfg, 'settings.json'), os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')): s = _leggi(f) if isinstance(s.get('skillOverrides'), dict): out.update(s['skillOverrides']) return out _STATO_CLAUDE = {'on': 'accesa', 'name-only': 'accesa', 'user-invocable-only': 'a_mano', 'off': 'spenta'} def _qwen_stato(nome, livello, scelte): voluta = scelte.get(('qwen', nome)) if voluta: return 'accesa' if voluta == 'accesa' else 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano' if livello != 'di_serie': return 'accesa' return 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano' if nome in QWEN_SKILL_A_SCELTA else 'accesa' def _progetto(radice): remoto = '' if radice: try: remoto = subprocess.run(['git', '-C', radice, 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, timeout=5).stdout.strip() except (OSError, subprocess.SubprocessError): remoto = '' return 'progetto:' + (re.sub('//[^/@]*@', '//', remoto) or os.path.basename(radice or '')) def raccogli_skill(radice, versioni_qwen, scelte=None): scelte = scelte or {} carte = [] progetto = _progetto(radice) claude = _claude_scelte(radice) if radice else {} case = _case_codex() codex_blocchi = {} for casa in case: with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h: codex_blocchi.update(_blocchi_codex(h.read())) def stato(cli, nome, livello, percorsi): out = {} for c in cli: if c == 'claude': out[c] = _STATO_CLAUDE.get(claude.get(nome, 'on'), 'accesa') elif c == 'codex': out[c] = 'spenta' if any((codex_blocchi.get(p) is False for p in percorsi)) else 'accesa' elif c == 'qwen': out[c] = _qwen_stato(nome, livello, scelte) return out def metti(livello, dove, cartella, cli): for t, p in _skill_in(cartella): carte.append({**t, 'livello': livello, 'dove': dove, 'cartella': _da_leggere(p, radice), 'cli': list(cli), 'stato': stato(cli, t['nome'], livello, [p])}) if radice: for rel, cli in _SKILL_PROGETTO: metti('progetto', progetto, os.path.join(radice, rel), cli) cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') metti('personale', 'personale', os.path.join(cfg, 'skills'), ('claude',)) metti('personale', 'personale', os.path.expanduser('~/.agents/skills'), ('codex', 'qwen')) metti('personale', 'personale', os.path.expanduser('~/.qwen/skills'), ('qwen',)) viste = set() for casa in case: for t, p in _skill_in(os.path.join(casa, 'skills', '.system')): if t['nome'] not in viste: viste.add(t['nome']) 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])}) metti('personale', 'personale', os.path.join(casa, 'skills'), ('codex',)) 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('.')))) if qv: for t, _p in _skill_in(os.path.join(versioni_qwen, qv[-1], 'lib', 'node_modules', '@qwen-code', 'qwen-code', 'bundled')): carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'qwen ' + qv[-1], 'cli': ['qwen'], 'stato': stato(('qwen',), t['nome'], 'di_serie', [])}) pacchetto = os.path.join(radice or '', '.claude', 'plugin.py') if radice and os.path.isfile(pacchetto) and shutil.which(os.environ.get('DELMINIO_CLI') or 'claude'): try: di_claude = runpy.run_path(pacchetto).get('SKILL_CLAUDE') or {} except Exception: di_claude = {} for nome in sorted(di_claude): carte.append({'nome': nome, 'descrizione': '', 'impronta': '', 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'claude', 'cli': ['claude'], 'stato': stato(('claude',), nome, 'di_serie', [])}) carte += raccogli_pezzi(radice, progetto) return carte[:_SKILL_TETTO] _COMANDI = (('.claude/commands', 'claude'), ('.qwen/commands', 'qwen')) _AGENTI = (('.claude/agents', 'claude'), ('.qwen/agents', 'qwen')) _PEZZO_PESO = 100000 _CHIAVE_FLAG = re.compile('^--?(?:[\\w-]*(?:token|key|secret|password|passwd|pass|auth|credential)[\\w-]*)$', re.I) _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,}$)') NASCOSTO = '•••' def _testa_md(testo): m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S) testa, corpo = (m.group(1), testo[m.end():]) if m else ('', testo) def campo(nome): c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M) if not c: return '' v = ' '.join(c.group(1).split()) if v[:1] in '"\'' and v[-1:] == v[:1]: v = v[1:-1] return '' if v in ('>', '|', '>-', '|-') else v return (campo, corpo) def _prima_riga(corpo): for r in corpo.splitlines(): r = r.strip().lstrip('#').strip() if r: return r[:200] return '' def _toml_stringa(testo, chiave): m = re.search('(?m)^' + re.escape(chiave) + '\\s*=\\s*("""(.*?)"""|\\\'\\\'\\\'(.*?)\\\'\\\'\\\'|"((?:[^"\\\\\\n]|\\\\.)*)"|\\\'([^\\\'\\n]*)\\\')', testo, re.S) if not m: return '' if m.group(4) is not None: try: return json.loads('"' + m.group(4) + '"') except ValueError: return m.group(4) return next((g for g in (m.group(2), m.group(3), m.group(5)) if g is not None)) def _scheda_file(p, rel_nome, cli, tipo): try: with open(p, 'rb') as h: crudo = h.read(_PEZZO_PESO + 1) except OSError: return None testo = crudo.decode('utf-8', errors='replace') if p.endswith('.toml'): descrizione, nome = (_toml_stringa(testo, 'description'), rel_nome) else: campo, corpo = _testa_md(testo) nome = (campo('name') if tipo == 'agente' else '') or rel_nome descrizione = campo('description') or (_prima_riga(corpo) if tipo == 'comando' else '') return {'nome': nome, 'descrizione': descrizione[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16], 'tipo': tipo, 'cli': [cli], 'stato': {}} def _file_in(cartella, estensioni, ricorsivo): if not os.path.isdir(cartella): return [] out = [] for base, cartelle, nomi in os.walk(cartella): cartelle[:] = sorted((c for c in cartelle if not c.startswith('.'))) if ricorsivo else [] for n in sorted(nomi): p = os.path.join(base, n) if n.startswith('.') or not n.endswith(estensioni) or (not os.path.isfile(p)): continue rel = os.path.relpath(p, cartella) out.append((p, os.path.splitext(rel)[0].replace(os.sep, ':'))) return out def _cartella_da_leggere(p, radice): casa = os.path.expanduser('~') if radice and p.startswith(radice + os.sep): return os.path.relpath(p, radice) if p.startswith(casa + os.sep): return '~/' + os.path.relpath(p, casa) return p def _argomenti_puliti(argomenti): out, dopo_flag = ([], False) for a in argomenti or []: a = str(a) if '=' in a and _CHIAVE_FLAG.match(a.split('=', 1)[0]): out.append(a.split('=', 1)[0] + '=' + NASCOSTO) elif dopo_flag or _CHIAVE_VALORE.search(a) or '${' in a: out.append(NASCOSTO) else: out.append(a[:500]) dopo_flag = bool(_CHIAVE_FLAG.match(a)) and '=' not in a return out[:40] def _url_pulito(url): try: u = urllib.parse.urlsplit(str(url or '')) except ValueError: return '' if u.scheme not in ('http', 'https') or not u.hostname: return '' host = u.netloc.rpartition('@')[2] return urllib.parse.urlunsplit((u.scheme, host, u.path, '', ''))[:500] def _variabile_del_token(intestazioni): for k, v in (intestazioni or {}).items(): m = re.fullmatch('(?:Bearer\\s+)?\\$\\{?([A-Za-z_][A-Za-z0-9_]{0,63})\\}?', str(v or '').strip()) if str(k).lower() == 'authorization' and m: return m.group(1) return '' def _server(nome, d, cli, livello, dove, cartella): if not isinstance(d, dict): return None url = d.get('url') or d.get('httpUrl') or '' intest = {} for k in ('headers', 'http_headers', 'env_http_headers'): if isinstance(d.get(k), dict): intest.update(d[k]) if url: token = str(d.get('bearer_token_env_var') or '') or _variabile_del_token(intest) mcp = {'tipo': 'remoto', 'url': _url_pulito(url), 'intestazioni': sorted((str(k) for k in intest))[:20]} if token: mcp['token_variabile'] = token elif d.get('command'): variabili = set(d['env']) if isinstance(d.get('env'), dict) else set() variabili |= {str(v) for v in d.get('env_vars') or [] if isinstance(v, str)} 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]} else: return None 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} def _toml_tabelle(testo, radice_tabella): try: import tomllib d = tomllib.loads(testo).get(radice_tabella) return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {} except ImportError: pass except ValueError: return {} out = {} for m in re.finditer('(?m)^\\[' + re.escape(radice_tabella) + '\\.("[^"\\n]+"|[A-Za-z0-9_-]+)(\\.[A-Za-z_]+)?\\]\\s*$', testo): nome = m.group(1).strip('"') corpo = re.split('(?m)^\\[', testo[m.end():], maxsplit=1)[0] campi = out.setdefault(nome, {}) if m.group(2): campi[m.group(2)[1:]] = {k.strip('"'): '' for k in re.findall('(?m)^("[^"\\n]+"|[A-Za-z0-9_-]+)\\s*=', corpo)} continue for chiave, valore in re.findall('(?m)^([A-Za-z_]+)\\s*=\\s*(.+?)\\s*$', corpo): if valore.startswith('{'): campi[chiave] = {k.strip('"'): '' for k in re.findall('("[^"]+"|[A-Za-z0-9_-]+)\\s*=', valore)} else: try: campi[chiave] = json.loads(valore) except ValueError: campi[chiave] = valore.strip("'") return out def _codex_config(radice): out = [] if radice: out.append((os.path.join(radice, '.codex', 'config.toml'), 'progetto')) casa = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex') out.append((os.path.join(casa, 'config.toml'), 'personale')) out += [(os.path.join(c, 'config.toml'), 'personale') for c in _case_codex()] return [(p, l) for p, l in out if os.path.isfile(p)] def raccogli_pezzi(radice, progetto): carte = [] cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') casa_qwen = os.path.expanduser('~/.qwen') def file_di(tipo, coppie_progetto, personali, estensioni, ricorsivo): dove_cli = [(os.path.join(radice, rel), cli, 'progetto', progetto) for rel, cli in coppie_progetto] if radice else [] dove_cli += [(c, cli, 'personale', 'personale') for c, cli in personali] for cartella, cli, livello, dove in dove_cli: for p, rel_nome in _file_in(cartella, estensioni(cli), ricorsivo): if (s := _scheda_file(p, rel_nome, cli, tipo)): carte.append({**s, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(p, radice)}) 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) file_di('agente', _AGENTI, [(os.path.join(cfg, 'agents'), 'claude'), (os.path.join(casa_qwen, 'agents'), 'qwen')], lambda cli: ('.md',), False) def server_json(percorso, chiavi, cli, livello, dove): d = _leggi(percorso) for k in chiavi: d = d.get(k) if isinstance(d, dict) else None for nome, s in (d or {}).items() if isinstance(d, dict) else []: if (x := _server(nome, s, cli, livello, dove, _cartella_da_leggere(percorso, radice))): carte.append(x) 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') if radice: server_json(os.path.join(radice, '.mcp.json'), ['mcpServers'], 'claude', 'progetto', progetto) server_json(os.path.join(radice, '.qwen', 'settings.json'), ['mcpServers'], 'qwen', 'progetto', progetto) server_json(stato_claude, ['projects', radice, 'mcpServers'], 'claude', 'personale', 'personale') server_json(stato_claude, ['mcpServers'], 'claude', 'personale', 'personale') server_json(os.path.join(casa_qwen, 'settings.json'), ['mcpServers'], 'qwen', 'personale', 'personale') visti = set() for percorso, livello in _codex_config(radice): try: with open(percorso, encoding='utf-8', errors='replace') as h: testo = h.read() except OSError: continue dove = progetto if livello == 'progetto' else 'personale' for nome, s in _toml_tabelle(testo, 'mcp_servers').items(): if (livello, 'mcp', nome) not in visti and (x := _server(nome, s, 'codex', livello, dove, _cartella_da_leggere(percorso, radice))): visti.add((livello, 'mcp', nome)) carte.append(x) for nome, s in _toml_tabelle(testo, 'agents').items(): if (livello, 'agente', nome) not in visti: visti.add((livello, 'agente', nome)) 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)}) return carte def applica_skill(radice, scelte, fatte): ora = {f'{c}:{n}': v for (c, n), v in scelte.items()} via = [k for k in fatte or [] if k not in ora] pacchetto = os.path.join(radice or '', '.claude', 'plugin.py') try: p = runpy.run_path(pacchetto) if os.path.isfile(pacchetto) else {} except Exception: p = {} di_serie_claude, spente_codex = (p.get('SKILL_CLAUDE') or {}, set(p.get('SKILL_CODEX_SPENTE') or ())) locale = os.path.join(radice or '', '.claude', 'settings.local.json') if radice and os.path.isfile(locale): s = _leggi(locale) so = s.get('skillOverrides') if isinstance(s.get('skillOverrides'), dict) else {} prima = dict(so) for k, v in ora.items(): c, n = k.split(':', 1) if c == 'claude': so[n] = 'on' if v == 'accesa' else 'user-invocable-only' for k in via: c, n = k.split(':', 1) if c == 'claude': if n in di_serie_claude: so[n] = di_serie_claude[n] else: so.pop(n, None) if so != prima: s['skillOverrides'] = so if not so: s.pop('skillOverrides', None) _scrivi_se_cambia(locale, json.dumps(s, indent=2, ensure_ascii=False) + '\n') for casa in _case_codex(): conf = os.path.join(casa, 'config.toml') with open(conf, encoding='utf-8', errors='replace') as h: testo = h.read() nuovo = testo def percorsi(n): 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'))] if radice: out.append(os.path.join(radice, '.agents', 'skills', n, 'SKILL.md')) return [x for x in out if os.path.isfile(x)] def blocco(t, percorso, acceso): chiave = json.dumps(percorso) schema = '(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(chiave) + '\\s*\\nenabled\\s*=\\s*(true|false)\\s*\\n?' riga = f"[[skills.config]]\npath = {chiave}\nenabled = {('true' if acceso else 'false')}\n" if acceso is None: return re.sub(schema, '', t) if re.search(schema, t): return re.sub(schema, riga.replace('\\', '\\\\'), t) return t.rstrip('\n') + '\n\n' + riga for k, v in ora.items(): c, n = k.split(':', 1) if c == 'codex': for pp in percorsi(n): nuovo = blocco(nuovo, pp, v == 'accesa') for k in via: c, n = k.split(':', 1) if c == 'codex': for pp in percorsi(n): di_serie = '/skills/.system/' in pp.replace(os.sep, '/') nuovo = blocco(nuovo, pp, False if n in spente_codex and di_serie else None) if nuovo != testo: with open(conf + '.nuovo', 'w', encoding='utf-8') as h: h.write(nuovo) os.replace(conf + '.nuovo', conf) return sorted(ora) _PORTO_FILE, _PORTO_PESO = (30, 512000) def _cartelle_di_skill(radice): cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') out = [os.path.join(cfg, 'skills'), os.path.expanduser('~/.agents/skills'), os.path.expanduser('~/.qwen/skills')] out += [os.path.join(c, 'skills') for c in _case_codex()] if radice: out += [os.path.join(radice, rel) for rel, _cli in _SKILL_PROGETTO] return {os.path.realpath(x) for x in out} def _file_da_portare(radice, cartella): if cartella.startswith('~/'): d = os.path.expanduser(cartella) elif os.path.isabs(cartella): d = cartella else: d = os.path.join(radice or '', cartella) vero = os.path.realpath(d) 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'))): return (None, F('porto_non_qui', cartella=cartella)) file, peso = ({}, 0) for base, cartelle, nomi in os.walk(vero): cartelle[:] = sorted((c for c in cartelle if not c.startswith('.') and (not os.path.islink(os.path.join(base, c))))) for n in sorted(nomi): p = os.path.join(base, n) if n.startswith('.') or os.path.islink(p): continue try: with open(p, 'rb') as h: crudo = h.read(_PORTO_PESO + 1) testo = crudo.decode('utf-8') except (OSError, UnicodeDecodeError): continue peso += len(crudo) if len(file) >= _PORTO_FILE or peso > _PORTO_PESO: return (None, F('porto_troppo', cartella=cartella, file=_PORTO_FILE, peso=_PORTO_PESO)) file[os.path.relpath(p, vero).replace(os.sep, '/')] = testo return (file, '') def _cartelle_di_pezzi(radice): cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') out = [os.path.join(cfg, 'commands'), os.path.join(cfg, 'agents'), os.path.expanduser('~/.qwen/commands'), os.path.expanduser('~/.qwen/agents')] if radice: out += [os.path.join(radice, rel) for rel, _cli in _COMANDI + _AGENTI] return [os.path.realpath(x) for x in out] def _pezzo_da_portare(radice, cartella): if cartella.startswith('~/'): p = os.path.expanduser(cartella) elif os.path.isabs(cartella): p = cartella else: p = os.path.join(radice or '', cartella) vero = os.path.realpath(p) dentro = any((vero.startswith(c + os.sep) for c in _cartelle_di_pezzi(radice))) if os.path.islink(p) or not dentro or (not os.path.isfile(vero)) or (not vero.endswith(('.md', '.toml'))): return (None, F('porto_non_qui', cartella=cartella)) try: with open(vero, 'rb') as h: crudo = h.read(_PEZZO_PESO + 1) testo = crudo.decode('utf-8') except (OSError, UnicodeDecodeError): return (None, F('porto_non_qui', cartella=cartella)) if len(crudo) > _PEZZO_PESO: return (None, F('porto_troppo', cartella=cartella, file=1, peso=_PEZZO_PESO)) return ({os.path.basename(vero): testo}, '') def _squadra(a, token, url, radice, impronta): pacchetto = os.path.join(radice or '', '.claude', 'squadra.py') if not radice or not os.path.isfile(pacchetto): return '' try: p = runpy.run_path(pacchetto) except Exception: return '' if 'squadra_scrivi' not in p: return '' chiave = hashlib.sha256(url.encode()).hexdigest()[:12] if impronta != (p['squadra_di'](chiave) or {}).get('impronta', ''): if impronta: try: pacco = json.loads(_get(a.url.rstrip('/') + '/api/skill/squadra', token, timeout=30) or b'{}') except (OSError, ValueError, urllib.error.URLError) as e: return F('squadra_muta', errore=e) else: pacco = {} if isinstance(pacco, dict): p['squadra_scrivi'](chiave, pacco) p['squadra_claude'](radice, chiave) if 'squadra_plugin_claude' in p: try: p['squadra_plugin_claude'](radice, chiave) except (OSError, subprocess.SubprocessError): pass sq = p['squadra_di'](chiave) if not sq: return '' c = sq['ruoli'].get('conto') or {} 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']) try: with open(os.path.join(sq['cartella'], '.plugin.json'), encoding='utf-8') as h: plugin_sq = [x for x in json.load(h) if isinstance(x, dict)] except (OSError, ValueError, TypeError): plugin_sq = [] if plugin_sq: fermi = sum((1 for x in plugin_sq if not x.get('accettato'))) detto += '\n' + F('squadra_plugin_qui', accettati=len(plugin_sq) - fermi, fermi=fermi) return detto def gesto_skill(a, url, sp, registro, mio): try: radice = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=5).stdout.strip() except (OSError, subprocess.SubprocessError): radice = '' try: token = open(os.path.expanduser(a.token_file)).read().strip() except OSError as e: print(F('registro_muto', url=a.url, errore=e), file=sys.stderr) return 2 base = a.url.rstrip('/') + '/api/skill/macchina' scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in sp.get('skill_scelte') or [] if isinstance(x, dict)} carte = raccogli_skill(radice, os.path.expanduser(a.versioni_qwen), scelte) try: 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'{}') except (OSError, ValueError, urllib.error.URLError) as e: print(F('registro_muto', url=a.url, errore=e), file=sys.stderr) return 2 nuove = r.get('scelte') if isinstance(r.get('scelte'), list) else [] 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 ''))} chiave = 'skill_applicate:' + (radice or '') sp[chiave] = applica_skill(radice, scelte, sp.get(chiave) or []) sp['skill_scelte'] = [{'cli': c, 'nome': n, 'stato': v} for (c, n), v in sorted(scelte.items())] _scrivi(registro, mio) print(F('skill_riferite', n=len(carte), scelte=len(scelte))) for x in r.get('porta') if isinstance(r.get('porta'), list) else []: cartella = str((x or {}).get('cartella') or '') if isinstance(x, dict) else '' if not cartella: continue file, errore = _pezzo_da_portare(radice, cartella) if x.get('tipo') in ('comando', 'agente') else _file_da_portare(radice, cartella) try: 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'{}') 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)) except (OSError, ValueError, urllib.error.URLError) as err: print(F('registro_muto', url=a.url, errore=err), file=sys.stderr) detto = _squadra(a, token, url, radice, str(r.get('squadra') or '')) if detto: print(detto) return 0 _PLUGIN_TETTO = 200 def _origine_plugin(fonte): if not isinstance(fonte, dict): return '' tipo = str(fonte.get('source') or fonte.get('source_type') or fonte.get('type') or '') if tipo == 'github' and re.fullmatch('[\\w.-]+/[\\w.-]+', str(fonte.get('repo') or '')): return 'github:' + str(fonte['repo']) valore = str(fonte.get('url') or fonte.get('path') or fonte.get('source') or '') if re.match('(?i)(https?|ssh|git)://', valore): try: u = urllib.parse.urlsplit(valore) except ValueError: return '' return urllib.parse.urlunsplit((u.scheme, u.netloc.rpartition('@')[2], u.path, '', ''))[:300] if re.fullmatch('[\\w.-]+@[\\w.-]+:[\\w./-]+', valore): return valore.partition('@')[2][:300] if valore.startswith(('/', '~')): return 'cartella:' + _cartella_da_leggere(os.path.expanduser(valore), '') return '' def _di_delminio(mercato, nome=''): return mercato == 'delminio' or mercato.startswith('delminio-squadra-') or (not mercato and nome == 'delminio') def _carta_plugin(cli, nome, mercato, *, versione='', acceso=None, livello='personale', dove='personale', origine='', cartella=''): 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)} def _plugin_claude(radice, progetto, carte): cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') acceso = {} impostazioni = [os.path.join(cfg, 'settings.json')] if radice: impostazioni += [os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')] for p in impostazioni: d = _leggi(p).get('enabledPlugins') for k, v in d.items() if isinstance(d, dict) else []: acceso[k] = v is True installati = _leggi(os.path.join(cfg, 'plugins', 'installed_plugins.json')).get('plugins') for pid, voci in installati.items() if isinstance(installati, dict) else []: nome, _, mercato = str(pid).partition('@') for v in voci if isinstance(voci, list) else []: if not isinstance(v, dict): continue if v.get('scope') == 'user': livello, dove = ('personale', 'personale') elif v.get('scope') in ('project', 'local') and radice and (v.get('projectPath') == radice): livello, dove = ('progetto', progetto) else: continue carte.append(_carta_plugin('claude', nome, mercato, versione=v.get('version'), acceso=acceso.get(pid, False), livello=livello, dove=dove)) mercati = _leggi(os.path.join(cfg, 'plugins', 'known_marketplaces.json')) for nome, m in mercati.items() if isinstance(mercati, dict) else []: if isinstance(m, dict): carte.append({'tipo': 'marketplace', 'cli': 'claude', 'nome': nome, 'origine': _origine_plugin(m.get('source')), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)}) def _plugin_codex(carte): casa_persona = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex') for casa in dict.fromkeys([casa_persona] + _case_codex()): try: with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h: testo = h.read() except OSError: continue cartella = _cartella_da_leggere(casa, '') for pid, campi in _toml_tabelle(testo, 'plugins').items(): nome, _, mercato = pid.partition('@') cache = os.path.join(casa, 'plugins', 'cache', mercato, nome) versioni = sorted(os.listdir(cache)) if mercato and os.path.isdir(cache) else [] carte.append(_carta_plugin('codex', nome, mercato, versione=versioni[-1] if versioni else '', acceso=campi.get('enabled') is not False, cartella=cartella)) for nome, campi in _toml_tabelle(testo, 'marketplaces').items(): 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)}) def _qwen_acceso(regole, qui): acceso = True for r in regole if isinstance(regole, list) else []: r = str(r) base = r.lstrip('!').rstrip('*').rstrip('/') if not base or qui == base or qui.startswith(base + '/'): acceso = not r.startswith('!') return acceso def _plugin_qwen(radice, carte): dati = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share') base = os.path.join(dati, 'delminio', 'qwen') case = [os.path.expanduser('~/.qwen')] + sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else []))) qui = radice or os.path.expanduser('~') for casa in case: cartella_ext = os.path.join(casa, 'extensions') if not os.path.isdir(cartella_ext): continue regole = _leggi(os.path.join(cartella_ext, 'extension-enablement.json')) for nome in sorted(os.listdir(cartella_ext)): d = os.path.join(cartella_ext, nome) if not os.path.isdir(d): continue inst = _leggi(os.path.join(d, '.qwen-extension-install.json')) sorgente = str(inst.get('source') or '') manifesto = _leggi(os.path.join(d, 'qwen-extension.json')) or (_leggi(os.path.join(sorgente, 'qwen-extension.json')) if inst.get('type') == 'link' else {}) nome_vero = str(manifesto.get('name') or inst.get('pluginName') or nome) origine = _origine_plugin({'path': sorgente} if inst.get('type') in ('link', 'local') else {'url': sorgente}) mercato = str((inst.get('marketplaceConfig') or {}).get('name') or '') if inst.get('pluginName') else '' 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, '')) carta['di_delminio'] = nome_vero == 'delminio' or '/delminio/plugin/' in sorgente or '/delminio/squadre/' in sorgente carte.append(carta) def _plugin_opencode(radice, progetto, carte): casa = os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'opencode') posti = [(casa, 'personale', 'personale')] + ([(radice, 'progetto', progetto)] if radice else []) for cartella, livello, dove in posti: sotto = os.path.join(cartella, 'plugins' if cartella == casa else os.path.join('.opencode', 'plugins')) for f in sorted(os.listdir(sotto)) if os.path.isdir(sotto) else []: nome, est = os.path.splitext(f) if est in ('.js', '.ts', '.mjs') and os.path.isfile(os.path.join(sotto, f)): carta = _carta_plugin('opencode', nome, '', acceso=True, livello=livello, dove=dove, origine='file', cartella=_cartella_da_leggere(sotto, radice)) carta['di_delminio'] = nome == 'delminio' carte.append(carta) for nome_conf in ('opencode.json', 'opencode.jsonc'): conf = _leggi(os.path.join(cartella, nome_conf)) for pacchetto in conf.get('plugin') if isinstance(conf.get('plugin'), list) else []: m = re.fullmatch('(@?[\\w.-]+(?:/[\\w.-]+)?)(?:@([\\w.^~<>=-]+))?', str(pacchetto)) if m: carte.append(_carta_plugin('opencode', m.group(1), '', versione=m.group(2) or '', acceso=True, livello=livello, dove=dove, origine='npm:' + m.group(1))) def raccogli_plugin(radice, progetto): carte = [] for leggi in (lambda: _plugin_claude(radice, progetto, carte), lambda: _plugin_codex(carte), lambda: _plugin_qwen(radice, carte), lambda: _plugin_opencode(radice, progetto, carte)): try: leggi() except (OSError, ValueError, TypeError, AttributeError): continue return carte[:_PLUGIN_TETTO] _GANCI_MOMENTI = (('apertura', 'apertura'), ('opening', 'apertura'), ('dove-siamo', 'dove-siamo'), ('status', 'dove-siamo')) def _ganci_git(radice, *argomenti): try: return subprocess.run(['git', '-C', radice, *argomenti], capture_output=True, text=True, timeout=5).stdout.strip() except (OSError, subprocess.SubprocessError): return '' def _ganci_accettate(radice): f = os.path.join(_ganci_git(radice, 'rev-parse', '--path-format=absolute', '--git-common-dir'), 'delminio-guardie-accettate') try: with open(f, encoding='utf-8') as h: return sorted({x for x in h.read().split() if re.fullmatch('[0-9a-f]{64}', x)})[:500] except OSError: return [] def _ganci_script(radice): codice = os.environ.get('DELMINIO_FIDATI_PY') or '' if not codice: return [] fidati = {} try: exec(codice, fidati) except Exception: return [] gia = fidati['accettati'](radice) voci = [(f, momento) for cartella, momento in _GANCI_MOMENTI for f in fidati['script_del_progetto'](radice, (cartella,))] voci += [(f, 'lascito') for f in fidati['lascito_del_progetto'](radice)] out = [] for f, momento in voci[:50]: altro = fidati['di_chi'](radice, f) 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 ''}) return out def raccogli_ganci(radice, progetto): if not radice: return {} return {'dove': progetto, 'accettate': _ganci_accettate(radice), 'script': _ganci_script(radice)} PROVA_CONTESTO_MIN = 32768 PROVA_CONTESTO_COMODO = 65536 _PROVA_STRUMENTO = {'nome': 'conta_lettere', 'descrizione': F('prova_strumento'), 'parametri': {'type': 'object', 'properties': {'parola': {'type': 'string'}}, 'required': ['parola']}} _PROVA_CHIEDI = F('prova_chiedi') _PROVA_PREFISSO = ' '.join((F('prova_regola', i=i) for i in range(330))) def _prova_post(url, intestazioni, corpo, timeout=90): req = urllib.request.Request(url, data=json.dumps(corpo).encode(), method='POST', headers={'Content-Type': 'application/json', **intestazioni}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read()) def _prova_cache_letta(formato, risposta): u = risposta.get('usage') or {} if formato == 'anthropic': letti = u.get('cache_read_input_tokens') totale = (u.get('input_tokens') or 0) + (letti or 0) + (u.get('cache_creation_input_tokens') or 0) return (letti, totale) totale = u.get('prompt_tokens') or 0 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')): if isinstance(chi, int): return (chi, totale) return (None, totale) def _prova_contesto(riga, formato, base, intestazioni, modello): f = riga.get('fornitore') or {} if f.get('contesto'): return int(f['contesto']) elenco = 'https://openrouter.ai/api/v1/models' if f.get('tipo') == 'openrouter' else base.rstrip('/') + '/models' if formato == 'openai' else '' if not elenco: return None h = {} if f.get('tipo') == 'openrouter' else intestazioni try: with urllib.request.urlopen(urllib.request.Request(elenco, headers=h), timeout=30) as r: dati = json.loads(r.read()) except (OSError, ValueError): return None for m in dati.get('data') or dati.get('models') or []: if m.get('id') == modello or m.get('name') == modello: for k in ('context_length', 'context_window', 'max_model_len', 'max_context_length'): if isinstance(m.get(k), int): return m[k] meta = m.get('meta') or {} if isinstance(meta.get('n_ctx_train'), int): return meta['n_ctx_train'] return None def prova_qwen(riga, dal_motore=''): imp = impostazioni_qwen(riga) formato = imp['security']['auth']['selectedType'] p = imp['modelProviders'][formato][0] modello, base, variabile = (p['id'], p.get('baseUrl') or '', p['envKey']) tipo = (riga.get('fornitore') or {}).get('tipo') chiave = dal_motore or os.environ.get(variabile) or ('nessuna' if tipo == 'casa' else '') if not chiave: raise RuntimeError(F('prova_senza_chiave', variabile=variabile)) marca = formato == 'anthropic' or 'dashscope' in base if formato == 'anthropic': url, intest = (base.rstrip('/') + '/v1/messages', {'x-api-key': chiave, 'anthropic-version': '2023-06-01'}) def corpo(sistema, testo, strumenti=False): s = {'type': 'text', 'text': sistema, **({'cache_control': {'type': 'ephemeral'}} if marca else {})} c = {'model': modello, 'max_tokens': 200, 'system': [s], 'messages': [{'role': 'user', 'content': testo}]} if strumenti: c['tools'] = [{'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'input_schema': _PROVA_STRUMENTO['parametri']}] return c def chiamato(r): 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 [])) else: url, intest = (base.rstrip('/') + '/chat/completions', {'Authorization': f'Bearer {chiave}'}) def corpo(sistema, testo, strumenti=False): s = [{'type': 'text', 'text': sistema, 'cache_control': {'type': 'ephemeral'}}] if marca else sistema c = {'model': modello, 'max_tokens': 200, 'messages': [{'role': 'system', 'content': s}, {'role': 'user', 'content': testo}]} if strumenti: c['tools'] = [{'type': 'function', 'function': {'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'parameters': _PROVA_STRUMENTO['parametri']}}] return c def chiamato(r): for c in ((r.get('choices') or [{}])[0].get('message') or {}).get('tool_calls') or []: fn = c.get('function') or {} if fn.get('name') == _PROVA_STRUMENTO['nome'] and 'delminio' in str(fn.get('arguments') or '').lower(): return True return False note = [] try: tool = chiamato(_prova_post(url, intest, corpo(F('prova_sistema'), _PROVA_CHIEDI, True))) except urllib.error.HTTPError as e: testo = e.read()[:200].decode(errors='replace') if e.code in (401, 403): raise RuntimeError(F('prova_chiave_rifiutata', codice=e.code, testo=testo)) from None tool = False note.append(F('prova_strumento_errore', codice=e.code)) letti = totale = None for attesa in (0, 3, 8): time.sleep(attesa) r = _prova_post(url, intest, corpo(_PROVA_PREFISSO, F('prova_ok'))) letti, totale = _prova_cache_letta(formato, r) if attesa and (letti is None or letti > 0): break contesto = _prova_contesto(riga, formato, base, intest, modello) if not tool: note.append(F('prova_senza_strumento')) if contesto is not None and contesto < PROVA_CONTESTO_COMODO: note.append(F('prova_contesto_stretto', contesto=contesto)) if letti is None: note.append(F('prova_cache_muta')) esito = 'non_va' if not tool or (contesto is not None and contesto < PROVA_CONTESTO_MIN) else 'va' if letti else 'senza_cache' return {'esito': esito, 'tool': tool, 'cache': {'letti': letti, 'totale': totale}, 'contesto': contesto, 'nota': '; '.join(note)} def comando_prova(a, righe, dati, base, token): riga = next((r for r in righe if a.nomi and r.get('nome') == a.nomi[0]), None) if riga is None or riga.get('cli') != 'qwen': print(F('uso_prova'), file=sys.stderr) return 2 riga = {**riga, '_fornitori': dati.get('fornitori_qwen') or {}} locale = (riga.get('fornitore') or {}).get('tipo') == 'casa' 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'))) dal_motore = '' if (scelta := (riga.get('fornitore') or {}).get('chiave')): try: dal_motore = _get(base + '/' + urllib.parse.quote(riga['nome']) + '/chiave', token).decode().strip() except urllib.error.HTTPError as e: print(F('prova_chiave_negata', scelta=scelta, errore=e.read()[:400].decode(errors='replace')), file=sys.stderr) return 1 except (OSError, urllib.error.URLError) as e: print(F('prova_chiave_negata', scelta=scelta, errore=e), file=sys.stderr) return 1 try: v = prova_qwen(riga, dal_motore) except (RuntimeError, OSError, ValueError) as e: print(F('prova_non_fatta', errore=e), file=sys.stderr) return 1 c = v['cache'] print(F('prova_riga_strumenti', valore=F('prova_si') if v['tool'] else F('prova_no'))) 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']))) print(F('prova_riga_contesto', valore=v['contesto'] or F('prova_non_lo_dice'))) 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 '')) try: _get(base + '/' + urllib.parse.quote(riga['nome']) + '/prova', token, metodo='POST', corpo=v) except (OSError, urllib.error.URLError) as e: print(F('verdetto_perso', errore=e), file=sys.stderr) return 1 return 0 if v['esito'] != 'non_va' else 1 def comando_rinomina(a, righe, base, token): if len(a.nomi) != 2: print(F('uso_rinomina'), file=sys.stderr) return 2 vecchio, nuovo = a.nomi riga = next((r for r in righe if r['nome'] == vecchio), None) if riga is None: print(F('rinomina_assente', nome=vecchio), file=sys.stderr) return 1 try: _get(f'{base}/{urllib.parse.quote(vecchio)}/rinomina', token, metodo='POST', corpo={'nuovo': nuovo}) except urllib.error.HTTPError as e: print(F('rinomina_rifiutata', errore=e.read().decode('utf-8', 'replace')[:300]), file=sys.stderr) return 1 print(F('rinominato', vecchio=vecchio, nuovo=nuovo)) return 0 def comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro): for r in righe: p = os.path.join(bin_dir, r['nome']) try: voluta = versione_voluta(r, canali) except Exception as e: voluta = f'? ({e})' ora = _del_file(p) 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])) 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) 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)) if sp.get('rifiutato'): print(F('stato_rifiutato')) if not righe: print(F('registro_vuoto')) r = riferisci(base, token, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli')) richiesta(base, token, r, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'), mio=mio, file_mio=registro) return 0 def comando_lascia(a, url, padroni, impronte, mio, registro): tolti = 0 for p in [x for x, chi in padroni.items() if url in chi]: if lascia_il_nome(p, url, padroni, impronte) == 'tolto': tolti += 1 mio['spazi'].pop(url, None) _scrivi(registro, mio) comando = os.path.join(os.path.expanduser(a.bin), 'delminio') if not mio['spazi'] and os.path.isfile(comando): with open(comando, encoding='utf-8', errors='replace') as h: if '# delminio-comando\n' in h.read(): os.remove(comando) print(F('lasciati', n=tolti)) return 0 def scrivi_il_primo(a, dati, righe, bin_dir, impronte): cli_voluta = a.vuoi or 'claude' catalogo = (dati.get('modelli') or {}).get(cli_voluta) or [] ordine = [m.get('id') for m in catalogo] consigliati = {m.get('id') for m in catalogo if m.get('consigliato')} 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))) 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]), '') if not candidati: print(F('nessun_agente_di', cli=CLI_NOMI.get(cli_voluta, cli_voluta))) with open(a.primo, 'w', encoding='utf-8') as f: f.write(primo) def main(): if sys.argv[1:2] == ['posta-ruolo']: return posta_ruolo(sys.argv[2:]) if sys.argv[1:2] == ['casa']: return casa(sys.argv[2:]) if sys.argv[1:2] == ['mie-qwen']: return unisci_mie_qwen(sys.argv[2:]) if sys.argv[1:2] == ['mie-codex']: return unisci_mie_codex(sys.argv[2:]) if sys.argv[1:2] == ['pulizia']: return pulizia(sys.argv[2:]) if sys.argv[1:2] == ['errori-registra']: return errori_registra(sys.argv[2:]) if sys.argv[1:2] == ['errori']: return errori(sys.argv[2:]) if sys.argv[1:2] == ['pulizia-codex']: return pulizia_codex(sys.argv[2:]) if sys.argv[1:2] == ['pulizia-opencode']: return pulizia_opencode(sys.argv[2:]) if sys.argv[1:2] == ['installa-agente']: return installa_agente(sys.argv[2:]) if sys.argv[1:2] == ['modello-gratuito']: return modello_gratuito(sys.argv[2:]) if sys.argv[1:2] == ['accetta']: return accetta(os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')) ap = argparse.ArgumentParser(description=F('aiuto_descrizione')) ap.add_argument('comando', nargs='?', default='allinea', choices=['allinea', 'stato', 'no', 'rinomina', 'lascia', 'spazio', 'prova', 'skill']) ap.add_argument('nomi', nargs='*', help=F('aiuto_nomi')) ap.add_argument('--url') ap.add_argument('--token-file') ap.add_argument('--da', help=F('aiuto_da')) ap.add_argument('--modo', choices=['kit', 'casa'], default='kit') ap.add_argument('--al-lancio', action='store_true', help=F('aiuto_al_lancio')) ap.add_argument('--converti', action='store_true', help=F('aiuto_converti')) ap.add_argument('--vuoi', choices=list(CLI_NOMI), help=F('aiuto_vuoi')) ap.add_argument('--primo', help=F('aiuto_primo')) ap.add_argument('--bin', default=os.environ.get('DELMINIO_BIN') or '~/.local/bin') ap.add_argument('--versioni', default=os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions') ap.add_argument('--versioni-codex', default=os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions') ap.add_argument('--versioni-qwen', default=os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions') ap.add_argument('--versioni-opencode', default=os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions') ap.add_argument('--registro', default=os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json') a = ap.parse_args() if a.da: for riga in open(a.da, encoding='utf-8'): k, _, v = riga.strip().partition('=') if k in ('URL', 'FILE_TOKEN') and v: setattr(a, 'url' if k == 'URL' else 'token_file', (shlex.split(v) or [''])[0]) if not a.url or not a.token_file: ap.error(F('servono_url_token')) bin_dir, versioni, registro = (os.path.expanduser(x) for x in (a.bin, a.versioni, a.registro)) _DIR_COMANDI[0] = cartella_dei_comandi(registro) prova = os.environ.get('DELMINIO_CLI_PROVA', '') mio = _leggi(registro) if a.vuoi and a.comando == 'allinea': mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {a.vuoi}) _scrivi(registro, mio) letto = _del_file(registro) impronte = mio.setdefault('eseguibili', {}) _ALIASI.update(mio.get('alias') or {}) url = spazio_di(a.url, _token_di(a.token_file)) if a.comando == 'spazio': if url not in mio.get('spazi', {}) and mio.get('spazi'): vero = _alias(mio, url, _istanza_di(a.url, _token_di(a.token_file))) if vero != url: _scrivi(registro, mio) url = vero print(url) return 0 sp = _spazio(mio, url) if a.comando == 'skill': return gesto_skill(a, url, sp, registro, mio) if a.comando == 'allinea' and a.modo == 'kit': ricorda_il_progetto(url) padroni = mio.setdefault('padroni', {}) if a.comando == 'no': sp['rifiutato'] = True _scrivi(registro, mio) print(F('rifiutati')) return 0 if a.comando == 'lascia': return comando_lascia(a, url, padroni, impronte, mio, registro) base = a.url.rstrip('/') + '/api/eseguibili' try: token = open(os.path.expanduser(a.token_file)).read().strip() dati = json.loads(_get(base, token)) righe = dati['eseguibili'] except (OSError, ValueError, KeyError, urllib.error.URLError) as e: print(F('registro_muto', url=a.url, errore=e), file=sys.stderr) return 2 fuori = [str(r.get('nome')) for r in righe if not _NOME_OK.fullmatch(str(r.get('nome') or ''))] if fuori: print(F('nomi_fuori_forma', nomi=', '.join(map(repr, fuori))), file=sys.stderr) righe = [r for r in righe if _NOME_OK.fullmatch(str(r.get('nome') or ''))] istanza = dati.get('istanza') or '' if (vero := _alias(mio, url, istanza)) != url: url, sp = (vero, _spazio(mio, vero)) if istanza: sp['istanza'] = istanza al_lancio = a.comando == 'allinea' and a.al_lancio if al_lancio and sp.get('registro') == dati.get('impronta'): return 3 if os.environ.get('DELMINIO_AL_LANCIO_ATTESO') else 0 if al_lancio and (not os.environ.get('DELMINIO_AL_LANCIO_ATTESO')): print(F('al_lancio'), file=sys.stderr) if a.comando == 'prova': return comando_prova(a, righe, dati, base, token) if a.comando == 'rinomina': return comando_rinomina(a, righe, base, token) canali, esito = ({}, 0) if a.comando == 'stato': return comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro) if fcntl is not None: try: os.makedirs(os.path.dirname(registro) or '.', exist_ok=True) lucchetto = open(registro + '.lock', 'w') fcntl.flock(lucchetto, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: if not al_lancio or os.environ.get('DELMINIO_AL_LANCIO_ATTESO') or 'lucchetto' not in locals(): print(F('allinea_in_corso')) return 0 print(F('al_lancio_attesa'), file=sys.stderr) fcntl.flock(lucchetto, fcntl.LOCK_EX) lucchetto.close() os.environ['DELMINIO_AL_LANCIO_ATTESO'] = '1' sys.stderr.flush() os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:]) else: if _del_file(registro) != letto and (not os.environ.get('DELMINIO_RILETTO')): lucchetto.close() os.environ['DELMINIO_RILETTO'] = '1' sys.stdout.flush() sys.stderr.flush() os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:]) os.makedirs(bin_dir, exist_ok=True) nomi = set() senza_cli = set() detto = [0.0] def avanza(percento, passo, subito=False): if not subito and time.time() - detto[0] < 2: return detto[0] = time.time() try: _get(f'{base}/lavoro', token, metodo='POST', corpo={'host': socket.gethostname(), 'percento': int(percento), 'passo': passo[:120]}, timeout=5) except (OSError, ValueError, urllib.error.URLError): pass nomi_cli = dati.get('cli') or {} quante = max(1, len(righe)) prima_volta = 'accettati' not in mio accettati, fermi = (set(mio.get('accettati') or []), []) for i, r in enumerate(righe): p = os.path.join(bin_dir, r['nome']) nomi.add(p) quota, nome_cli = (100.0 * i / quante, nomi_cli.get(r.get('cli') or 'claude', r.get('cli') or 'claude')) 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)): senza_cli.add(r['nome']) print(F('senza_cli_qui', nome=r['nome'], cli=r.get('cli') or 'claude')) continue if da_accettare(r, accettati): if prima_volta and any((impronte.get(x) for x in (p, comando_dello_spazio(url, r['nome'])))): accettati.add(impronta_libera(r)) else: fermi.append({'nome': r['nome'], **parte_libera(r)}) print(F('riga_da_accettare', nome=r['nome'])) continue try: voluta = versione_voluta(r, canali) avanza(quota, F('passo_controllo', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True) 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 '')) 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) if personaggio(r) and r.get('cli') in ('claude', 'qwen'): assicura_canale(a.url, token, r['porta']) if r.get('cli') == 'claude': assicura_rito() except Exception as e: print(f"❌ {r['nome']}: {e}") esito = 1 continue modello = next((m for m in (dati.get('modelli') or {}).get(r.get('cli') or 'claude', []) if m['id'] == r.get('modello')), {}) promemoria = ((dati.get('promemoria') or {}).get('ambiente') or {}).get(r.get('cli') or 'claude') or {} promemoria = {k: v for k, v in promemoria.items() if k in PROMEMORIA_AMMESSI} 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 {}} testo = wrapper(da_lanciare, cli, a.modo, a.url, os.path.expanduser(a.token_file)) ora = _del_file(p) if ora is not None and p not in impronte: print(F('non_di_delminio', percorso=p)) esito = 1 continue if ora is not None and impronte.get(p) != ora: print(F('toccato_resta', percorso=p)) continue if a.modo == 'kit' and (not a.converti) and (ora != _impronta(testo)) and _di_casa(p): testo = wrapper(da_lanciare, cli, 'casa', a.url, os.path.expanduser(a.token_file)) chi = padroni.get(p) or [] altri = [u for u in chi if u != url] if ora is not None and altri and (not e_smistatore(p)) and (ora == _impronta(testo)): if url not in chi: chi.append(url) sp.setdefault('cli', {})[p] = voluta continue if ora is not None and (altri or e_smistatore(p)): q = comando_dello_spazio(url, r['nome']) gia = _del_file(q) if gia is not None and impronte.get(q) not in (None, gia): print(F('toccato_resta', percorso=q)) continue vecchio = None if gia is not None: with open(q, encoding='utf-8') as f: vecchio = f.read() prima = (sp.get('cli') or {}).get(p) sp.setdefault('cli', {})[p] = voluta if url in chi and gia == _impronta(testo) and e_smistatore(p): continue if dividi(p, url, testo, padroni, impronte): print(F('smistato', nome=r['nome'], spazi=', '.join((come_si_chiama(u) for u in padroni[p])))) cambiate = _nel_diario(registro, q, prima, voluta, vecchio, testo) if gia is None: print(F('scritto', percorso=q, versione=voluta)) elif gia != _impronta(testo): print(F('rinfrescato', percorso=q, versione=voluta, righe=cambiate) if prima == voluta else F('aggiornato', percorso=q, prima=prima or '?', versione=voluta)) continue padroni[p] = [url] + altri prima = (sp.get('cli') or {}).get(p) sp.setdefault('cli', {})[p] = voluta if ora == _impronta(testo): continue vecchio = None if ora is not None: try: with open(p, encoding='utf-8') as f: vecchio = f.read() except (OSError, UnicodeDecodeError): pass with open(p + '.nuovo', 'w', encoding='utf-8') as f: f.write(testo) os.chmod(p + '.nuovo', 493) os.replace(p + '.nuovo', p) impronte[p] = _impronta(testo) cambiate = _nel_diario(registro, p, prima, voluta, vecchio, testo) if ora is None: print(F('scritto', percorso=p, versione=voluta)) elif prima == voluta: print(F('rinfrescato', percorso=p, versione=voluta, righe=cambiate)) else: print(F('aggiornato', percorso=p, prima=prima or '?', versione=voluta)) avanza(100.0 * (i + 1) / quante, F('passo_scritto', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True) for p in [x for x in impronte if x not in nomi and os.path.dirname(x) == bin_dir]: chi = padroni.get(p) or [] if url not in chi: continue sp.get('cli', {}).pop(p, None) com_e = lascia_il_nome(p, url, padroni, impronte) if com_e == 'tolto': print(F('tolto', percorso=p)) elif com_e in ('altri', 'tornato'): print(F('lasciato_ad_altri', percorso=p, spazi=', '.join(padroni.get(p) or []))) if righe: sp['rifiutato'] = False mio['accettati'], sp['fermi'] = (sorted(accettati), fermi) sp['registro'], sp['quando'] = (dati.get('impronta', ''), int(time.time())) sp['skill_scelte'] = dati.get('skill_scelte') or [] _scrivi(registro, mio) if esito == 0 and righe and (not prova): pota(bin_dir, [versioni] + [os.path.expanduser(c) for c in (a.versioni_codex, a.versioni_qwen, a.versioni_opencode)], nudo(bin_dir, versioni)) r = riferisci(base, token, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), senza_cli=senza_cli) 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')): os.environ['DELMINIO_RIALLINEATO'] = '1' sys.stdout.flush() os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:]) cartelle = [os.path.realpath(os.path.expanduser(c)) for c in os.environ.get('PATH', '').split(os.pathsep) if c] if righe and os.path.realpath(bin_dir) not in cartelle: print(F('fuori_dal_path', cartella=bin_dir)) if a.primo: scrivi_il_primo(a, dati, righe, bin_dir, impronte) return 3 if al_lancio and esito == 0 else esito if __name__ == '__main__': sys.exit(main())