Delminio — the client
Clonegit clone https://git.delminio.com/delminio-client2026.11.26-b027f1c · 26 Nov 2026

delminio-client / kit / it / squadra-client

raw · sha256 1dc58bdf011f3a57b9d5c9a4321e5201e81ff4af53fa64285a24b7ec48911bf0

1#!/usr/bin/env python3
2# © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE.
3"""La squadra di Delminio su questo computer (F810, F867): ciò che lo spazio dà a ogni suo"""
4from __future__ import annotations
5import hashlib
6import json
7import os
8import re
9import shlex
10import shutil
11import subprocess
12import sys
13NOME = 'delminio'
14FRASI = {
15    "uso": "uso: python3 .claude/squadra.py accetta \xb7 lancio <cli> <dove> \xb7 codex|qwen <cartella della CLI> \xb7 stacca <radice del repo>",
16    "squadra_descrizione": "Le skill della squadra, da Delminio",
17    "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] ",
18    "squadra_mcp_locale": "il comando che parte qui: {comando}\n  le variabili d'ambiente che riceve: {variabili}",
19    "squadra_mcp_remoto": "l'indirizzo che chiama: {url}\n  la variabile d'ambiente che gli manda come chiave: {variabile}",
20    "squadra_mcp_si": "s si s\xec y",
21    "squadra_mcp_accettati": "\u2705 server MCP e plugin della squadra: {nuovi} accettati ora \xb7 {restano} restano fermi (se uno cambia, lo richiedo)",
22    "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] "
23}
24
25def F(chiave: str, **valori) -> str:
26    testo = FRASI[chiave]
27    for k, v in valori.items():
28        testo = testo.replace('{' + k + '}', str(v))
29    return testo
30
31def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
32    return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
33
34def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
35    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)
36SQUADRA_MKT = NOME + '-squadra-'
37NOME_PLUGIN_OK = re.compile('[a-z0-9]+(?:-[a-z0-9]+)*')
38
39def cartella_squadre() -> str:
40    return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'squadre')
41
42def _chiave_ok(chiave: str) -> bool:
43    return bool(re.fullmatch('[0-9a-f]{12}', chiave or ''))
44
45def squadra_di(chiave: str) -> dict:
46    d = os.path.join(cartella_squadre(), chiave)
47    try:
48        with open(os.path.join(d, '.claude-plugin', 'marketplace.json'), encoding='utf-8') as h:
49            m = json.load(h)
50        p = m['plugins'][0]
51        with open(os.path.join(d, '.impronta'), encoding='utf-8') as h:
52            impronta = h.read().strip()
53    except (OSError, ValueError, KeyError, IndexError, TypeError):
54        return {}
55    if not _chiave_ok(chiave) or not NOME_PLUGIN_OK.fullmatch(str(p.get('name') or '')):
56        return {}
57    try:
58        with open(os.path.join(d, '.ruoli.json'), encoding='utf-8') as h:
59            di_chi = json.load(h)
60    except (OSError, ValueError):
61        di_chi = {}
62    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 {}}
63
64def _norm_ruolo(nome: str) -> str:
65    return ''.join((c for c in (nome or '').lower() if c.isalnum()))
66
67def _testa(testo: str) -> tuple[dict, str]:
68    m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
69    if not m:
70        return ({}, testo)
71    campi = {}
72    for riga in m.group(1).splitlines():
73        k, _, v = riga.partition(':')
74        v = v.strip()
75        if v[:1] == '"':
76            try:
77                v = json.loads(v)
78            except ValueError:
79                v = v.strip('"')
80        campi[k.strip()] = v
81    return (campi, testo[m.end():])
82
83def _col_nome(testo: str, nome: str) -> str:
84    m = re.match('^---[ \\t]*\\n(.*?)\\n---[ \\t]*(?:\\n|$)', testo, re.S)
85    if not m:
86        return f'---\nname: {nome}\n---\n' + testo
87    righe = [r for r in m.group(1).splitlines() if not re.match('name[ \\t]*:', r)]
88    return '---\n' + '\n'.join([f'name: {nome}', *righe]) + '\n---\n' + testo[m.end():]
89
90def _mcp_claude(spec: dict) -> dict:
91    if spec.get('tipo') == 'remoto':
92        t = spec.get('token_variabile')
93        return {'type': 'http', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
94    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 {})}
95
96def _mcp_qwen(spec: dict) -> dict:
97    if spec.get('tipo') == 'remoto':
98        t = spec.get('token_variabile')
99        return {'httpUrl': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
100    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 {})}
101_TESTA_AMMESSA = frozenset({'name', 'description', 'argument-hint', 'when_to_use', 'disable-model-invocation', 'user-invocable', 'model', 'color', 'tools', 'modelConfig', 'runConfig'})
102_CHIAVE_TESTA = re.compile('([A-Za-z_][\\w-]*)[ \\t]*:(?:[ \\t]|$)')
103
104def _testa_ripulita(testo: str) -> str:
105    m = re.match('^(\\ufeff?\\s*---[ \\t]*\\r?\\n)(.*?)(\\r?\\n---[ \\t]*(?:\\r?\\n|$))', testo, re.S)
106    if not m:
107        return testo
108    tenute, tieni = ([], False)
109    for riga in re.split('\\r\\n|\\r|\\n', m.group(2)):
110        if riga[:1] not in (' ', '\t'):
111            k = _CHIAVE_TESTA.match(riga)
112            tieni = bool(k) and k.group(1) in _TESTA_AMMESSA
113        if tieni:
114            tenute.append(riga)
115    return '---\n' + ''.join((r + '\n' for r in tenute)) + '---\n' + testo[m.end():]
116
117def _stampabile(v) -> bool:
118    if isinstance(v, str):
119        return v.isprintable()
120    if isinstance(v, dict):
121        return all((_stampabile(k) and _stampabile(x) for k, x in v.items()))
122    if isinstance(v, list):
123        return all((_stampabile(x) for x in v))
124    return True
125
126def _visibile(v) -> str:
127    return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
128
129def _mcp_impronta(nome: str, spec: dict) -> str:
130    return hashlib.sha256(json.dumps([nome, spec], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
131
132def _accettati_file(chiave: str) -> str:
133    return os.path.join(cartella_squadre(), chiave + '.mcp-accettati')
134
135def mcp_accettati(chiave: str) -> set[str]:
136    try:
137        with open(_accettati_file(chiave), encoding='utf-8') as h:
138            return set(h.read().split())
139    except OSError:
140        return set()
141
142def _squadra_contenuti(chiave: str, pacco: dict) -> dict[str, str]:
143    plugin = str(pacco.get('plugin') or 'squadra')
144    if not NOME_PLUGIN_OK.fullmatch(plugin):
145        plugin = 'squadra'
146    impronta = str(pacco.get('impronta') or '')
147    descrizione = F('squadra_descrizione')
148    mkt = SQUADRA_MKT + chiave
149    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)]
150    tutti, plugin_squadra = ([], [])
151    for x in pezzi:
152        tipo, nome = (str(x.get('tipo') or ''), str(x.get('nome') or ''))
153        if tipo == 'plugin' and NOME_PLUGIN_OK.fullmatch(nome) and (len(nome) <= 64):
154            if (spec := _plugin_spec((x.get('file') or {}).get('plugin.json'))):
155                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)})})
156            continue
157        if tipo not in ('skill', 'comando', 'agente', 'mcp') or not NOME_PLUGIN_OK.fullmatch(nome) or len(nome) > 64:
158            continue
159        file = {}
160        for rel, testo in (x.get('file') or {}).items():
161            pezzi_rel = str(rel).replace('\\', '/').split('/')
162            if isinstance(testo, str) and (not any((not q or q.startswith('.') for q in pezzi_rel))):
163                file[os.path.join(*pezzi_rel)] = testo
164        principale = {'skill': 'SKILL.md', 'comando': 'comando.md', 'agente': 'agente.md', 'mcp': 'mcp.json'}[tipo]
165        if principale not in file:
166            continue
167        if tipo != 'mcp':
168            file[principale] = _testa_ripulita(file[principale])
169        spec = {}
170        if tipo == 'mcp':
171            try:
172                spec = json.loads(file[principale])
173                spec = {k: v for k, v in spec.items() if k != 'descrizione'}
174                _mcp_claude(spec)
175            except (ValueError, KeyError, TypeError, AttributeError):
176                continue
177            if not _stampabile(spec):
178                continue
179        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)})})
180    accettati = mcp_accettati(chiave)
181    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]
182    via = {x['nome'] for x in fermi}
183    tutti = [x for x in tutti if not (x['tipo'] == 'mcp' and x['nome'] in via)]
184    dentro = sorted((_mcp_impronta(x['nome'], x['spec']) for x in tutti if x['tipo'] == 'mcp'))
185    minore = int(hashlib.sha256(' '.join(dentro).encode()).hexdigest()[:5], 16) + 1 if dentro else 0
186    versione = f"1.{minore}.{int((impronta or '0')[:7], 16)}"
187    f: dict[str, str] = {}
188    manifesto = {'name': plugin, 'version': versione, 'description': descrizione}
189
190    def un_plugin(dove: str, scelti) -> None:
191        mcp_claude, mcp_qwen = ({}, {})
192        for x in scelti:
193            n = x['nome']
194            if x['tipo'] == 'skill':
195                for rel, testo in x['file'].items():
196                    f[os.path.join(dove, 'skills', n, rel)] = testo
197            elif x['tipo'] == 'comando':
198                f[os.path.join(dove, 'commands', n + '.md')] = x['file']['comando.md']
199            elif x['tipo'] == 'agente':
200                f[os.path.join(dove, 'agents', n + '.md')] = x['file']['agente.md']
201            else:
202                mcp_claude[n] = _mcp_claude(x['spec'])
203                mcp_qwen[plugin + '-' + n] = _mcp_qwen(x['spec'])
204        f[os.path.join(dove, '.claude-plugin', 'plugin.json')] = json.dumps(manifesto, ensure_ascii=False, indent=2) + '\n'
205        if mcp_claude:
206            f[os.path.join(dove, '.mcp.json')] = json.dumps({'mcpServers': mcp_claude}, ensure_ascii=False, indent=2) + '\n'
207        f[os.path.join(dove, 'qwen-extension.json')] = json.dumps({**manifesto, **({'mcpServers': mcp_qwen} if mcp_qwen else {})}, ensure_ascii=False, indent=2) + '\n'
208    per_tutti = [x for x in tutti if not x['ruoli']]
209    un_plugin(plugin, per_tutti)
210    for r in sorted({r for x in tutti for r in x['ruoli']}):
211        un_plugin(os.path.join('ruoli', r, plugin), per_tutti + [x for x in tutti if r in x['ruoli']])
212    lancio = {'skill': {}, 'agente': {}, 'mcp': {}}
213    for x in tutti:
214        n = x['nome']
215        if x['tipo'] == 'skill':
216            for rel, testo in x['file'].items():
217                f[os.path.join('codex', plugin, 'skills', n, rel)] = testo
218            lancio['skill'][n] = x['ruoli']
219            if len(plugin) + 1 + len(n) <= 64:
220                for rel, testo in x['file'].items():
221                    f[os.path.join('opencode', 'skills', f'{plugin}-{n}', rel)] = _col_nome(testo, f'{plugin}-{n}') if rel == 'SKILL.md' else testo
222        elif x['tipo'] == 'comando':
223            campi, corpo = _testa(x['file']['comando.md'])
224            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')
225            lancio['skill'][n] = x['ruoli']
226        elif x['tipo'] == 'agente':
227            campi, corpo = _testa(x['file']['agente.md'])
228            f[os.path.join('codex', 'agenti', n + '.toml')] = f'name = {json.dumps(n)}\ndeveloper_instructions = {json.dumps(corpo.strip(), ensure_ascii=False)}\n'
229            lancio['agente'][n] = {'ruoli': x['ruoli'], 'descrizione': str(campi.get('description') or '')}
230        else:
231            lancio['mcp'][n] = {'ruoli': x['ruoli'], 'spec': x['spec']}
232    f[os.path.join('codex', plugin, '.codex-plugin', 'plugin.json')] = json.dumps({**manifesto, 'skills': './skills/'}, ensure_ascii=False, indent=2) + '\n'
233    lancio['conto'] = {t: sum((1 for x in tutti if x['tipo'] == t)) for t in ('skill', 'comando', 'agente', 'mcp')}
234    lancio['conto']['mcp_fermi'] = len(fermi)
235    f['.ruoli.json'] = json.dumps(lancio, indent=2, sort_keys=True, ensure_ascii=False) + '\n'
236    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'
237    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'
238    f['.impronta'] = impronta + '\n'
239    f['.pacco.json'] = json.dumps(pacco, ensure_ascii=False, sort_keys=True) + '\n'
240    if fermi:
241        f['.mcp-fermi.json'] = json.dumps(fermi, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
242    if plugin_squadra:
243        presi = plugin_accettati(chiave)
244        for x in plugin_squadra:
245            x['accettato'] = x['impronta'] in presi
246        f['.plugin.json'] = json.dumps(plugin_squadra, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
247        if (fermi_p := [x for x in plugin_squadra if not x['accettato']]):
248            f['.plugin-fermi.json'] = json.dumps(fermi_p, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
249    return f
250
251def squadra_accetta_dal_terminale() -> int:
252    radice = cartella_squadre()
253    try:
254        chiavi = sorted((c for c in os.listdir(radice) if _chiave_ok(c)))
255    except OSError:
256        return 0
257    try:
258        tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
259    except OSError:
260        return 1
261    nuovi = restano = 0
262    for chiave in chiavi:
263        d = os.path.join(radice, chiave)
264        try:
265            with open(os.path.join(d, '.pacco.json'), encoding='utf-8') as h:
266                pacco = json.load(h)
267        except (OSError, ValueError):
268            continue
269        try:
270            with open(os.path.join(d, '.mcp-fermi.json'), encoding='utf-8') as h:
271                fermi = json.load(h)
272        except (OSError, ValueError):
273            fermi = []
274        accettati, presi = (mcp_accettati(chiave), 0)
275        for x in fermi if isinstance(fermi, list) else []:
276            spec, nome = (x.get('spec') or {}, str(x.get('nome') or ''))
277            if not isinstance(spec, dict) or not _stampabile(spec):
278                restano += 1
279                continue
280            if spec.get('tipo') == 'remoto':
281                cosa = F('squadra_mcp_remoto', url=_visibile(spec.get('url') or ''), variabile=_visibile(spec.get('token_variabile') or '—'))
282            else:
283                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 '—'))
284            tty.write(F('squadra_mcp_domanda', nome=_visibile(nome), cosa=cosa))
285            tty.flush()
286            if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
287                accettati.add(_mcp_impronta(nome, spec))
288                presi += 1
289            else:
290                restano += 1
291        try:
292            with open(os.path.join(d, '.plugin-fermi.json'), encoding='utf-8') as h:
293                plugin_fermi = json.load(h)
294        except (OSError, ValueError):
295            plugin_fermi = []
296        presi_p, plugin_presi = (0, plugin_accettati(chiave))
297        for x in plugin_fermi if isinstance(plugin_fermi, list) else []:
298            spec, nome = (_plugin_spec(json.dumps((x or {}).get('spec'))), str((x or {}).get('nome') or ''))
299            if not spec or not NOME_PLUGIN_OK.fullmatch(nome):
300                restano += 1
301                continue
302            tty.write(F('squadra_plugin_domanda', nome=_visibile(nome), mercato=_visibile(spec['mercato']), origine=_visibile(spec['origine']), cli=', '.join(spec['cli'])))
303            tty.flush()
304            if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
305                plugin_presi.add(_mcp_impronta(nome, spec))
306                presi_p += 1
307            else:
308                restano += 1
309        if presi_p:
310            os.makedirs(radice, exist_ok=True)
311            with open(_plugin_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
312                h.write(''.join((i + '\n' for i in sorted(plugin_presi))))
313            os.replace(_plugin_accettati_file(chiave) + '.nuovo', _plugin_accettati_file(chiave))
314            presi += presi_p
315        if presi:
316            os.makedirs(radice, exist_ok=True)
317            with open(_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
318                h.write(''.join((i + '\n' for i in sorted(accettati))))
319            os.replace(_accettati_file(chiave) + '.nuovo', _accettati_file(chiave))
320            squadra_scrivi(chiave, pacco)
321            nuovi += presi
322    if nuovi or restano:
323        print(F('squadra_mcp_accettati', nuovi=nuovi, restano=restano))
324    return 0
325
326def squadra_scrivi(chiave: str, pacco: dict) -> dict:
327    if not _chiave_ok(chiave):
328        return {}
329    d = os.path.join(cartella_squadre(), chiave)
330    if not (pacco.get('pezzi') or pacco.get('skill')):
331        shutil.rmtree(d, ignore_errors=True)
332        return {}
333    voluti = _squadra_contenuti(chiave, pacco)
334    for rel, testo in voluti.items():
335        p = os.path.join(d, rel)
336        try:
337            with open(p, encoding='utf-8') as h:
338                if h.read() == testo:
339                    continue
340        except (OSError, UnicodeDecodeError):
341            pass
342        os.makedirs(os.path.dirname(p), exist_ok=True)
343        with open(p + '.nuovo', 'w', encoding='utf-8') as h:
344            h.write(testo)
345        os.replace(p + '.nuovo', p)
346    for radice, cartelle, nomi in os.walk(d, topdown=False):
347        for n in nomi:
348            rel = os.path.relpath(os.path.join(radice, n), d)
349            if rel not in voluti:
350                os.remove(os.path.join(radice, n))
351        if radice != d and (not os.listdir(radice)):
352            os.rmdir(radice)
353    return squadra_di(chiave)
354
355def _squadra_id(sq: dict) -> str:
356    return f"{sq['plugin']}@{sq['marketplace']}"
357
358def squadra_claude(radice: str, chiave: str) -> int:
359    p = os.path.join(radice, '.claude', 'settings.local.json')
360    try:
361        with open(p, encoding='utf-8') as h:
362            s = json.load(h)
363    except (OSError, ValueError):
364        s = {}
365    accesi = s.get('enabledPlugins') if isinstance(s.get('enabledPlugins'), dict) else {}
366    mkt = SQUADRA_MKT + chiave
367    sq = squadra_di(chiave)
368    voluto = _squadra_id(sq) if sq else ''
369    vecchi = [k for k in accesi if k.endswith('@' + mkt) and k != voluto]
370    if (not voluto or accesi.get(voluto) is True) and (not vecchi):
371        return 0
372    if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
373        return 3
374    try:
375        for k in vecchi:
376            _claude('uninstall', k, '--scope', 'local', cwd=radice)
377        if voluto:
378            _claude('marketplace', 'add', sq['cartella'], '--scope', 'local', cwd=radice)
379            _claude('install', voluto, '--scope', 'local', cwd=radice)
380        else:
381            _claude('marketplace', 'remove', mkt, '--scope', 'local', cwd=radice)
382    except (OSError, subprocess.TimeoutExpired):
383        return 3
384    return 0
385
386def _squadra_codex(casa: str) -> None:
387    chiave = os.path.basename(os.path.normpath(casa))
388    if not _chiave_ok(chiave):
389        return
390    sq = squadra_di(chiave)
391    try:
392        with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
393            conf = h.read()
394    except OSError:
395        conf = ''
396    mkt = SQUADRA_MKT + chiave
397    if not sq:
398        for m in re.finditer('^\\[plugins\\."([a-z0-9-]+@' + re.escape(mkt) + ')"\\]', conf, re.M):
399            _codex(casa, 'remove', m.group(1))
400        if mkt in conf:
401            _codex(casa, 'marketplace', 'remove', mkt)
402        return
403    pid = _squadra_id(sq)
404    acceso = re.search('^\\[plugins\\."' + re.escape(pid) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
405    if acceso and os.path.isdir(os.path.join(casa, 'plugins', 'cache', mkt, sq['plugin'], sq['versione'])):
406        return
407    _codex(casa, 'marketplace', 'add', sq['cartella'])
408    _codex(casa, 'add', pid)
409
410def _squadra_qwen(casa: str) -> None:
411    chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
412    if not _chiave_ok(chiave):
413        return
414    sq = squadra_di(chiave)
415    q = os.environ.get('DELMINIO_QWEN') or 'qwen'
416    ambiente = {**os.environ, 'QWEN_HOME': casa}
417    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'])]
418    for n in via:
419        subprocess.run([q, 'extensions', 'uninstall', n], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
420    if not sq:
421        return
422    del_ruolo = os.path.join(sq['cartella'], 'ruoli', _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')), sq['plugin'])
423    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'])
424    if _collegata_a(casa, sq['plugin'], estensione):
425        return
426    subprocess.run([q, 'extensions', 'uninstall', sq['plugin']], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
427    subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
428_PLUGIN_ORIGINE = re.compile('(github:[A-Za-z0-9][\\w.-]*/[\\w.-]+|https://[^\\s@?#]{3,300})')
429
430def _plugin_spec(testo) -> dict:
431    try:
432        d = json.loads(testo) if isinstance(testo, str) else {}
433    except ValueError:
434        return {}
435    if not isinstance(d, dict):
436        return {}
437    mercato, origine = (str(d.get('mercato') or ''), str(d.get('origine') or ''))
438    cli = [c for c in ('claude', 'codex', 'qwen') if c in (d.get('cli') or [])]
439    if not re.fullmatch('[\\w.-]{1,100}', mercato) or not _PLUGIN_ORIGINE.fullmatch(origine) or (not cli) or (not _stampabile({'m': mercato, 'o': origine})):
440        return {}
441    return {'mercato': mercato, 'origine': origine, 'cli': cli}
442
443def _plugin_accettati_file(chiave: str) -> str:
444    return os.path.join(cartella_squadre(), chiave + '.plugin-accettati')
445
446def plugin_accettati(chiave: str) -> set[str]:
447    try:
448        with open(_plugin_accettati_file(chiave), encoding='utf-8') as h:
449            return set(h.read().split())
450    except OSError:
451        return set()
452
453def plugin_squadra(chiave: str, cli: str) -> list[dict]:
454    try:
455        with open(os.path.join(cartella_squadre(), chiave, '.plugin.json'), encoding='utf-8') as h:
456            tutti = json.load(h)
457    except (OSError, ValueError):
458        return []
459    presi = plugin_accettati(chiave)
460    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')))]
461
462def _installati(chiave: str) -> dict:
463    try:
464        with open(os.path.join(cartella_squadre(), chiave + '.plugin-installati.json'), encoding='utf-8') as h:
465            d = json.load(h)
466        return d if isinstance(d, dict) else {}
467    except (OSError, ValueError):
468        return {}
469
470def _installati_scrivi(chiave: str, d: dict) -> None:
471    p = os.path.join(cartella_squadre(), chiave + '.plugin-installati.json')
472    os.makedirs(os.path.dirname(p), exist_ok=True)
473    with open(p + '.nuovo', 'w', encoding='utf-8') as h:
474        json.dump(d, h, indent=2, sort_keys=True)
475    os.replace(p + '.nuovo', p)
476
477def _sorgente(origine: str, cli: str) -> str:
478    if origine.startswith('github:'):
479        return origine[7:] if cli != 'qwen' else 'https://github.com/' + origine[7:]
480    return origine
481
482def _claude_installati(radice: str) -> dict:
483    cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
484    try:
485        with open(os.path.join(cfg, 'plugins', 'installed_plugins.json'), encoding='utf-8') as h:
486            d = json.load(h).get('plugins') or {}
487    except (OSError, ValueError, AttributeError):
488        return {}
489    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)}
490
491def squadra_plugin_claude(radice: str, chiave: str) -> int:
492    if not radice or not _chiave_ok(chiave) or (not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude')):
493        return 3
494    voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'claude')}
495    stato = _installati(chiave)
496    miei = stato.get('claude:' + radice) or {}
497    c_e = _claude_installati(radice)
498    try:
499        with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
500            accesi = json.load(h).get('enabledPlugins') or {}
501    except (OSError, ValueError, AttributeError):
502        accesi = {}
503    for pid, x in voluti.items():
504        if pid not in c_e:
505            _claude('marketplace', 'add', _sorgente(x['spec']['origine'], 'claude'), '--scope', 'local', cwd=radice)
506            if _claude('install', pid, '--scope', 'local', cwd=radice).returncode != 0:
507                continue
508            miei[pid] = True
509        elif pid not in miei:
510            continue
511        per_tutti = not x['ruoli']
512        if per_tutti and accesi.get(pid) is not True:
513            _claude('enable', pid, '--scope', 'local', cwd=radice)
514        elif not per_tutti and accesi.get(pid) is not False:
515            _claude('disable', pid, '--scope', 'local', cwd=radice)
516    for pid in [k for k in miei if k not in voluti]:
517        _claude('uninstall', pid, '--scope', 'local', cwd=radice)
518        miei.pop(pid)
519    stato['claude:' + radice] = miei
520    _installati_scrivi(chiave, stato)
521    return 0
522
523def _squadra_plugin_codex(casa: str) -> None:
524    chiave = os.path.basename(os.path.normpath(casa))
525    if not _chiave_ok(chiave):
526        return
527    voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'codex') if not x['ruoli']}
528    stato = _installati(chiave)
529    miei = stato.get('codex:' + casa) or {}
530    try:
531        with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
532            conf = h.read()
533    except OSError:
534        conf = ''
535    for pid, x in voluti.items():
536        if f'[plugins."{pid}"]' in conf:
537            continue
538        if f"[marketplaces.{x['spec']['mercato']}]" not in conf:
539            _codex(casa, 'marketplace', 'add', _sorgente(x['spec']['origine'], 'codex'))
540        if _codex(casa, 'add', pid).returncode == 0:
541            miei[pid] = True
542    for pid in [k for k in miei if k not in voluti]:
543        _codex(casa, 'remove', pid)
544        miei.pop(pid)
545    stato['codex:' + casa] = miei
546    _installati_scrivi(chiave, stato)
547
548def _squadra_plugin_qwen(casa: str) -> None:
549    chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
550    if not _chiave_ok(chiave):
551        return
552    ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
553    voluti = {x['nome']: x for x in plugin_squadra(chiave, 'qwen') if not x['ruoli'] or ruolo in x['ruoli']}
554    stato = _installati(chiave)
555    miei = stato.get('qwen:' + casa) or {}
556    q = os.environ.get('DELMINIO_QWEN') or 'qwen'
557    ambiente = {**os.environ, 'QWEN_HOME': casa}
558    for nome, x in voluti.items():
559        if os.path.isdir(os.path.join(casa, 'extensions', nome)):
560            continue
561        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)
562        if r.returncode == 0:
563            miei[nome] = True
564    for nome in [k for k in miei if k not in voluti]:
565        subprocess.run([q, 'extensions', 'uninstall', nome], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
566        miei.pop(nome)
567    stato['qwen:' + casa] = miei
568    _installati_scrivi(chiave, stato)
569
570def squadra_lancio(cli: str, dove: str) -> list[str]:
571    ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
572    if cli == 'claude':
573        try:
574            with open(os.path.join(dove, '.claude', 'settings.local.json'), encoding='utf-8') as h:
575                accesi = json.load(h).get('enabledPlugins') or {}
576        except (OSError, ValueError, AttributeError):
577            return []
578        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]
579        sq = squadra_di(chiavi[0]) if chiavi else {}
580        d = os.path.join(sq['cartella'], 'ruoli', ruolo, sq['plugin']) if sq and ruolo else ''
581        out = ['--plugin-dir', d] if d and os.path.isdir(d) else []
582        if chiavi and ruolo:
583            c_e = _claude_installati(dove)
584            for x in plugin_squadra(chiavi[0], 'claude'):
585                cartella = c_e.get(f"{x['nome']}@{x['spec']['mercato']}", '')
586                if ruolo in x['ruoli'] and cartella and os.path.isdir(cartella):
587                    out += ['--plugin-dir', cartella]
588        return out
589    if cli == 'codex':
590        chiave = os.path.basename(os.path.normpath(dove))
591        sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
592        if not sq:
593            return []
594        lancio = sq['ruoli']
595        per_me = lambda r: not r or ruolo in r
596        out = []
597        base = os.path.join(dove, 'plugins', 'cache', sq['marketplace'], sq['plugin'], sq['versione'], 'skills')
598        via = [n for n, r in sorted((lancio.get('skill') or {}).items()) if not per_me(r) and NOME_PLUGIN_OK.fullmatch(n)]
599        if via:
600            voci = ','.join(('{path=' + json.dumps(os.path.join(base, n, 'SKILL.md')) + ',enabled=false}' for n in via))
601            out += ['-c', f'skills.config=[{voci}]']
602        for n, a in sorted((lancio.get('agente') or {}).items()):
603            toml = os.path.join(sq['cartella'], 'codex', 'agenti', n + '.toml')
604            if NOME_PLUGIN_OK.fullmatch(n) and per_me(a.get('ruoli')) and os.path.isfile(toml):
605                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)}']
606        for n, m in sorted((lancio.get('mcp') or {}).items()):
607            spec, k = (m.get('spec') or {}, f"{sq['plugin']}-{n}")
608            if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
609                continue
610            if spec.get('tipo') == 'remoto' and spec.get('url'):
611                out += ['-c', f"mcp_servers.{k}.url={json.dumps(spec['url'])}"]
612                if spec.get('token_variabile'):
613                    out += ['-c', f"mcp_servers.{k}.bearer_token_env_var={json.dumps(spec['token_variabile'])}"]
614            elif spec.get('comando'):
615                out += ['-c', f"mcp_servers.{k}.command={json.dumps(spec['comando'])}", '-c', f"mcp_servers.{k}.args={json.dumps(list(spec.get('argomenti') or []))}"]
616                if spec.get('variabili'):
617                    out += ['-c', f"mcp_servers.{k}.env_vars={json.dumps(list(spec['variabili']))}"]
618        return out
619    if cli == 'opencode':
620        return [json.dumps(_squadra_opencode(ruolo), ensure_ascii=False)]
621    return []
622
623def _squadra_opencode(ruolo: str) -> dict:
624    chiave = os.environ.get('DELMINIO_SQUADRA', '')
625    sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
626    if not sq:
627        return {}
628    lancio, plugin = (sq['ruoli'], sq['plugin'])
629    per_me = lambda r: not r or ruolo in r
630    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'))]
631    del_ruolo = os.path.join(sq['cartella'], 'ruoli', ruolo, plugin)
632    base = del_ruolo if ruolo and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], plugin)
633    comandi, agenti = ({}, {})
634    for cartella, dove in (('commands', comandi), ('agents', agenti)):
635        try:
636            nomi = sorted(os.listdir(os.path.join(base, cartella)))
637        except OSError:
638            nomi = []
639        for x in nomi:
640            n = x[:-3] if x.endswith('.md') else ''
641            if not NOME_PLUGIN_OK.fullmatch(n):
642                continue
643            try:
644                with open(os.path.join(base, cartella, x), encoding='utf-8') as h:
645                    campi, corpo = _testa(h.read())
646            except OSError:
647                continue
648            descrizione = str(campi.get('description') or n)
649            if cartella == 'commands':
650                dove[f'{plugin}:{n}'] = {'template': corpo.strip() or '$ARGUMENTS', 'description': descrizione}
651            else:
652                dove[f'{plugin}-{n}'] = {'mode': 'subagent', 'description': descrizione, 'system': corpo.strip()}
653    server = {}
654    for n, m in sorted((lancio.get('mcp') or {}).items()):
655        spec = m.get('spec') or {}
656        if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
657            continue
658        if spec.get('tipo') == 'remoto' and spec.get('url'):
659            t = spec.get('token_variabile')
660            s = {'type': 'remote', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer {env:' + t + '}'}} if t else {})}
661        elif spec.get('comando'):
662            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 {})}
663        else:
664            continue
665        server[f'{plugin}-{n}'] = s
666    out: dict = {}
667    if skill:
668        out['skills'] = skill
669    if comandi:
670        out['commands'] = comandi
671    if agenti:
672        out['agents'] = agenti
673    if server:
674        out['mcp'] = {'servers': server}
675    return out
676
677def _collegata_a(casa: str, nome: str, dove: str) -> bool:
678    try:
679        with open(os.path.join(casa, 'extensions', nome, '.qwen-extension-install.json'), encoding='utf-8') as h:
680            d = json.load(h)
681    except (OSError, ValueError):
682        return False
683    sorgente = os.path.realpath(d.get('source') or '')
684    dove = os.path.realpath(dove)
685    return d.get('type') == 'link' and (sorgente == dove or sorgente.startswith(dove + os.sep))
686
687def codex(casa: str) -> int:
688    try:
689        _squadra_codex(casa)
690        _squadra_plugin_codex(casa)
691    except (OSError, subprocess.TimeoutExpired):
692        pass
693    return 0
694
695def qwen(casa: str) -> int:
696    try:
697        _squadra_qwen(casa)
698        _squadra_plugin_qwen(casa)
699    except (OSError, subprocess.TimeoutExpired):
700        pass
701    return 0
702
703def stacca(radice: str) -> int:
704    d = cartella_squadre()
705    for nome in sorted(os.listdir(d)) if os.path.isdir(d) else []:
706        if nome.endswith('.plugin-installati.json') and _chiave_ok(nome.split('.', 1)[0]):
707            chiave = nome.split('.', 1)[0]
708            stato = _installati(chiave)
709            miei = stato.pop('claude:' + radice, None) or {}
710            for pid in miei:
711                try:
712                    _claude('uninstall', pid, '--scope', 'local', cwd=radice)
713                except (OSError, subprocess.TimeoutExpired):
714                    pass
715            if miei:
716                _installati_scrivi(chiave, stato)
717    p = os.path.join(radice, '.claude', 'settings.local.json')
718    try:
719        with open(p, encoding='utf-8') as h:
720            s = json.load(h)
721    except (OSError, ValueError):
722        return 0
723    cambiato = False
724    for k in [k for k in s.get('enabledPlugins') or {} if k.split('@', 1)[-1].startswith(SQUADRA_MKT)]:
725        del s['enabledPlugins'][k]
726        cambiato = True
727    if isinstance(s.get('enabledPlugins'), dict) and (not s['enabledPlugins']):
728        del s['enabledPlugins']
729    mercati = s.get('extraKnownMarketplaces')
730    for m in [m for m in mercati or {} if m.startswith(SQUADRA_MKT)] if isinstance(mercati, dict) else []:
731        del mercati[m]
732        cambiato = True
733    if isinstance(mercati, dict) and (not mercati):
734        del s['extraKnownMarketplaces']
735    if cambiato:
736        with open(p + '.nuovo', 'w', encoding='utf-8') as h:
737            h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
738        os.replace(p + '.nuovo', p)
739    return 0
740
741def main(argv: list[str]) -> int:
742    if argv == ['accetta']:
743        return squadra_accetta_dal_terminale()
744    if len(argv) == 3 and argv[0] == 'lancio':
745        for x in squadra_lancio(argv[1], os.path.realpath(argv[2])):
746            print(x)
747        return 0
748    if len(argv) == 2 and argv[0] in ('codex', 'qwen', 'stacca'):
749        return {'codex': codex, 'qwen': qwen, 'stacca': stacca}[argv[0]](os.path.realpath(argv[1]))
750    print(F('uso'), file=sys.stderr)
751    return 1
752if __name__ == '__main__':
753    sys.exit(main(sys.argv[1:]))