#!/usr/bin/env bash # © 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. set -euo pipefail URL="${DELMINIO_URL:-__DELMINIO_URL__}" URL="${URL%/}" muori() { printf '❌ %s\n' "$*" >&2; exit 1; } _no_del_motore() { local c=${1##*$'\n'} e case "$c" in 200) return 0 ;; ''|000) [ -n "${2:-}" ] || return 0 e=$(_f "$M_non_risponde" url "$URL"); muori "$(_f "$M_rifiutato" motivo "$e")" ;; *) e=$(printf '%s' "${1%$'\n'*}" | campo error); muori "$(_f "$M_rifiutato" motivo "HTTP $c${e:+: $e}")" ;; esac } : '⟦frasi: aggancia⟧' M_agente_opencode_domanda=' OpenCode works with a provider'"'"'s models. Do you have its key? [c] I'"'"'ll add it now — or [g] I'"'"'ll try OpenCode'"'"'s free models, no key: ' M_agente_opencode_gratuito=' The free model answering right now is {modello}: fine for trying; to work for real you need a provider'"'"'s key.' M_agente_opencode_nessuno='no free OpenCode model answers right now: run this command again and choose a provider'"'"'s key' M_agente_opencode_chiave_no='the key was not added: run this command again, or choose the free models' M_agente_opencode_senza_terminale=' OpenCode is installed. To start it needs a terminal: run this command again from there, and choose the key or the free models.' M_agente_non_installato='{cli} did not install (the reason is in the lines above): run this command again, and if it stops again show those lines to the person who gave you Delminio' M_agente_quale='“--agente” wants claude, codex, qwen or opencode and the version (you wrote “{cli} {versione}”)' M_agente_frase='Read {url}/aggancia.en.md with curl -fsSL and follow that text word for word.' M_agente_entra_account='the first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes.' M_agente_entra_qwen='the first time it asks which model to connect to: a Qwen account, or a provider with its key (pick it from the list and paste the key). Then, if it asks, say you trust this folder.' M_agente_entra_opencode='with the key or the free model you chose.' M_agente_parte=' Done: {cli} is on this computer. It starts now: {entra} We already gave it the sentence: it reads Delminio'"'"'s guide and takes you through every step — git, the project, the memory copy, the connection. What you already know how to do, tell it and it skips it. If it closes halfway, run the same command again: it downloads nothing new, and reopens it with the sentence. ' M_manca='“{c}” is missing: install it and run this command again (on Ubuntu and Debian: sudo apt install {c})' M_non_parte='“{c}” is there ({dove}) but does not run: {perche}. Fix it and run this command again.' M_mac_strumenti='On this Mac git and python3 are Apple'"'"'s, and they only run with Apple'"'"'s command line tools (about 1 GB, one click). I asked the Mac to install them: in Apple'"'"'s window press “Install”, wait for it to finish and run this command again. If the window did not open, run: xcode-select --install' M_argomento_ignoto='I don'"'"'t know “{arg}”: the arguments are --installa claude, codex or qwen, and --agente claude, codex, qwen or opencode with the version' M_installa_quale='“--installa” wants claude, codex or qwen (you wrote “{cli}”)' M_chi_sei_nome='git does not know who you are yet. The name that will sign your work (for example Mary Smith): ' M_chi_sei_mail='Your email: ' M_installo_cli=' Installing {cli} on this machine, at the version chosen in Delminio: a few minutes the first time.' M_installa_non_riuscita='the computer is connected, but {cli} was not installed (the reason is in the lines above): run this command again, and if it stops again show those lines to your administrator' M_parto_codex=' With Codex, after the folder: type /hooks and choose “Trust all”, just once. Without it Codex starts but does not hear Delminio. ' M_parto_qwen=' With Qwen Code the model and provider are those of the agent in the Agents view, and it reads the provider key from your environment. ' M_fuori_dal_clone='run it inside the clone of the repository you want to connect' M_progetto_nome='There is no git project here ({dove}). I'"'"'ll create a new one, in a new folder inside this one, with a git on this computer only. What should I call it? [progetto] ' M_progetto_nome_no='“{nome}” is not a good folder name: use letters without accents, digits, “-” and “_”, and do not start with a dot' M_progetto_esiste='{cartella} already exists and I won'"'"'t touch it: run again choosing another name, or go inside it and run again if it already is your project' M_progetto_creato=' The project is in the folder {cartella}, with a git on this computer only. When you want it on GitHub or another git host too, the agent explains how.' M_progetto_primo_commit='The project begins' M_parto=' Done. {nome} is starting. The first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes. When it is ready type {apertura}: from there the agent guides you. Next time open the terminal in {cartella} and type {dopo}. ' M_rito_apertura=/opening M_rito_apertura_codex=opening M_comando_occupato='{file} already exists and isn'"'"'t Delminio'"'"'s: I leave it alone. Without the “delminio” command, the commands are written in full, from the project folder: bash .claude/delminio.sh …' M_comando_fuori='delminio: there is no project connected to Delminio here. Go into the project folder, or one of its subfolders, and try again.' M_chi_sei='git doesn'"'"'t know who you are: git config --global user.name "Name" && git config --global user.email you@example.com' M_senza_origin='this repository has no “origin” remote: handoffs and merges stay on this machine, and anyone working from another one doesn'"'"'t see them' M_non_pusha='you can'"'"'t push to {origine} (git: {errore}): handoffs and merges will stay on this machine until you fix the credentials' M_codice_apri=' Open this address and press Approve:' M_codice_oppure=' (or: Delminio → Access, enter the code {codice} and press Approve)' M_codice_vale=' Valid for 10 minutes. This machine introduces itself as “{macchina}”. Waiting for approval…' M_approvato=' ✅ approved' M_scaduto=' ❌ the code has expired: run the command again' M_senza_terminale='no terminal to ask for the token: pass it in DELMINIO_TOKEN' M_domanda_token='The Delminio token (app → Access → Connect a repository): ' M_nessun_token='no token' M_non_risponde='Delminio is not responding at {url}' M_token_rifiutato='Delminio at {url} rejects this token (HTTP {codice})' M_rifiutato='not connected: {motivo}' M_tiene_gia='⚠️ Other repositories are already connected to this Delminio space: {altri}. A space holds a single project: several repositories are fine if they belong to the same work, with the same team. A different project goes in another space.' M_stessa_storia=' Is {repo} part of the same project? [y/N] ' M_altra_storia='not connected: if it'"'"'s another project, create another space (in the app, “Spaces”) and connect it there; if it'"'"'s the same one, run the command again and answer yes' M_app_codex_domanda=' The Codex app is on this computer: shall I add Delminio to it too? I only add the Delminio plugin and the permission for its two tools to ~/.codex/config.toml. [y/N] ' M_clone_fermo='the memory clone in {cartella} isn'"'"'t updating: it'"'"'s retried at every opening' M_clone_https=' memories: ssh to {remoto} doesn'"'"'t get through from here, cloned over https ({https})' M_clonate=' memories: cloned from {remoto} into {cartella} — the CLI finds the index there' M_memorie_vuote='the memory repository ({remoto}) is still empty: Delminio puts the base there as soon as its push goes through (Settings → “Memories on git”: the deploy key, with write access). The clone in {cartella} updates itself; while it'"'"'s empty the agent starts without the index, and is told so' M_clone_negato='the memory repository ({remoto}) can'"'"'t be read from this computer with your git credentials: that'"'"'s fine, the agent gets the memory index from Delminio when it starts. If you also want the local copy, ask the person who owns the repository for read access and run the connection again' M_codex_indice=' Codex and Qwen Code receive the memory index in Delminio'"'"'s opening: they need neither a local git clone nor an initial call to list.' M_senza_embedder='Delminio has no embedder: until the admin configures it (Settings → Embedder) memories are searched by words, without semantic search' M_embedder_muto='the embedder configured in Delminio is not responding ({risposta}): until it'"'"'s back, search is by words' M_note_sue='📦 Your CLI keeps its notes in {cartella} (says {fonte}). From now on Delminio would keep them and that folder wouldn'"'"'t be read any more. First I make a backup outside the repo, the agent proposes the notes to you as memories, and with “delminio disconnect” everything goes back to how it was.' M_va_bene=' OK? [y/N] ' M_memoria_sua_resta='not connected: your memory stays where it is. If it'"'"'s OK, run it again and answer yes (or DELMINIO_MEMORIA_SUA=si)' M_prima_non_salva='I can'"'"'t back up what was there before: I haven'"'"'t touched anything' M_prima_copia_diversa='the copy of {file} doesn'"'"'t match the original: I'"'"'m stopping before touching anything' M_mcp_fallito='claude mcp add failed' M_mcp_senza_claude='Claude Code is not in this shell'"'"'s PATH: the Delminio tool is not registered, and a Claude started here would have no memory. With Claude Code installed (and `claude` in the PATH), run this connection again: it only redoes what is missing.' M_senza_client='Delminio doesn'"'"'t provide the client ({indirizzo})' M_comando_tuo='{file} is a /{c} of yours, and it wins over Delminio'"'"'s in every project: here /{c} won'"'"'t be Delminio'"'"'s. If you want that one, rename yours (for example to /{c}-mine)' M_mcp_col_nome_nostro='{file} has an MCP server of its own called “memoria”, like Delminio'"'"'s: in {cli} it takes its place, and the agent is left without memory. Give it another name.' M_json_non_valido='{file} isn'"'"'t valid JSON: fix it and run again' M_codex_sotto_git='.codex/hooks.json is tracked by git: Codex here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again' M_qwen_sotto_git='.qwen/settings.json is tracked by git: Qwen Code here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again' M_senza_client_cantiere='Delminio doesn'"'"'t provide the Backlog client ({indirizzo})' M_senza_client_eseguibili='Delminio doesn'"'"'t provide the agents client ({indirizzo})' M_senza_client_cassaforte='Delminio doesn'"'"'t provide the vault client ({indirizzo})' M_apertura_muta='the opening hook gets no answer from Delminio: look at delminio apertura' M_nello_spazio=' in the space “{spazio}”' M_collegato='✅ {repo} is connected to Delminio ({url}){dove} as {chi}.' M_sempre_nello_spazio=' An agent opened in this folder always works{dove}: for another space, use another clone connected from there.' M_prima_al_sicuro='📦 What was there before is safe in {cartella}, outside the repo (the LEGGIMI.md in there says what). The agent goes through it with you at the first session. To go back to how it was: delminio disconnect' M_apri_eseguibile=' Open the agent in here with your Delminio command, and type /opening.' M_scrivi_eseguibile=' The agent starts best from Delminio'"'"'s command, with the rules at the top: delminio agents writes it on this machine (the name in the Agents view); then /opening.' M_path_nuovo=' ℹ️ The “delminio” command is in {cartella}, which isn'"'"'t in this terminal'"'"'s PATH: until it is, write it in full, {comando}. On Linux a new terminal usually finds it by name.' M_con_codex=' With Codex: if it'"'"'s already open, close it and start it again from Delminio'"'"'s command (the one “eseguibili” writes): a Codex opened before the connection doesn'"'"'t see Delminio. At the first start Codex asks whether to trust the folder and the hooks (/hooks → Trust all): say yes, then type opening, without the slash.' M_senza_cli=' This machine doesn'"'"'t have an agent CLI yet (claude, codex, qwen or opencode). To install one, run the connection again with the one you want: the right command is in Delminio → Agents → “Connect another computer” → “I don'"'"'t have an agent”.' M_con_qwen=' With Qwen Code: start it from Delminio'"'"'s command (the one “delminio agents” writes), which gives it the model chosen in the Agents view and its key from the environment; a Qwen opened before the connection doesn'"'"'t see Delminio. Then type /opening.' M_con_opencode=' With OpenCode: open it in this folder (restart one that is already open): memory, /opening and /closing come with Delminio'"'"'s plugin in .opencode/plugins. Then type /opening.' M_qwen_ripiego='Delminio'"'"'s extension did not link in Qwen Code ({agente}): the hooks and /opening and /closing stay in the project, as before the package.' M_solo_claude=' With plain claude, or from the desktop app, it starts with the standard prompt: /opening brings it the rules.' M_gancio_tuo='⚠️ {file} is already there and isn'"'"'t Delminio'"'"'s: add this line to it yourself {riga}' M_gancio_globale='⚠️ git hooks here come from {dir}, which isn'"'"'t this repository'"'"'s (global core.hooksPath): it applies to all your repositories, and Delminio doesn'"'"'t write there. Add to {file} yourself {riga}' M_prima_questo_progetto='this project' M_prima_claude_md='the project'"'"'s instructions for Claude' M_prima_claude_local='your personal instructions for this project' M_prima_settings='the CLI'"'"'s local settings for this project, as they were' M_prima_hook_codex='Codex'"'"'s hooks for this project, as they were' M_prima_qwen='Qwen Code'"'"'s settings for this project, as they were' M_prima_apertura='your /opening command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one' M_prima_chiusura='your /closing command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one' M_prima_mcp='the “{nome}” MCP server you had before (it contains its token)' M_prima_note='- `memoria/` — the {n} notes the CLI had written for itself, from `{cartella}`' M_prima_configurazioni='- your CLI configurations (hooks, commands, agents, MCP servers, plugins): **not touched**, they stay where they are; the settings files are also in this backup, `fatti.json` has the list, and the agent tells you what works alongside Delminio and what doesn'"'"'t' M_prima_altri='- the instructions you wrote for other tools and the memories other tools keep ({elenco}): **copied here and not touched**, the originals stay where they are; `fatti.json` says what they are, and the agent proposes them to you along with the notes' M_prima_chiesti='- what you asked to back up before the connection ({elenco})' M_prima_tutti='- {n} files in all, each with its fingerprint in `fatti.json`: that'"'"'s how the copy is checked against the original' M_prima_non_copiato='- `{file}`: not copied ({perche})' M_prima_perche_credenziali='it holds credentials: it stays only where it is, and the connection doesn'"'"'t touch it' M_prima_perche_grande='too big for the backup: it stays where it is, and the connection doesn'"'"'t touch it' M_prima_perche_fuori='it'"'"'s outside the repo and your home folder' M_prima_perche_assente='it isn'"'"'t there' M_prima_niente_da_ripassare='nothing of yours to go through: the backup is there anyway' M_prima_leggimi_titolo='What was there before Delminio' M_prima_leggimi_testa='Before touching anything, the connection to Delminio copied here what this project had on this machine. Nothing was deleted: the originals are still in place.' M_prima_leggimi_note='From now on the CLI'"'"'s notes aren'"'"'t read any more: the CLI reads Delminio'"'"'s index. The agent proposes them to you as memories, one by one, and only what you approve is created; you can keep the CLAUDE.md files as they are, or move them to Delminio.' M_prima_leggimi_tornare='To go back to how it was: `delminio disconnect`. It restores the previous settings, commands and MCP server, and the CLI goes back to reading its notes; what was created in Delminio stays in Delminio.' M_qwen_comando_apertura='Delminio: open the session with your role'"'"'s briefing — what you write after the command goes as your message' M_qwen_comando_chiusura='Delminio: end the session — what you write after the command goes as your message' M_senza_client_plugin='Delminio doesn'"'"'t provide the package client for the CLIs ({indirizzo})' M_senza_client_squadra='Delminio does not serve the team client ({indirizzo})' M_kit_non_firmato='{file} from {url} doesn'"'"'t carry Delminio'"'"'s release signature, or isn'"'"'t the signed file: not installing it. If this Delminio is a development build and you know it, run again with DELMINIO_KIT_SENZA_FIRMA=1.' : '⟦fine frasi⟧' export ${!M_@} # anche ai python (F, fra gli aiutanti qui sotto) PORTABILI=$(cat <<'PORTABILI' ha_terminale() { { : /dev/null; } _f() { # _f "$M_" [segnaposto valore]... → la frase coi {segnaposto} riempiti local t=$1 k v fuori shift while [ $# -ge 2 ]; do k="{$1}"; v=$2; fuori="" while [ "${t#*"$k"}" != "$t" ]; do fuori=$fuori${t%%"$k"*}$v; t=${t#*"$k"}; done t=$fuori$t; shift 2 done printf '%s\n' "$t" } export DELMINIO_F_PY='def F(chiave, **s): t = __import__("os").environ.get("M_" + chiave, chiave) for k, v in s.items(): t = t.replace("{" + k + "}", str(v)) return t' _sha16() { # stdin → i primi 16 dello sha256 (il nome del file del token: uguale ovunque) if command -v sha256sum >/dev/null 2>&1; then sha256sum elif command -v shasum >/dev/null 2>&1; then shasum -a 256 else python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' fi | cut -c1-16 } _tempo() { # _tempo — come timeout: 124 se scade if command -v timeout >/dev/null 2>&1; then timeout "$@" elif command -v gtimeout >/dev/null 2>&1; then gtimeout "$@" else python3 -c 'import subprocess, sys try: sys.exit(subprocess.run(sys.argv[2:], timeout=float(sys.argv[1])).returncode) except subprocess.TimeoutExpired: sys.exit(124) except OSError: sys.exit(127)' "$@" fi } _staccato() { # _staccato — in una sessione sua: la CLI che esce non se lo porta via if command -v setsid >/dev/null 2>&1; then setsid nohup "$@" else nohup python3 -c 'import os, sys try: os.setsid() except OSError: pass os.execvp(sys.argv[1], sys.argv[1:])' "$@" fi } _mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; } _lucchetto() { # _lucchetto — esclusivo sull'fd 9, come flock -w if command -v flock >/dev/null 2>&1; then flock -w "$1" 9 else python3 -c 'import fcntl, sys, time fine = time.time() + float(sys.argv[1]) while True: try: fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB); break except BlockingIOError: if time.time() > fine: sys.exit(1) time.sleep(0.5)' "$1" fi } _assoluto() { python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"; } _args() { # _args → gli argomenti del processo, uno per riga, coi loro confini if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; return; fi python3 -c 'import ctypes, ctypes.util, struct, sys pid = int(sys.argv[1]); libc = ctypes.CDLL(ctypes.util.find_library("c")) def leggi(mib): m = (ctypes.c_int * len(mib))(*mib); n = ctypes.c_size_t(0) if libc.sysctl(m, len(mib), None, ctypes.byref(n), None, 0): sys.exit(1) b = ctypes.create_string_buffer(n.value) if libc.sysctl(m, len(mib), b, ctypes.byref(n), None, 0): sys.exit(1) return b.raw[:n.value] if sys.platform == "darwin": r = leggi([1, 49, pid]) # KERN_PROCARGS2: argc, il percorso, NUL, gli argomenti argc = struct.unpack("i", r[:4])[0]; r = r[4:] args = r[r.index(b"\0"):].lstrip(b"\0").split(b"\0")[:argc] else: args = leggi([1, 14, 7, pid]).rstrip(b"\0").split(b"\0") # KERN_PROC_ARGS print("\n".join(a.decode(errors="replace") for a in args))' "$1" 2>/dev/null \ || ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n' } _chiave() { printf 'header = "Authorization: Bearer %s"\n' "$1"; } KIT_FIRMA='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0' _firmato() { # _firmato → 0 se il file sta nella firma del kit [ -n "${DELMINIO_KIT_SENZA_FIRMA:-}" ] && return 0 local d r=1 d=$(mktemp -d) || return 1 if curl -fsS -m 30 "$1/static/kit/FIRMA" -o "$d/f" 2>/dev/null \ && curl -fsS -m 30 "$1/static/kit/FIRMA.sig" -o "$d/f.sig" 2>/dev/null \ && printf 'rilasci@delminio.com %s\n' "$KIT_FIRMA" > "$d/chi" \ && ssh-keygen -Y verify -f "$d/chi" -I rilasci@delminio.com -n delminio-kit -s "$d/f.sig" < "$d/f" >/dev/null 2>&1 \ && python3 -c 'import hashlib, sys i = hashlib.sha256(open(sys.argv[3], "rb").read()).hexdigest() righe = open(sys.argv[1], encoding="utf-8").read().splitlines() sys.exit(0 if righe[:1] and righe[0].startswith("delminio-kit ") and i + " " + sys.argv[2] in righe[1:] else 1)' \ "$d/f" "$2" "$3"; then r=0 fi rm -rf "$d" return $r } campo() { # campo < json → il valore, o "" (anche su un corpo che non è JSON) python3 -c 'import json,sys try: print(json.load(sys.stdin).get(sys.argv[1]) or "") except Exception: print("")' "$1" } json_stringa() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"; } # una stringa JSON export DELMINIO_GANCI_PY='def nostro(h, cosa=None): c = h.get("command", "") return ".claude/mneme.sh" in c or ("delminio.sh" in c and (cosa is None or c.endswith(" " + cosa))) def togli_ganci(s, cosa=None): for evento, lista in list((s.get("hooks") or {}).items()): for b in lista: b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)] lista[:] = [b for b in lista if b.get("hooks")] if not lista: del s["hooks"][evento] if not s.get("hooks"): s.pop("hooks", None) def metti_ganci(s, comando, gesti, matcher_sempre=False): for evento, cosa, extra, matcher in gesti: lista = s.setdefault("hooks", {}).setdefault(evento, []) for b in lista: b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)] lista[:] = [b for b in lista if b.get("hooks")] lista.append({**({"matcher": matcher} if matcher or matcher_sempre else {}), "hooks": [{"type": "command", "command": comando + " " + cosa, **extra}]})' KIT_FILE=".claude/delminio.sh .claude/lanciatori.sh .claude/ganci-git.sh .claude/worktree.sh .claude/consumi.py .claude/cantiere.py .claude/backlog.py .claude/eseguibili.py .claude/cassaforte.py .claude/firme.py .claude/plugin.py .claude/squadra.py .claude/settings.local.json .claude/commands/apertura.md .claude/commands/chiusura.md .claude/commands/start.md .claude/commands/handoff.md .claude/commands/opening.md .claude/commands/closing.md .claude/rules/delminio.md .codex/hooks.json .qwen/settings.json .qwen/commands/apertura.md .qwen/commands/chiusura.md .qwen/commands/start.md .qwen/commands/handoff.md .qwen/commands/opening.md .qwen/commands/closing.md .claude/opencode.js .opencode/plugins/delminio.js" KIT_DI_PRIMA=".claude/guardia.py .claude/commands/risveglio.md" PORTABILI ) eval "$PORTABILI" installa="" agente_cli=""; agente_versione="" while [ $# -gt 0 ]; do case "$1" in --installa) installa=${2:-}; [ $# -ge 2 ] && shift; shift ;; --agente) agente_cli=${2:-}; agente_versione=${3:-}; shift; [ $# -gt 0 ] && shift; [ $# -gt 0 ] && shift ;; *) muori "$(_f "$M_argomento_ignoto" arg "$1")" ;; esac done case "$installa" in ''|claude|codex|qwen) ;; *) muori "$(_f "$M_installa_quale" cli "$installa")" ;; esac if [ -n "$agente_cli" ]; then case "$agente_cli" in claude|codex|qwen|opencode) ;; *) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac case "$agente_versione" in ''|*[!A-Za-z0-9.]*) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac fi segnaposto_apple() { local d [ "$(uname -s)" = Darwin ] || return 1 case "$1" in git|python3) ;; *) return 1 ;; esac # curl di /usr/bin è vero case "$(command -v "$1")" in /usr/bin/*) ;; *) return 1 ;; esac d=$(xcode-select -p 2>/dev/null) && [ -d "$d" ] && return 1 return 0 } for c in curl git python3; do command -v "$c" >/dev/null || muori "$(_f "$M_manca" c "$c")" if segnaposto_apple "$c"; then xcode-select --install >/dev/null 2>&1 || true muori "$M_mac_strumenti" fi case $c in curl) perche=$(curl --version 2>&1 >/dev/null) ;; git) perche=$(git --version 2>&1 >/dev/null) ;; python3) perche=$(python3 -c 'import json, ssl, urllib.request' 2>&1) ;; esac || { dove_c=$(command -v "$c"); perche=$(printf '%s' "${perche:-?}" | tail -1) muori "$(_f "$M_non_parte" c "$c" dove "$dove_c" perche "$perche")" } done if [ -n "$agente_cli" ]; then cartella_agente=$(mktemp -d) || muori "$(_f "$M_installa_non_riuscita" cli "$agente_cli")" curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \ || muori "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")" _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \ || muori "$(_f "$M_kit_non_firmato" file eseguibili-client url "$URL")" case $agente_cli in claude) nome_cli="Claude Code" ;; codex) nome_cli=Codex ;; qwen) nome_cli="Qwen Code" ;; *) nome_cli=OpenCode ;; esac _f "$M_installo_cli" cli "$nome_cli" uscita=$(python3 "$cartella_agente/eseguibili.py" installa-agente "$agente_cli" "$agente_versione") \ && lancia=$(printf '%s\n' "$uscita" | tail -1) && [ -x "$lancia" ] \ || { rm -rf "$cartella_agente"; muori "$(_f "$M_agente_non_installato" cli "$nome_cli")"; } rm -rf "$cartella_agente" nodo=$(printf '%s\n' "$uscita" | sed -n 's/^DELMINIO_NODE=//p' | tail -1) [ -n "$nodo" ] && PATH="$nodo:$PATH" && export PATH case $0 in /dev/fd/*|/proc/self/fd/*) cat "$0" >/dev/null 2>&1 || true ;; esac frase=$(_f "$M_agente_frase" url "$URL") primo=("$frase"); entra=$M_agente_entra_account [ "$agente_cli" = qwen ] && primo=(-i "$frase") && entra=$M_agente_entra_qwen export QWEN_CODE_SKIP_UPDATE_CHECK_ONCE=true OPENCODE_DISABLE_AUTOUPDATE=1 if [ "$agente_cli" = opencode ]; then primo=(--standalone) entra=$M_agente_entra_opencode ha_terminale || { echo "$M_agente_opencode_senza_terminale"; exit 0; } risposta=""; read -rp "$M_agente_opencode_domanda" risposta /dev/null || [ -n "$(ls -A "$d" 2>/dev/null)" ] \ || { [ "$1" = opencode ] && [ -n "$(ls -A "${DELMINIO_VERSIONI_OPENCODE:-$HOME/.local/share/delminio/opencode/versions}" 2>/dev/null)" ]; } } senza_cli="" cli_presente claude || cli_presente codex || cli_presente qwen || cli_presente opencode || senza_cli=1 chiedi_una_riga() { # chiedi_una_riga → la risposta, richiesta finché è vuota (tre volte) local r="" giri=0 while [ -z "$r" ] && [ $giri -lt 3 ]; do read -rp "$1" r /dev/null); then [ -n "$installa" ] && ha_terminale || muori "$M_fuori_dal_clone" domanda=$(_f "$M_progetto_nome" dove "$PWD") read -rp "$domanda" nome_progetto &2; } senza_credenziali() { sed -E 's#([A-Za-z][A-Za-z0-9+.-]*://)[^/[:space:]]*@#\1#g'; } [ -n "$(git config user.name)" ] && [ -n "$(git config user.email)" ] || muori "$M_chi_sei" if [ -n "$progetto_nuovo" ]; then git commit -q --allow-empty -m "$M_progetto_primo_commit" _f "$M_progetto_creato" cartella "$radice" fi if ! git remote get-url origin >/dev/null 2>&1; then avvisa "$M_senza_origin" elif ! perche=$(GIT_TERMINAL_PROMPT=0 git push --dry-run -q origin "HEAD:refs/heads/delminio-prova-del-push-$$" 2>&1); then origine=$(git remote get-url origin | senza_credenziali) errore_git=$(printf '%s' "$perche" | tail -1 | senza_credenziali) avvisa "$(_f "$M_non_pusha" origine "$origine" errore "$errore_git")" fi aggancio_col_codice() { local r codice disp c giri=0 macchina macchina=$(hostname 2>/dev/null || echo "?") r=$(python3 -c 'import json,sys; print(json.dumps({"macchina": sys.argv[1]}))' "$macchina" \ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \ "$URL/api/aggancio/inizia" 2>/dev/null) || return 1 [ "${r##*$'\n'}" = 200 ] || return 1 r=${r%$'\n'*} codice=$(printf '%s' "$r" | campo codice) disp=$(printf '%s' "$r" | campo dispositivo) [ -n "$codice" ] && [ -n "$disp" ] || return 1 { echo echo "$M_codice_apri" echo echo " $URL/?aggancio=$codice" echo _f "$M_codice_oppure" codice "$codice" echo _f "$M_codice_vale" macchina "$macchina" } >&2 while [ $giri -lt 220 ]; do sleep 3; giri=$((giri + 1)) r=$(python3 -c 'import json,sys; print(json.dumps({"dispositivo": sys.argv[1]}))' "$disp" \ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \ "$URL/api/aggancio/ritira" 2>/dev/null) || continue c=${r##*$'\n'} case "$c" in 200) printf '%s' "${r%$'\n'*}" | campo token echo "$M_approvato" >&2; return 0 ;; 410) echo "$M_scaduto" >&2; return 1 ;; esac done return 1 } token="${DELMINIO_TOKEN:-}" [ -n "$token" ] || token=$(aggancio_col_codice) || token="" if [ -z "$token" ]; then ha_terminale || muori "$M_senza_terminale" read -rsp "$M_domanda_token" token &1) \ || muori "$(_f "$M_non_risponde" url "$URL")" codice=${risposta##*$'\n'} [ "$codice" = 200 ] || muori "$(_f "$M_token_rifiutato" url "$URL" codice "$codice")" if frasi=$(curl -fsS -m 10 -K <(_chiave "$token") "$URL/aggancia.sh" 2>/dev/null | python3 -c ' import re, shlex, sys m = re.search(r"^: .⟦frasi: aggancia⟧.\n(.*?)^: .⟦fine frasi⟧.\n", sys.stdin.read(), re.S | re.M) voci = shlex.split(m.group(1), comments=True) if m else [] if voci and all(re.fullmatch(r"M_\w+=.*", v, re.S) for v in voci): print("".join("%s=%s\n" % (k, shlex.quote(v)) for k, _, v in (x.partition("=") for x in voci))) ') && [ -n "$frasi" ]; then eval "$frasi"; export ${!M_@} fi chi=$(python3 -c 'import json,sys; u=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("utente") or {}; print((u.get("mostrato") or u.get("nome") or "?") + " (" + (u.get("ruolo_detto") or u.get("ruolo") or "?") + ")")' <<<"$risposta") etichetta=$(python3 -c 'import json,sys; print(json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("etichetta") or "")' <<<"$risposta" 2>/dev/null) remoto_repo=$(git remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#' || true) conferma=false { [ -f .claude/delminio.sh ] || [ "${DELMINIO_STESSA_STORIA:-}" = si ]; } && conferma=true remoto_prima=$(sed -n 's/^REMOTO=//p' .claude/delminio.sh 2>/dev/null | head -1 | sed 's/\\\(.\)/\1/g' || true) corpo_repo=$(python3 -c 'import json,sys; print(json.dumps({"remoto": sys.argv[1], "nome": sys.argv[2], "conferma": sys.argv[3] == "true", "prima": sys.argv[4]}))' "$remoto_repo" "$(basename "$radice")" "$conferma" "$remoto_prima") repo=$(curl -sS -m 10 -w '\n%{http_code}' -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" 2>/dev/null) || repo="" _no_del_motore "$repo"; repo=${repo%$'\n'*} no=$(printf '%s' "$repo" | campo rifiuta) [ -z "$no" ] || muori "$(_f "$M_rifiutato" motivo "$no")" if [ -n "$repo" ] \ && altri=$(printf '%s' "$repo" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(", ".join(d.get("altri") or []) if d.get("chiede") else "")' 2>/dev/null) \ && [ -n "$altri" ]; then _f "$M_tiene_gia" altri "$altri" risposta_storia="${DELMINIO_STESSA_STORIA:-}" if [ -z "$risposta_storia" ] && ha_terminale; then nome_repo=$(basename "$radice") read -rp "$(_f "$M_stessa_storia" repo "$nome_repo")" risposta_storia /dev/null 2>&1 || true ;; *) muori "$M_altra_storia" ;; esac fi imp=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/impostazioni" 2>/dev/null || true) _no_del_motore "$imp" si; imp=${imp%$'\n'*} emb=$(printf '%s' "$imp" | python3 -c 'import json,sys try: e = json.load(sys.stdin).get("embedder") or {} except Exception: e = {} print(json.dumps({"url": e.get("url") or "", "modello": e.get("modello") or ""}) if not e.get("di_delminio") else "di_delminio")') memoria=$(printf '%s' "$imp" | campo memoria_sul_disco) kit=$(printf '%s' "$imp" | campo versione) [ -n "$memoria" ] && [ ! -d "$memoria" ] && memoria="" clone="" if [ -z "$memoria" ]; then remoto_memorie=$(printf '%s' "$imp" | campo memorie_remoto) dest="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$radice" | _sha16)/memoria" ssh_muto=${GIT_SSH_COMMAND:-ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new} if [ -d "$dest/.git" ]; then GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 30 git -C "$dest" pull -q --ff-only >/dev/null 2>&1 \ || avvisa "$(_f "$M_clone_fermo" cartella "$dest")" memoria=$dest; clone=si elif [ -n "$remoto_memorie" ] && command -v claude >/dev/null; then mkdir -p "$(dirname "$dest")" in_https=$(python3 -c 'import sys r = sys.argv[1].strip() if r.startswith("ssh://"): host, _, p = r[6:].split("@", 1)[-1].partition("/") host = host.split(":", 1)[0] elif "://" not in r and "@" in r and ":" in r.split("@", 1)[1]: host, _, p = r.split("@", 1)[1].partition(":") else: sys.exit(1) print("https://" + host + "/" + p.lstrip("/"))' "$remoto_memorie" 2>/dev/null || true) if GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$remoto_memorie" "$dest" 2>/dev/null \ || { [ -n "$in_https" ] && rm -rf "$dest" && GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$in_https" "$dest" 2>/dev/null \ && _f "$M_clone_https" remoto "$remoto_memorie" https "$in_https"; }; then memoria=$dest; clone=si if [ -f "$dest/MEMORY.md" ]; then _f "$M_clonate" remoto "$remoto_memorie" cartella "$dest" else avvisa "$(_f "$M_memorie_vuote" remoto "$remoto_memorie" cartella "$dest")" fi else _f "$M_clone_negato" remoto "$remoto_memorie" fi elif ! command -v claude >/dev/null && { cli_presente codex || cli_presente qwen; }; then echo "$M_codex_indice" fi fi if [ "$emb" != di_delminio ]; then case "$emb" in *'"url": ""'*) avvisa "$M_senza_embedder" ;; esac prova=$(curl -sS -m 30 -w '\n%{http_code}' -X POST -K <(_chiave "$token") \ -H "Content-Type: application/json" --data-binary "$emb" "$URL/api/impostazioni/embedder/prova" 2>/dev/null || true) if [ "${prova##*$'\n'}" = 200 ] && ! printf '%s' "${prova%$'\n'*}" | grep -q '"ok": *true'; then risposta_emb="${prova%$'\n'*}" avvisa "$(_f "$M_embedder_muto" risposta "$risposta_emb")" fi fi scarica_client() { # nome, destinazione, errore già composto nella lingua dello spazio local nuovo indirizzo="$URL/static/kit/$1" case $1 in *.*) ;; *) indirizzo+=-client ;; esac nuovo=$(mktemp "$2.XXXXXX") || muori "$3" if ! curl -fsS -K <(_chiave "$token") "$indirizzo" -o "$nuovo"; then rm -f "$nuovo" muori "$3" fi if ! _firmato "$URL" "${indirizzo##*/}" "$nuovo"; then rm -f "$nuovo" muori "$(_f "$M_kit_non_firmato" file "${indirizzo##*/}" url "$URL")" fi mv -f "$nuovo" "$2" } cartella_copia=$(mktemp -d) || muori "$M_prima_non_salva" scarica_client copia "$cartella_copia/copia.py" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/copia-client")" prima_volta=si; [ -f .claude/delminio.sh ] && prima_volta="" gitdir=$(_assoluto "$(git rev-parse --git-common-dir)") comune=$(dirname "$gitdir") if [ -n "$prima_volta" ]; then sua=$(python3 "$cartella_copia/copia.py" controlla "$radice" "$memoria" "$comune" "$URL" "$gitdir") if [ -n "$sua" ]; then cartella_sua="${sua%%$'\t'*}"; chi_lo_dice="${sua#*$'\t'}" _f "$M_note_sue" cartella "$cartella_sua" fonte "$chi_lo_dice" risposta_sua="${DELMINIO_MEMORIA_SUA:-}" if [ -z "$risposta_sua" ] && ha_terminale; then read -rp "$M_va_bene" risposta_sua "$file_token" ) scarica_client plugin .claude/plugin.py "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/plugin-client")" scarica_client squadra .claude/squadra.py "$(_f "$M_senza_client_squadra" indirizzo "$URL/static/kit/squadra-client")" mcp_locali() { # mcp_locali togli|da-parte python3 - "$1" "${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" "$radice" "$URL" \ "$(_assoluto "$(git rev-parse --git-common-dir)")/delminio-backup" <<'MCP_LOCALI' || true import glob, json, os, subprocess, sys gesto, cj, radice, url, segno = sys.argv[1:6] try: server = json.load(open(cj, encoding="utf-8"))["projects"][radice]["mcpServers"] or {} except (OSError, ValueError, KeyError, TypeError): server = {} for nome in ("memoria", "delminio"): s = server.get(nome) if not isinstance(s, dict): continue if str(s.get("url", "")).startswith(url): if gesto == "togli": subprocess.run(["claude", "mcp", "remove", nome, "-s", "local"], capture_output=True, timeout=60) elif gesto == "da-parte" and nome == "memoria": try: prime = sorted(glob.glob(os.path.join(open(segno, encoding="utf-8").read().strip(), "*", "fatti.json"))) except OSError: prime = [] dest = os.path.join(os.path.dirname(prime[-1]), "mcp-memoria.json") if prime else "" if dest and not os.path.exists(dest): os.umask(0o077) with open(dest, "w", encoding="utf-8") as f: json.dump(s, f, indent=2) MCP_LOCALI } con_plugin="" if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && command -v claude >/dev/null && python3 .claude/plugin.py claude "$radice"; then con_plugin=si mcp_locali togli else python3 .claude/plugin.py rimuovi "$radice" >/dev/null 2>&1 || true fi scarica_client opencode-client.js .claude/opencode.js "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/opencode-client.js")" if cli_presente opencode || [ -f .opencode/plugins/delminio.js ]; then python3 .claude/plugin.py opencode "$radice" || true fi ganci_claude_nel_progetto="" if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || { [ -z "$con_plugin" ] && command -v claude >/dev/null; }; then ganci_claude_nel_progetto=si fi if [ -z "$con_plugin" ] && command -v claude >/dev/null; then mcp_locali togli mcp_locali da-parte claude mcp remove memoria -s local >/dev/null 2>&1 || true cj="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" conf=$(python3 -c 'import json,sys url, f, cj, radice = sys.argv[1:5] try: fidato = json.load(open(cj, encoding="utf-8")).get("projects", {}).get(radice, {}).get("hasTrustDialogAccepted") is True except (OSError, ValueError, AttributeError): fidato = False h = "printf %s \"$(cat %s)\"" % (chr(39) + "{\"Authorization\":\"Bearer %s\"}" + chr(39), chr(39) + f + chr(39)) if not fidato or chr(39) in f or not all(32 <= ord(c) < 127 for c in h): sys.exit(1) print(json.dumps({"type": "http", "url": url + "/mcp", "headersHelper": h}))' "$URL" "$file_token" "$cj" "$radice" 2>/dev/null || true) if [ -z "$conf" ] || ! claude mcp add-json -s local memoria "$conf" >/dev/null 2>&1 \ || ! python3 -c 'import json,sys s = json.load(open(sys.argv[1], encoding="utf-8"))["projects"][sys.argv[2]]["mcpServers"]["memoria"] sys.exit(0 if s.get("headersHelper") else 1)' "$cj" "$radice" 2>/dev/null; then claude mcp remove memoria -s local >/dev/null 2>&1 || true ponte=$(python3 -c 'import json,sys; print(json.dumps({"type": "stdio", "command": "bash", "args": [sys.argv[1], "ponte"]}))' \ "$radice/.claude/delminio.sh") || muori "$M_mcp_fallito" claude mcp add-json -s local memoria "$ponte" >/dev/null || muori "$M_mcp_fallito" fi elif [ -z "$con_plugin" ] && [ -z "$installa" ] && ! cli_presente codex && ! cli_presente qwen; then avvisa "$M_mcp_senza_claude" fi for parte in lanciatori:lanciatori.sh ganci-git:ganci-git.sh worktree:worktree.sh consumi:consumi.py firme:firme.py; do scarica_client "${parte%%:*}" ".claude/${parte#*:}" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/${parte%%:*}-client")" done client_scaricato=$(mktemp) || muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")" curl -fsS -K <(_chiave "$token") "$URL/static/kit/delminio-client" -o "$client_scaricato" \ || { rm -f "$client_scaricato"; muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"; } _firmato "$URL" delminio-client "$client_scaricato" \ || { rm -f "$client_scaricato"; muori "$(_f "$M_kit_non_firmato" file delminio-client url "$URL")"; } { echo '#!/usr/bin/env bash' echo "# Il client di Delminio per gli hook di Claude Code, scritto da aggancia.sh." echo "# Il token sta fuori dal repo, nel file qui sotto (600). Per cambiarlo, rilancia l'aggancio." printf 'URL=%q\nFILE_TOKEN=%q\nMEMORIA=%q\nCLONE=%q\nKIT=%q\nREMOTO=%q\n' "$URL" "$file_token" "$memoria" "$clone" "$kit" "$remoto_repo" echo 'TOKEN=$(cat "$FILE_TOKEN" 2>/dev/null || true)' printf '%s\n' "$PORTABILI" cat "$client_scaricato" } > .claude/delminio.sh.nuovo rm -f "$client_scaricato" mv -f .claude/delminio.sh.nuovo .claude/delminio.sh chmod 700 .claude/delminio.sh comando_client=$(python3 -c 'import shlex,sys; print("bash " + shlex.quote(sys.argv[1]))' "$radice/.claude/delminio.sh") mkdir -p .claude/commands if [ -f .claude/commands/risveglio.md ] && grep -q 'delminio.sh' .claude/commands/risveglio.md; then rm -f .claude/commands/risveglio.md fi if [ -z "$ganci_claude_nel_progetto" ]; then for c in apertura chiusura opening closing start handoff; do f=".claude/commands/$c.md" [ -f "$f" ] || continue if grep -q 'delminio.sh' "$f"; then rm -f "$f" elif [ -n "$con_plugin" ] && { [ "$c" = apertura ] || [ "$c" = chiusura ]; }; then rm -f "$f"; fi done rmdir .claude/commands 2>/dev/null || true else cat > .claude/commands/apertura.md < .claude/commands/chiusura.md </dev/null || true import json, os, re, sys radice, url = sys.argv[1:3] def suo(s): return isinstance(s, dict) and not str(s.get("url") or s.get("httpUrl") or "").startswith(url) \ and "delminio" not in json.dumps([s.get("command"), s.get("args")]) f = os.path.join(radice, ".qwen", "settings.json") try: if suo((json.load(open(f, encoding="utf-8")).get("mcpServers") or {}).get("memoria")): print(f"{f}\tQwen Code") except (OSError, ValueError, AttributeError): pass for f, sempre in ((os.path.join(radice, ".codex", "config.toml"), True), (os.path.expanduser("~/.codex/config.toml"), False)): try: testo = open(f, encoding="utf-8").read() except OSError: continue if re.search(r"(?m)^\[mcp_servers\.memoria\]", testo) and (sempre or re.search(r"(?m)^\[marketplaces\.delminio\]", testo)): print(f"{f}\tCodex") NOME_NOSTRO ) for c in apertura chiusura opening closing start handoff; do f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/commands/$c.md" if [ -f "$f" ] && ! grep -q 'delminio.sh' "$f"; then avvisa "$(_f "$M_comando_tuo" file "$f" c "$c")" fi done python3 - "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "$radice" <<'GESTITE' || true import glob, json, os, runpy, sys config, radice = sys.argv[1], sys.argv[2] cartelle = os.environ.get("DELMINIO_GESTITE_DIRS", "/etc/claude-code:/Library/Application Support/ClaudeCode:/mnt/c/Program Files/ClaudeCode").split(":") def leggi(f): try: with open(f, encoding="utf-8") as h: return json.load(h) except Exception: return None def dice(testo): print("⚠️ " + testo, file=sys.stderr) for d in cartelle: for f in [os.path.join(d, "managed-settings.json")] + sorted(glob.glob(os.path.join(d, "managed-settings.d", "*.json"))): s = leggi(f) if not isinstance(s, dict): continue if s.get("disableAllHooks") is True: dice(f"{f} (impostazioni gestite di questa macchina) spegne TUTTI gli hook: gli agenti nascono senza l'apertura di Delminio, senza la posta e senza i controlli. Chiedi a chi amministra la macchina di togliere disableAllHooks, o di mettere gli hook di Delminio fra quelli gestiti.") if s.get("allowManagedHooksOnly") is True: dice(f"{f} lascia partire solo gli hook gestiti (allowManagedHooksOnly): quelli di Delminio no. Chiedi a chi amministra la macchina di aggiungerli fra quelli gestiti.") nomi = lambda lista: [str((x or {}).get("serverName") or (x or {}).get("serverUrl") or "") for x in (lista or []) if isinstance(x, dict)] consentiti = s.get("allowedMcpServers") di_delminio = lambda n: "delminio" in n.lower() or n.lower() == "memoria" if (isinstance(consentiti, list) and not any(di_delminio(n) for n in nomi(consentiti))) \ or any(di_delminio(n) for n in nomi(s.get("deniedMcpServers"))): dice(f"{f} non lascia collegare il server MCP «memoria» di Delminio: l'agente non raggiungerà la memoria. Chiedi di aggiungerlo fra i server consentiti.") if s.get("allowManagedPermissionRulesOnly") is True: try: nomi_tool = " e ".join(runpy.run_path(".claude/plugin.py")["TOOLS_CLAUDE"]) except Exception: nomi_tool = "mcp__plugin_delminio_memoria__delminio e mcp__plugin_delminio_memoria__delminio_write" dice(f"{f} tiene solo i permessi gestiti: ogni chiamata a Delminio chiederà il permesso. Chiedi di consentire {nomi_tool} fra i permessi gestiti.") for f in (os.path.join(config, "settings.json"), os.path.join(radice, ".claude", "settings.json"), os.path.join(radice, ".claude", "settings.local.json")): s = leggi(f) if isinstance(s, dict) and s.get("disableAllHooks") is True: dice(f"{f} ha disableAllHooks: true — è tua e non la tocco, ma con quella gli hook di Delminio non partono.") for f in ("/etc/codex/requirements.toml", "/etc/codex/managed_config.toml"): if os.path.isfile(f): dice(f"{f}: ci sono regole gestite di Codex su questa macchina. Delminio non le legge: se Codex non fa partire i ganci o il server MCP di Delminio, guarda lì.") GESTITE python3 - "$comando_client" "$memoria" "$con_plugin" "$ganci_claude_nel_progetto" <<'IMPOSTA' || muori "$(_f "$M_json_non_valido" file .claude/settings.local.json)" import json, pathlib, runpy, sys exec(__import__("os").environ["DELMINIO_GANCI_PY"]) comando, memoria, con_plugin, nel_progetto = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] pacchetto = runpy.run_path(".claude/plugin.py") p = pathlib.Path(".claude/settings.local.json") testo = p.read_text(encoding="utf-8") if p.exists() else "" s = json.loads(testo) if testo.strip() else {} if nel_progetto: metti_ganci(s, comando, pacchetto["GANCI_CLAUDE"]) else: togli_ganci(s) if memoria: s["autoMemoryDirectory"] = memoria allow = s.setdefault("permissions", {}).setdefault("allow", []) progetto = pacchetto["TOOLS_CLAUDE_PROGETTO"] tools, vecchi = ((progetto, pacchetto["TOOLS_CLAUDE"]) if nel_progetto else (pacchetto["TOOLS_CLAUDE"], progetto)) vecchi = (*vecchi, *pacchetto["TOOLS_CLAUDE_DI_PRIMA"]) allow[:] = [a for a in allow if a not in vecchi] allow.extend(t for t in tools if t not in allow) def scelte(f): try: v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("skillOverrides") except (OSError, ValueError, AttributeError): return {} return v if isinstance(v, dict) else {} gia = {**scelte(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json"), **scelte(".claude/settings.json")} mie = s.get("skillOverrides") if isinstance(s.get("skillOverrides"), dict) else {} import subprocess try: comune = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], capture_output=True, text=True, timeout=10).stdout.strip() except (OSError, subprocess.SubprocessError): comune = "" segno_f844 = pathlib.Path(comune) / "delminio-skill-f844" if comune else None if segno_f844 and not segno_f844.exists(): prima = pacchetto.get("SKILL_CLAUDE_F811") or {} mie = {n: (pacchetto["SKILL_CLAUDE"].get(n, v) if prima.get(n) == v else v) for n, v in mie.items()} if mie: s["skillOverrides"] = mie else: segno_f844 = None nuove = {n: v for n, v in pacchetto["SKILL_CLAUDE"].items() if n not in mie and n not in gia} if nuove: s["skillOverrides"] = {**mie, **nuove} def regole(f): try: v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("permissions") or {} except (OSError, ValueError, AttributeError): return [] return [r for k in ("allow", "ask", "deny") for r in (v.get(k) or []) if isinstance(r, str)] if isinstance(v, dict) else [] sue = regole(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json") \ + regole(".claude/settings.json") \ + [r for k in ("allow", "deny") for r in (s.get("permissions", {}).get(k) or []) if isinstance(r, str)] ask = s.setdefault("permissions", {}).setdefault("ask", []) for tool in pacchetto.get("CHIEDI_CLAUDE") or (): if tool not in ask and not any(r == tool or r.startswith(tool + "(") for r in sue): ask.append(tool) if not ask: s["permissions"].pop("ask") p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") if segno_f844: try: segno_f844.touch() except OSError: pass IMPOSTA if git ls-files --error-unmatch .codex/hooks.json >/dev/null 2>&1; then avvisa "$M_codex_sotto_git" else mkdir -p .codex python3 - "$comando_client" "${DELMINIO_SENZA_PLUGIN:-}" <<'CODEX' || muori "$(_f "$M_json_non_valido" file .codex/hooks.json)" import json, pathlib, runpy, sys exec(__import__("os").environ["DELMINIO_GANCI_PY"]) comando, senza_plugin = sys.argv[1], sys.argv[2] p = pathlib.Path(".codex/hooks.json") testo = p.read_text(encoding="utf-8") if p.exists() else "" s = json.loads(testo) if testo.strip() else {} if senza_plugin: metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_CODEX"]) else: togli_ganci(s) if s or p.exists(): p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") CODEX rmdir .codex 2>/dev/null || true # vuota: non era dell'umano, e il plugin non la usa fi qwen_senza_plugin=${DELMINIO_SENZA_PLUGIN:-} if [ -z "$qwen_senza_plugin" ] && cli_presente qwen; then for w in "${DELMINIO_BIN:-$HOME/.local/bin}"/*; do [ -f "$w" ] && grep -q '^export DELMINIO_CLI_NOME=qwen' "$w" 2>/dev/null || continue grep -q 'DELMINIO_NASCITA=porta' "$w" && continue if ! ( eval "$(grep -E '^export (QWEN_HOME|PATH|DELMINIO_CLI)=' "$w")" [ -n "${QWEN_HOME:-}" ] && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" \ python3 .claude/plugin.py qwen "$QWEN_HOME" >/dev/null 2>&1 ); then avvisa "$(_f "$M_qwen_ripiego" agente "$(basename "$w")")" qwen_senza_plugin=si fi done fi if git ls-files --error-unmatch .qwen/settings.json >/dev/null 2>&1; then avvisa "$M_qwen_sotto_git" else mkdir -p .qwen python3 - "$comando_client" "$qwen_senza_plugin" <<'QWEN' || muori "$(_f "$M_json_non_valido" file .qwen/settings.json)" import json, pathlib, runpy, sys exec(__import__("os").environ["DELMINIO_GANCI_PY"]) comando, senza_plugin = sys.argv[1], sys.argv[2] p = pathlib.Path(".qwen/settings.json") testo = p.read_text(encoding="utf-8") if p.exists() else "" s = json.loads(testo) if testo.strip() else {} if senza_plugin: metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_QWEN"], matcher_sempre=True) else: togli_ganci(s) if s or p.exists(): p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") QWEN if [ -z "$qwen_senza_plugin" ]; then for parola in apertura chiusura opening closing start handoff; do f=".qwen/commands/$parola.md" [ -f "$f" ] && grep -q 'Delminio' "$f" && rm -f "$f" done rmdir .qwen/commands .qwen 2>/dev/null || true else mkdir -p .qwen/commands for parola in apertura chiusura opening closing start handoff; do f=".qwen/commands/$parola.md" [ -f "$f" ] && ! grep -q 'Delminio' "$f" && continue case $parola in apertura|opening|start) descrizione=$M_qwen_comando_apertura ;; *) descrizione=$M_qwen_comando_chiusura ;; esac printf -- '---\ndescription: "%s"\n---\n%s\n' "${descrizione//\"/\'}" "$parola" > "$f" done fi fi mkdir -p .claude/rules cat > .claude/rules/delminio.md </dev/null; then avvisa "$(_f "$M_comando_occupato" file "$comando_delminio")" else mkdir -p "$bin_delminio" { cat <<'COMANDO' #!/usr/bin/env bash # delminio-comando # Scritto da aggancia.sh: i gesti di Delminio da qualunque cartella di un progetto collegato. 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" ]; then COMANDO printf ' echo %q >&2\n' "$M_comando_fuori" cat <<'COMANDO' exit 1 fi # Tutto al client, anche il Backlog: i nomi dei comandi in ogni lingua li sa lui (F666). exec bash "$r/.claude/delminio.sh" "$@" COMANDO } > "$comando_delminio.nuovo" && chmod 755 "$comando_delminio.nuovo" && mv -f "$comando_delminio.nuovo" "$comando_delminio" fi scarica_client cassaforte .claude/cassaforte.py "$(_f "$M_senza_client_cassaforte" indirizzo "$URL/static/kit/cassaforte-client")" rm -f .claude/guardia.py ganci_globali="" if ! git config --local core.hooksPath >/dev/null 2>&1 && git config core.hooksPath >/dev/null 2>&1; then ganci_globali=$(git config core.hooksPath) fi ganci=$(git config --local core.hooksPath || git rev-parse --git-path hooks) mkdir -p "$ganci" for g in commit-msg post-commit post-rewrite; do if [ -n "$ganci_globali" ]; then _f "$M_gancio_globale" dir "$ganci_globali" file "$ganci_globali/$g" riga "$comando_client $g \"\$@\"" continue fi f="$ganci/$g" if [ -e "$f" ] && ! sed -n 2p "$f" | grep -qE '^# (Delminio|Mneme) \(aggancia\.sh\)'; then grep -q "delminio.sh" "$f" \ || { riga_gancio="$comando_client $g \"\$@\""; _f "$M_gancio_tuo" file "$f" riga "$riga_gancio"; } continue fi printf '#!/bin/sh\n# Delminio (aggancia.sh): la chiusura giudicata dal motore. Gli altri commit passano.\nexec %s %s "$@"\n' "$comando_client" "$g" > "$f" chmod +x "$f" done pubblico=$(printf '%s' "$repo" | python3 -c 'import json,sys try: d = json.load(sys.stdin) except Exception: sys.exit(0) d = d.get("repo", d) if isinstance(d, dict) else {} print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null || true) segno="$(git rev-parse --path-format=absolute --git-common-dir)/delminio-pubblico" case "$pubblico" in si) : > "$segno" ;; no) rm -f "$segno" ;; esac escludi=$(git rev-parse --git-path info/exclude) mkdir -p "$(dirname "$escludi")" for f in $KIT_FILE .claude/delminio-prima/ .claude/delminio-personali/; do case "$f" in .codex/hooks.json|.qwen/settings.json) git ls-files --error-unmatch "$f" >/dev/null 2>&1 && continue ;; esac grep -qxF "$f" "$escludi" 2>/dev/null || echo "$f" >> "$escludi" done DELMINIO_PROVA=1 bash .claude/delminio.sh apertura < /dev/null > /dev/null \ || muori "$M_apertura_muta" spazio=$(python3 .claude/eseguibili.py spazio --da .claude/delminio.sh 2>/dev/null || printf '%s' "${URL%/}") case "$spazio" in *"#"*) nome_spazio="${etichetta:-${spazio##*#}}"; dove=$(_f "$M_nello_spazio" spazio "$nome_spazio") ;; *) dove="" python3 -c 'import json,sys; d=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]); sys.exit(0 if len(d.get("spazi") or []) > 1 else 1)' <<<"$risposta" 2>/dev/null \ && dove=$(_f "$M_nello_spazio" spazio principale) ;; esac nome_repo=$(basename "$radice") _f "$M_collegato" repo "$nome_repo" url "$URL" dove "$dove" chi "$chi" [ -n "$dove" ] && _f "$M_sempre_nello_spazio" dove "$dove" if [ -n "$salvato" ]; then _f "$M_prima_al_sicuro" cartella "$salvato" fi if ha_terminale && [ -f .claude/plugin.py ] && [ "$(python3 .claude/plugin.py app-codex stato 2>/dev/null)" = manca ]; then risposta_app=""; read -rp "$M_app_codex_domanda" risposta_app /dev/null || true); rm -f "$primo" [ -n "$lancia" ] && [ -x "$lancia" ] || muori "$(_f "$M_installa_non_riuscita" cli "$installa")" nome_agente=$(basename "$lancia") apertura=$M_rito_apertura; [ "$installa" = codex ] && apertura=$M_rito_apertura_codex # Codex: senza la barra case ":$PATH:" in *":$(dirname "$lancia"):"*) dopo=$nome_agente ;; *) dopo=$lancia ;; esac _f "$M_parto" nome "$nome_agente" apertura "$apertura" cartella "$radice" dopo "$dopo" case "$installa" in codex) echo "$M_parto_codex" ;; qwen) echo "$M_parto_qwen" ;; esac ha_terminale || exit 0 if [ -t 0 ]; then exec "$lancia"; fi exec "$lancia" /dev/null; then echo "$M_solo_claude" fi