#!/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. """La squadra di Delminio su questo computer (F810, F867): ciò che lo spazio dà a ogni suo""" from __future__ import annotations import hashlib import json import os import re import shlex import shutil import subprocess import sys NOME = 'delminio' FRASI = { "uso": "uso: python3 .claude/squadra.py accetta \xb7 lancio \xb7 codex|qwen \xb7 stacca ", "squadra_descrizione": "Le skill della squadra, da Delminio", "squadra_mcp_domanda": "\nIl server MCP \xab{nome}\xbb della squadra dello spazio:\n {cosa}\n\nGirer\xe0 su questo computer, coi tuoi permessi, ogni volta che parte un agente. Lo accetti? [s/N] ", "squadra_mcp_locale": "il comando che parte qui: {comando}\n le variabili d'ambiente che riceve: {variabili}", "squadra_mcp_remoto": "l'indirizzo che chiama: {url}\n la variabile d'ambiente che gli manda come chiave: {variabile}", "squadra_mcp_si": "s si s\xec y", "squadra_mcp_accettati": "\u2705 server MCP e plugin della squadra: {nuovi} accettati ora \xb7 {restano} restano fermi (se uno cambia, lo richiedo)", "squadra_plugin_domanda": "\nIl plugin \xab{nome}\xbb della squadra dello spazio:\n dal marketplace {mercato} ({origine}), per {cli}\n\nUn plugin pu\xf2 portare comandi, hook e server che girano su questo computer coi tuoi permessi. Lo installo? [s/N] " } def F(chiave: str, **valori) -> str: testo = FRASI[chiave] for k, v in valori.items(): testo = testo.replace('{' + k + '}', str(v)) return testo def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess: return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess: return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) SQUADRA_MKT = NOME + '-squadra-' NOME_PLUGIN_OK = re.compile('[a-z0-9]+(?:-[a-z0-9]+)*') def cartella_squadre() -> str: return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'squadre') def _chiave_ok(chiave: str) -> bool: return bool(re.fullmatch('[0-9a-f]{12}', chiave or '')) def squadra_di(chiave: str) -> dict: d = os.path.join(cartella_squadre(), chiave) try: with open(os.path.join(d, '.claude-plugin', 'marketplace.json'), encoding='utf-8') as h: m = json.load(h) p = m['plugins'][0] with open(os.path.join(d, '.impronta'), encoding='utf-8') as h: impronta = h.read().strip() except (OSError, ValueError, KeyError, IndexError, TypeError): return {} if not _chiave_ok(chiave) or not NOME_PLUGIN_OK.fullmatch(str(p.get('name') or '')): return {} try: with open(os.path.join(d, '.ruoli.json'), encoding='utf-8') as h: di_chi = json.load(h) except (OSError, ValueError): di_chi = {} return {'cartella': d, 'plugin': p['name'], 'versione': str(p.get('version') or ''), 'marketplace': m.get('name') or '', 'impronta': impronta, 'ruoli': di_chi if isinstance(di_chi, dict) else {}} def _norm_ruolo(nome: str) -> str: return ''.join((c for c in (nome or '').lower() if c.isalnum())) def _testa(testo: str) -> tuple[dict, str]: m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S) if not m: return ({}, testo) campi = {} for riga in m.group(1).splitlines(): k, _, v = riga.partition(':') v = v.strip() if v[:1] == '"': try: v = json.loads(v) except ValueError: v = v.strip('"') campi[k.strip()] = v return (campi, testo[m.end():]) def _col_nome(testo: str, nome: str) -> str: m = re.match('^---[ \\t]*\\n(.*?)\\n---[ \\t]*(?:\\n|$)', testo, re.S) if not m: return f'---\nname: {nome}\n---\n' + testo righe = [r for r in m.group(1).splitlines() if not re.match('name[ \\t]*:', r)] return '---\n' + '\n'.join([f'name: {nome}', *righe]) + '\n---\n' + testo[m.end():] def _mcp_claude(spec: dict) -> dict: if spec.get('tipo') == 'remoto': t = spec.get('token_variabile') return {'type': 'http', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})} return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})} def _mcp_qwen(spec: dict) -> dict: if spec.get('tipo') == 'remoto': t = spec.get('token_variabile') return {'httpUrl': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})} return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})} _TESTA_AMMESSA = frozenset({'name', 'description', 'argument-hint', 'when_to_use', 'disable-model-invocation', 'user-invocable', 'model', 'color', 'tools', 'modelConfig', 'runConfig'}) _CHIAVE_TESTA = re.compile('([A-Za-z_][\\w-]*)[ \\t]*:(?:[ \\t]|$)') def _testa_ripulita(testo: str) -> str: m = re.match('^(\\ufeff?\\s*---[ \\t]*\\r?\\n)(.*?)(\\r?\\n---[ \\t]*(?:\\r?\\n|$))', testo, re.S) if not m: return testo tenute, tieni = ([], False) for riga in re.split('\\r\\n|\\r|\\n', m.group(2)): if riga[:1] not in (' ', '\t'): k = _CHIAVE_TESTA.match(riga) tieni = bool(k) and k.group(1) in _TESTA_AMMESSA if tieni: tenute.append(riga) return '---\n' + ''.join((r + '\n' for r in tenute)) + '---\n' + testo[m.end():] def _stampabile(v) -> bool: if isinstance(v, str): return v.isprintable() if isinstance(v, dict): return all((_stampabile(k) and _stampabile(x) for k, x in v.items())) if isinstance(v, list): return all((_stampabile(x) for x in v)) return True def _visibile(v) -> str: return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v))) def _mcp_impronta(nome: str, spec: dict) -> str: return hashlib.sha256(json.dumps([nome, spec], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24] def _accettati_file(chiave: str) -> str: return os.path.join(cartella_squadre(), chiave + '.mcp-accettati') def mcp_accettati(chiave: str) -> set[str]: try: with open(_accettati_file(chiave), encoding='utf-8') as h: return set(h.read().split()) except OSError: return set() def _squadra_contenuti(chiave: str, pacco: dict) -> dict[str, str]: plugin = str(pacco.get('plugin') or 'squadra') if not NOME_PLUGIN_OK.fullmatch(plugin): plugin = 'squadra' impronta = str(pacco.get('impronta') or '') descrizione = F('squadra_descrizione') mkt = SQUADRA_MKT + chiave pezzi = pacco.get('pezzi') if isinstance(pacco.get('pezzi'), list) else [{**x, 'tipo': 'skill'} for x in pacco.get('skill') or [] if isinstance(x, dict)] tutti, plugin_squadra = ([], []) for x in pezzi: tipo, nome = (str(x.get('tipo') or ''), str(x.get('nome') or '')) if tipo == 'plugin' and NOME_PLUGIN_OK.fullmatch(nome) and (len(nome) <= 64): if (spec := _plugin_spec((x.get('file') or {}).get('plugin.json'))): plugin_squadra.append({'nome': nome, 'spec': spec, 'impronta': _mcp_impronta(nome, spec), 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})}) continue if tipo not in ('skill', 'comando', 'agente', 'mcp') or not NOME_PLUGIN_OK.fullmatch(nome) or len(nome) > 64: continue file = {} for rel, testo in (x.get('file') or {}).items(): pezzi_rel = str(rel).replace('\\', '/').split('/') if isinstance(testo, str) and (not any((not q or q.startswith('.') for q in pezzi_rel))): file[os.path.join(*pezzi_rel)] = testo principale = {'skill': 'SKILL.md', 'comando': 'comando.md', 'agente': 'agente.md', 'mcp': 'mcp.json'}[tipo] if principale not in file: continue if tipo != 'mcp': file[principale] = _testa_ripulita(file[principale]) spec = {} if tipo == 'mcp': try: spec = json.loads(file[principale]) spec = {k: v for k, v in spec.items() if k != 'descrizione'} _mcp_claude(spec) except (ValueError, KeyError, TypeError, AttributeError): continue if not _stampabile(spec): continue tutti.append({'tipo': tipo, 'nome': nome, 'file': file, 'principale': principale, 'spec': spec, 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})}) accettati = mcp_accettati(chiave) fermi = [{'nome': x['nome'], 'spec': x['spec'], 'impronta': _mcp_impronta(x['nome'], x['spec'])} for x in tutti if x['tipo'] == 'mcp' and _mcp_impronta(x['nome'], x['spec']) not in accettati] via = {x['nome'] for x in fermi} tutti = [x for x in tutti if not (x['tipo'] == 'mcp' and x['nome'] in via)] dentro = sorted((_mcp_impronta(x['nome'], x['spec']) for x in tutti if x['tipo'] == 'mcp')) minore = int(hashlib.sha256(' '.join(dentro).encode()).hexdigest()[:5], 16) + 1 if dentro else 0 versione = f"1.{minore}.{int((impronta or '0')[:7], 16)}" f: dict[str, str] = {} manifesto = {'name': plugin, 'version': versione, 'description': descrizione} def un_plugin(dove: str, scelti) -> None: mcp_claude, mcp_qwen = ({}, {}) for x in scelti: n = x['nome'] if x['tipo'] == 'skill': for rel, testo in x['file'].items(): f[os.path.join(dove, 'skills', n, rel)] = testo elif x['tipo'] == 'comando': f[os.path.join(dove, 'commands', n + '.md')] = x['file']['comando.md'] elif x['tipo'] == 'agente': f[os.path.join(dove, 'agents', n + '.md')] = x['file']['agente.md'] else: mcp_claude[n] = _mcp_claude(x['spec']) mcp_qwen[plugin + '-' + n] = _mcp_qwen(x['spec']) f[os.path.join(dove, '.claude-plugin', 'plugin.json')] = json.dumps(manifesto, ensure_ascii=False, indent=2) + '\n' if mcp_claude: f[os.path.join(dove, '.mcp.json')] = json.dumps({'mcpServers': mcp_claude}, ensure_ascii=False, indent=2) + '\n' f[os.path.join(dove, 'qwen-extension.json')] = json.dumps({**manifesto, **({'mcpServers': mcp_qwen} if mcp_qwen else {})}, ensure_ascii=False, indent=2) + '\n' per_tutti = [x for x in tutti if not x['ruoli']] un_plugin(plugin, per_tutti) for r in sorted({r for x in tutti for r in x['ruoli']}): un_plugin(os.path.join('ruoli', r, plugin), per_tutti + [x for x in tutti if r in x['ruoli']]) lancio = {'skill': {}, 'agente': {}, 'mcp': {}} for x in tutti: n = x['nome'] if x['tipo'] == 'skill': for rel, testo in x['file'].items(): f[os.path.join('codex', plugin, 'skills', n, rel)] = testo lancio['skill'][n] = x['ruoli'] if len(plugin) + 1 + len(n) <= 64: for rel, testo in x['file'].items(): f[os.path.join('opencode', 'skills', f'{plugin}-{n}', rel)] = _col_nome(testo, f'{plugin}-{n}') if rel == 'SKILL.md' else testo elif x['tipo'] == 'comando': campi, corpo = _testa(x['file']['comando.md']) f[os.path.join('codex', plugin, 'skills', n, 'SKILL.md')] = f"---\nname: {n}\ndescription: {json.dumps(str(campi.get('description') or ''), ensure_ascii=False)}\n---\n" + corpo.lstrip('\n') lancio['skill'][n] = x['ruoli'] elif x['tipo'] == 'agente': campi, corpo = _testa(x['file']['agente.md']) f[os.path.join('codex', 'agenti', n + '.toml')] = f'name = {json.dumps(n)}\ndeveloper_instructions = {json.dumps(corpo.strip(), ensure_ascii=False)}\n' lancio['agente'][n] = {'ruoli': x['ruoli'], 'descrizione': str(campi.get('description') or '')} else: lancio['mcp'][n] = {'ruoli': x['ruoli'], 'spec': x['spec']} f[os.path.join('codex', plugin, '.codex-plugin', 'plugin.json')] = json.dumps({**manifesto, 'skills': './skills/'}, ensure_ascii=False, indent=2) + '\n' lancio['conto'] = {t: sum((1 for x in tutti if x['tipo'] == t)) for t in ('skill', 'comando', 'agente', 'mcp')} lancio['conto']['mcp_fermi'] = len(fermi) f['.ruoli.json'] = json.dumps(lancio, indent=2, sort_keys=True, ensure_ascii=False) + '\n' f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': mkt, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': plugin, 'source': './' + plugin, 'description': descrizione, 'version': versione}]}, ensure_ascii=False, indent=2) + '\n' f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': mkt, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': plugin, 'source': {'source': 'local', 'path': './codex/' + plugin}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n' f['.impronta'] = impronta + '\n' f['.pacco.json'] = json.dumps(pacco, ensure_ascii=False, sort_keys=True) + '\n' if fermi: f['.mcp-fermi.json'] = json.dumps(fermi, ensure_ascii=False, indent=2, sort_keys=True) + '\n' if plugin_squadra: presi = plugin_accettati(chiave) for x in plugin_squadra: x['accettato'] = x['impronta'] in presi f['.plugin.json'] = json.dumps(plugin_squadra, ensure_ascii=False, indent=2, sort_keys=True) + '\n' if (fermi_p := [x for x in plugin_squadra if not x['accettato']]): f['.plugin-fermi.json'] = json.dumps(fermi_p, ensure_ascii=False, indent=2, sort_keys=True) + '\n' return f def squadra_accetta_dal_terminale() -> int: radice = cartella_squadre() try: chiavi = sorted((c for c in os.listdir(radice) if _chiave_ok(c))) except OSError: return 0 try: tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w')) except OSError: return 1 nuovi = restano = 0 for chiave in chiavi: d = os.path.join(radice, chiave) try: with open(os.path.join(d, '.pacco.json'), encoding='utf-8') as h: pacco = json.load(h) except (OSError, ValueError): continue try: with open(os.path.join(d, '.mcp-fermi.json'), encoding='utf-8') as h: fermi = json.load(h) except (OSError, ValueError): fermi = [] accettati, presi = (mcp_accettati(chiave), 0) for x in fermi if isinstance(fermi, list) else []: spec, nome = (x.get('spec') or {}, str(x.get('nome') or '')) if not isinstance(spec, dict) or not _stampabile(spec): restano += 1 continue if spec.get('tipo') == 'remoto': cosa = F('squadra_mcp_remoto', url=_visibile(spec.get('url') or ''), variabile=_visibile(spec.get('token_variabile') or '—')) else: cosa = F('squadra_mcp_locale', comando=_visibile(shlex.join([str(spec.get('comando') or '')] + [str(a) for a in spec.get('argomenti') or []])), variabili=_visibile(', '.join((str(v) for v in spec.get('variabili') or [])) or '—')) tty.write(F('squadra_mcp_domanda', nome=_visibile(nome), cosa=cosa)) tty.flush() if tty_in.readline().strip().lower() in F('squadra_mcp_si').split(): accettati.add(_mcp_impronta(nome, spec)) presi += 1 else: restano += 1 try: with open(os.path.join(d, '.plugin-fermi.json'), encoding='utf-8') as h: plugin_fermi = json.load(h) except (OSError, ValueError): plugin_fermi = [] presi_p, plugin_presi = (0, plugin_accettati(chiave)) for x in plugin_fermi if isinstance(plugin_fermi, list) else []: spec, nome = (_plugin_spec(json.dumps((x or {}).get('spec'))), str((x or {}).get('nome') or '')) if not spec or not NOME_PLUGIN_OK.fullmatch(nome): restano += 1 continue tty.write(F('squadra_plugin_domanda', nome=_visibile(nome), mercato=_visibile(spec['mercato']), origine=_visibile(spec['origine']), cli=', '.join(spec['cli']))) tty.flush() if tty_in.readline().strip().lower() in F('squadra_mcp_si').split(): plugin_presi.add(_mcp_impronta(nome, spec)) presi_p += 1 else: restano += 1 if presi_p: os.makedirs(radice, exist_ok=True) with open(_plugin_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h: h.write(''.join((i + '\n' for i in sorted(plugin_presi)))) os.replace(_plugin_accettati_file(chiave) + '.nuovo', _plugin_accettati_file(chiave)) presi += presi_p if presi: os.makedirs(radice, exist_ok=True) with open(_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h: h.write(''.join((i + '\n' for i in sorted(accettati)))) os.replace(_accettati_file(chiave) + '.nuovo', _accettati_file(chiave)) squadra_scrivi(chiave, pacco) nuovi += presi if nuovi or restano: print(F('squadra_mcp_accettati', nuovi=nuovi, restano=restano)) return 0 def squadra_scrivi(chiave: str, pacco: dict) -> dict: if not _chiave_ok(chiave): return {} d = os.path.join(cartella_squadre(), chiave) if not (pacco.get('pezzi') or pacco.get('skill')): shutil.rmtree(d, ignore_errors=True) return {} voluti = _squadra_contenuti(chiave, pacco) for rel, testo in voluti.items(): p = os.path.join(d, rel) try: with open(p, encoding='utf-8') as h: if h.read() == testo: continue except (OSError, UnicodeDecodeError): pass os.makedirs(os.path.dirname(p), exist_ok=True) with open(p + '.nuovo', 'w', encoding='utf-8') as h: h.write(testo) os.replace(p + '.nuovo', p) for radice, cartelle, nomi in os.walk(d, topdown=False): for n in nomi: rel = os.path.relpath(os.path.join(radice, n), d) if rel not in voluti: os.remove(os.path.join(radice, n)) if radice != d and (not os.listdir(radice)): os.rmdir(radice) return squadra_di(chiave) def _squadra_id(sq: dict) -> str: return f"{sq['plugin']}@{sq['marketplace']}" def squadra_claude(radice: str, chiave: str) -> int: p = os.path.join(radice, '.claude', 'settings.local.json') try: with open(p, encoding='utf-8') as h: s = json.load(h) except (OSError, ValueError): s = {} accesi = s.get('enabledPlugins') if isinstance(s.get('enabledPlugins'), dict) else {} mkt = SQUADRA_MKT + chiave sq = squadra_di(chiave) voluto = _squadra_id(sq) if sq else '' vecchi = [k for k in accesi if k.endswith('@' + mkt) and k != voluto] if (not voluto or accesi.get(voluto) is True) and (not vecchi): return 0 if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'): return 3 try: for k in vecchi: _claude('uninstall', k, '--scope', 'local', cwd=radice) if voluto: _claude('marketplace', 'add', sq['cartella'], '--scope', 'local', cwd=radice) _claude('install', voluto, '--scope', 'local', cwd=radice) else: _claude('marketplace', 'remove', mkt, '--scope', 'local', cwd=radice) except (OSError, subprocess.TimeoutExpired): return 3 return 0 def _squadra_codex(casa: str) -> None: chiave = os.path.basename(os.path.normpath(casa)) if not _chiave_ok(chiave): return sq = squadra_di(chiave) try: with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h: conf = h.read() except OSError: conf = '' mkt = SQUADRA_MKT + chiave if not sq: for m in re.finditer('^\\[plugins\\."([a-z0-9-]+@' + re.escape(mkt) + ')"\\]', conf, re.M): _codex(casa, 'remove', m.group(1)) if mkt in conf: _codex(casa, 'marketplace', 'remove', mkt) return pid = _squadra_id(sq) acceso = re.search('^\\[plugins\\."' + re.escape(pid) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M) if acceso and os.path.isdir(os.path.join(casa, 'plugins', 'cache', mkt, sq['plugin'], sq['versione'])): return _codex(casa, 'marketplace', 'add', sq['cartella']) _codex(casa, 'add', pid) def _squadra_qwen(casa: str) -> None: chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0] if not _chiave_ok(chiave): return sq = squadra_di(chiave) q = os.environ.get('DELMINIO_QWEN') or 'qwen' ambiente = {**os.environ, 'QWEN_HOME': casa} via = [n for n in (os.listdir(os.path.join(casa, 'extensions')) if os.path.isdir(os.path.join(casa, 'extensions')) else []) if n != NOME and _collegata_a(casa, n, cartella_squadre()) and (not sq or n != sq['plugin'])] for n in via: subprocess.run([q, 'extensions', 'uninstall', n], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) if not sq: return del_ruolo = os.path.join(sq['cartella'], 'ruoli', _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')), sq['plugin']) estensione = del_ruolo if _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')) and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], sq['plugin']) if _collegata_a(casa, sq['plugin'], estensione): return subprocess.run([q, 'extensions', 'uninstall', sq['plugin']], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n') _PLUGIN_ORIGINE = re.compile('(github:[A-Za-z0-9][\\w.-]*/[\\w.-]+|https://[^\\s@?#]{3,300})') def _plugin_spec(testo) -> dict: try: d = json.loads(testo) if isinstance(testo, str) else {} except ValueError: return {} if not isinstance(d, dict): return {} mercato, origine = (str(d.get('mercato') or ''), str(d.get('origine') or '')) cli = [c for c in ('claude', 'codex', 'qwen') if c in (d.get('cli') or [])] if not re.fullmatch('[\\w.-]{1,100}', mercato) or not _PLUGIN_ORIGINE.fullmatch(origine) or (not cli) or (not _stampabile({'m': mercato, 'o': origine})): return {} return {'mercato': mercato, 'origine': origine, 'cli': cli} def _plugin_accettati_file(chiave: str) -> str: return os.path.join(cartella_squadre(), chiave + '.plugin-accettati') def plugin_accettati(chiave: str) -> set[str]: try: with open(_plugin_accettati_file(chiave), encoding='utf-8') as h: return set(h.read().split()) except OSError: return set() def plugin_squadra(chiave: str, cli: str) -> list[dict]: try: with open(os.path.join(cartella_squadre(), chiave, '.plugin.json'), encoding='utf-8') as h: tutti = json.load(h) except (OSError, ValueError): return [] presi = plugin_accettati(chiave) return [x for x in tutti if isinstance(x, dict) and x.get('impronta') in presi and (cli in (x.get('spec') or {}).get('cli', [])) and NOME_PLUGIN_OK.fullmatch(str(x.get('nome') or '')) and _plugin_spec(json.dumps(x.get('spec')))] def _installati(chiave: str) -> dict: try: with open(os.path.join(cartella_squadre(), chiave + '.plugin-installati.json'), encoding='utf-8') as h: d = json.load(h) return d if isinstance(d, dict) else {} except (OSError, ValueError): return {} def _installati_scrivi(chiave: str, d: dict) -> None: p = os.path.join(cartella_squadre(), chiave + '.plugin-installati.json') os.makedirs(os.path.dirname(p), exist_ok=True) with open(p + '.nuovo', 'w', encoding='utf-8') as h: json.dump(d, h, indent=2, sort_keys=True) os.replace(p + '.nuovo', p) def _sorgente(origine: str, cli: str) -> str: if origine.startswith('github:'): return origine[7:] if cli != 'qwen' else 'https://github.com/' + origine[7:] return origine def _claude_installati(radice: str) -> dict: cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude') try: with open(os.path.join(cfg, 'plugins', 'installed_plugins.json'), encoding='utf-8') as h: d = json.load(h).get('plugins') or {} except (OSError, ValueError, AttributeError): return {} return {pid: str(v.get('installPath') or '') for pid, voci in d.items() if isinstance(voci, list) for v in voci if isinstance(v, dict) and v.get('scope') in ('local', 'project') and (v.get('projectPath') == radice)} def squadra_plugin_claude(radice: str, chiave: str) -> int: if not radice or not _chiave_ok(chiave) or (not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude')): return 3 voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'claude')} stato = _installati(chiave) miei = stato.get('claude:' + radice) or {} c_e = _claude_installati(radice) try: with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h: accesi = json.load(h).get('enabledPlugins') or {} except (OSError, ValueError, AttributeError): accesi = {} for pid, x in voluti.items(): if pid not in c_e: _claude('marketplace', 'add', _sorgente(x['spec']['origine'], 'claude'), '--scope', 'local', cwd=radice) if _claude('install', pid, '--scope', 'local', cwd=radice).returncode != 0: continue miei[pid] = True elif pid not in miei: continue per_tutti = not x['ruoli'] if per_tutti and accesi.get(pid) is not True: _claude('enable', pid, '--scope', 'local', cwd=radice) elif not per_tutti and accesi.get(pid) is not False: _claude('disable', pid, '--scope', 'local', cwd=radice) for pid in [k for k in miei if k not in voluti]: _claude('uninstall', pid, '--scope', 'local', cwd=radice) miei.pop(pid) stato['claude:' + radice] = miei _installati_scrivi(chiave, stato) return 0 def _squadra_plugin_codex(casa: str) -> None: chiave = os.path.basename(os.path.normpath(casa)) if not _chiave_ok(chiave): return voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'codex') if not x['ruoli']} stato = _installati(chiave) miei = stato.get('codex:' + casa) or {} try: with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h: conf = h.read() except OSError: conf = '' for pid, x in voluti.items(): if f'[plugins."{pid}"]' in conf: continue if f"[marketplaces.{x['spec']['mercato']}]" not in conf: _codex(casa, 'marketplace', 'add', _sorgente(x['spec']['origine'], 'codex')) if _codex(casa, 'add', pid).returncode == 0: miei[pid] = True for pid in [k for k in miei if k not in voluti]: _codex(casa, 'remove', pid) miei.pop(pid) stato['codex:' + casa] = miei _installati_scrivi(chiave, stato) def _squadra_plugin_qwen(casa: str) -> None: chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0] if not _chiave_ok(chiave): return ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')) voluti = {x['nome']: x for x in plugin_squadra(chiave, 'qwen') if not x['ruoli'] or ruolo in x['ruoli']} stato = _installati(chiave) miei = stato.get('qwen:' + casa) or {} q = os.environ.get('DELMINIO_QWEN') or 'qwen' ambiente = {**os.environ, 'QWEN_HOME': casa} for nome, x in voluti.items(): if os.path.isdir(os.path.join(casa, 'extensions', nome)): continue r = subprocess.run([q, 'extensions', 'install', f"{_sorgente(x['spec']['origine'], 'qwen')}:{nome}", '--consent'], env=ambiente, capture_output=True, text=True, timeout=300, stdin=subprocess.DEVNULL) if r.returncode == 0: miei[nome] = True for nome in [k for k in miei if k not in voluti]: subprocess.run([q, 'extensions', 'uninstall', nome], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) miei.pop(nome) stato['qwen:' + casa] = miei _installati_scrivi(chiave, stato) def squadra_lancio(cli: str, dove: str) -> list[str]: ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')) if cli == 'claude': try: with open(os.path.join(dove, '.claude', 'settings.local.json'), encoding='utf-8') as h: accesi = json.load(h).get('enabledPlugins') or {} except (OSError, ValueError, AttributeError): return [] chiavi = [m.group(1) for k, v in accesi.items() if v is True for m in [re.search('@' + re.escape(SQUADRA_MKT) + '([0-9a-f]{12})$', k)] if m] sq = squadra_di(chiavi[0]) if chiavi else {} d = os.path.join(sq['cartella'], 'ruoli', ruolo, sq['plugin']) if sq and ruolo else '' out = ['--plugin-dir', d] if d and os.path.isdir(d) else [] if chiavi and ruolo: c_e = _claude_installati(dove) for x in plugin_squadra(chiavi[0], 'claude'): cartella = c_e.get(f"{x['nome']}@{x['spec']['mercato']}", '') if ruolo in x['ruoli'] and cartella and os.path.isdir(cartella): out += ['--plugin-dir', cartella] return out if cli == 'codex': chiave = os.path.basename(os.path.normpath(dove)) sq = squadra_di(chiave) if _chiave_ok(chiave) else {} if not sq: return [] lancio = sq['ruoli'] per_me = lambda r: not r or ruolo in r out = [] base = os.path.join(dove, 'plugins', 'cache', sq['marketplace'], sq['plugin'], sq['versione'], 'skills') via = [n for n, r in sorted((lancio.get('skill') or {}).items()) if not per_me(r) and NOME_PLUGIN_OK.fullmatch(n)] if via: voci = ','.join(('{path=' + json.dumps(os.path.join(base, n, 'SKILL.md')) + ',enabled=false}' for n in via)) out += ['-c', f'skills.config=[{voci}]'] for n, a in sorted((lancio.get('agente') or {}).items()): toml = os.path.join(sq['cartella'], 'codex', 'agenti', n + '.toml') if NOME_PLUGIN_OK.fullmatch(n) and per_me(a.get('ruoli')) and os.path.isfile(toml): out += ['-c', f"agents.{n}.description={json.dumps(a.get('descrizione') or n, ensure_ascii=False)}", '-c', f'agents.{n}.config_file={json.dumps(toml)}'] for n, m in sorted((lancio.get('mcp') or {}).items()): spec, k = (m.get('spec') or {}, f"{sq['plugin']}-{n}") if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')): continue if spec.get('tipo') == 'remoto' and spec.get('url'): out += ['-c', f"mcp_servers.{k}.url={json.dumps(spec['url'])}"] if spec.get('token_variabile'): out += ['-c', f"mcp_servers.{k}.bearer_token_env_var={json.dumps(spec['token_variabile'])}"] elif spec.get('comando'): out += ['-c', f"mcp_servers.{k}.command={json.dumps(spec['comando'])}", '-c', f"mcp_servers.{k}.args={json.dumps(list(spec.get('argomenti') or []))}"] if spec.get('variabili'): out += ['-c', f"mcp_servers.{k}.env_vars={json.dumps(list(spec['variabili']))}"] return out if cli == 'opencode': return [json.dumps(_squadra_opencode(ruolo), ensure_ascii=False)] return [] def _squadra_opencode(ruolo: str) -> dict: chiave = os.environ.get('DELMINIO_SQUADRA', '') sq = squadra_di(chiave) if _chiave_ok(chiave) else {} if not sq: return {} lancio, plugin = (sq['ruoli'], sq['plugin']) per_me = lambda r: not r or ruolo in r skill = [os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}') for n, r in sorted((lancio.get('skill') or {}).items()) if per_me(r) and NOME_PLUGIN_OK.fullmatch(n) and os.path.isfile(os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}', 'SKILL.md'))] del_ruolo = os.path.join(sq['cartella'], 'ruoli', ruolo, plugin) base = del_ruolo if ruolo and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], plugin) comandi, agenti = ({}, {}) for cartella, dove in (('commands', comandi), ('agents', agenti)): try: nomi = sorted(os.listdir(os.path.join(base, cartella))) except OSError: nomi = [] for x in nomi: n = x[:-3] if x.endswith('.md') else '' if not NOME_PLUGIN_OK.fullmatch(n): continue try: with open(os.path.join(base, cartella, x), encoding='utf-8') as h: campi, corpo = _testa(h.read()) except OSError: continue descrizione = str(campi.get('description') or n) if cartella == 'commands': dove[f'{plugin}:{n}'] = {'template': corpo.strip() or '$ARGUMENTS', 'description': descrizione} else: dove[f'{plugin}-{n}'] = {'mode': 'subagent', 'description': descrizione, 'system': corpo.strip()} server = {} for n, m in sorted((lancio.get('mcp') or {}).items()): spec = m.get('spec') or {} if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')): continue if spec.get('tipo') == 'remoto' and spec.get('url'): t = spec.get('token_variabile') s = {'type': 'remote', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer {env:' + t + '}'}} if t else {})} elif spec.get('comando'): s = {'type': 'local', 'command': [str(spec['comando'])] + [str(a) for a in spec.get('argomenti') or []], **({'environment': {v: '{env:' + v + '}' for v in spec['variabili']}} if spec.get('variabili') else {})} else: continue server[f'{plugin}-{n}'] = s out: dict = {} if skill: out['skills'] = skill if comandi: out['commands'] = comandi if agenti: out['agents'] = agenti if server: out['mcp'] = {'servers': server} return out def _collegata_a(casa: str, nome: str, dove: str) -> bool: try: with open(os.path.join(casa, 'extensions', nome, '.qwen-extension-install.json'), encoding='utf-8') as h: d = json.load(h) except (OSError, ValueError): return False sorgente = os.path.realpath(d.get('source') or '') dove = os.path.realpath(dove) return d.get('type') == 'link' and (sorgente == dove or sorgente.startswith(dove + os.sep)) def codex(casa: str) -> int: try: _squadra_codex(casa) _squadra_plugin_codex(casa) except (OSError, subprocess.TimeoutExpired): pass return 0 def qwen(casa: str) -> int: try: _squadra_qwen(casa) _squadra_plugin_qwen(casa) except (OSError, subprocess.TimeoutExpired): pass return 0 def stacca(radice: str) -> int: d = cartella_squadre() for nome in sorted(os.listdir(d)) if os.path.isdir(d) else []: if nome.endswith('.plugin-installati.json') and _chiave_ok(nome.split('.', 1)[0]): chiave = nome.split('.', 1)[0] stato = _installati(chiave) miei = stato.pop('claude:' + radice, None) or {} for pid in miei: try: _claude('uninstall', pid, '--scope', 'local', cwd=radice) except (OSError, subprocess.TimeoutExpired): pass if miei: _installati_scrivi(chiave, stato) p = os.path.join(radice, '.claude', 'settings.local.json') try: with open(p, encoding='utf-8') as h: s = json.load(h) except (OSError, ValueError): return 0 cambiato = False for k in [k for k in s.get('enabledPlugins') or {} if k.split('@', 1)[-1].startswith(SQUADRA_MKT)]: del s['enabledPlugins'][k] cambiato = True if isinstance(s.get('enabledPlugins'), dict) and (not s['enabledPlugins']): del s['enabledPlugins'] mercati = s.get('extraKnownMarketplaces') for m in [m for m in mercati or {} if m.startswith(SQUADRA_MKT)] if isinstance(mercati, dict) else []: del mercati[m] cambiato = True if isinstance(mercati, dict) and (not mercati): del s['extraKnownMarketplaces'] if cambiato: with open(p + '.nuovo', 'w', encoding='utf-8') as h: h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n') os.replace(p + '.nuovo', p) return 0 def main(argv: list[str]) -> int: if argv == ['accetta']: return squadra_accetta_dal_terminale() if len(argv) == 3 and argv[0] == 'lancio': for x in squadra_lancio(argv[1], os.path.realpath(argv[2])): print(x) return 0 if len(argv) == 2 and argv[0] in ('codex', 'qwen', 'stacca'): return {'codex': codex, 'qwen': qwen, 'stacca': stacca}[argv[0]](os.path.realpath(argv[1])) print(F('uso'), file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))