#!/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. """I token di una conversazione, letti dalla CLI e mai il testo (F868).""" import glob, json, os, re, sys POSTA = re.compile('^ \\S+ → \\S+ \\d\\d:\\d\\d UTC$', re.M) stato_f = sys.argv[1] try: e = json.load(sys.stdin) p = e.get('transcript_path') or '' dim = os.path.getsize(p) except Exception: sys.exit(0) try: st = json.load(open(stato_f)) except Exception: st = {} oc = e.get('cli') == 'opencode' sid_oc = str(e.get('session_id') or '') chiave = p + '#' + sid_oc if oc else p if st.get('p') != chiave or (not oc and st.get('off', 0) > dim): st = {'p': chiave, 'off': 0, 'cli': '', 'mod': '', 't': {}, 'id': '', 'u': {}, 'n': 0} t = st['t'] def oc_testo(x): if isinstance(x, str): return x if isinstance(x, list): return ''.join((oc_testo(b) for b in x)) if isinstance(x, dict): return str(x.get('text') or x.get('output') or '') return '' def oc_risposta(mid, modello, tok, blocchi, risultati): tok = tok or {} cache = tok.get('cache') or {} u = {'input_tokens': int(tok.get('input') or 0), 'cache_read_input_tokens': int(cache.get('read') or 0), 'cache_creation_input_tokens': int(cache.get('write') or 0), 'output_tokens': int(tok.get('output') or 0) + int(tok.get('reasoning') or 0)} out = [{'type': 'assistant', 'message': {'id': mid, 'model': modello, 'usage': u, 'content': blocchi}}] if risultati: out.append({'type': 'user', 'message': {'content': risultati}}) return out def oc_umano(parti): out = [] for x in parti: if x.get('type') != 'text' or not x.get('text'): continue if x.get('synthetic'): out.append({'type': 'attachment', 'attachment': {'type': 'hook_additional_context', 'hookEvent': 'opencode', 'content': x['text']}}) else: out.append({'type': 'user', 'message': {'content': [{'type': 'text', 'text': x['text']}]}}) return out def oc_righe(db, sid, dopo): import sqlite3 righe, fino = ([], list(dopo or [0, ''])) try: c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2) except sqlite3.Error: return (righe, fino) try: tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')} dove = 'session_id=? and (time_created>? or (time_created=? and id>?)) order by time_created, id' arg = (sid, fino[0], fino[0], fino[1]) if 'session_message' in tabelle: for mid, tc, tipo, d in c.execute('select id, time_created, type, data from session_message where ' + dove, arg).fetchall(): m = json.loads(d) if tipo == 'assistant': if not (m.get('time') or {}).get('completed'): break mod = m.get('model') or {} modello = (str(mod.get('providerID') or '') + '/' + str(mod.get('id') or '')).strip('/') blocchi, ris = ([], []) for x in m.get('content') or []: k = x.get('type') if k == 'tool': s = x.get('state') or {} blocchi.append({'type': 'tool_use', 'id': x.get('id'), 'name': x.get('name'), 'input': s.get('input') or {}}) if s.get('status') in ('completed', 'error'): ris.append({'type': 'tool_result', 'tool_use_id': x.get('id'), 'content': oc_testo(s.get('content') or s.get('error') or '')}) elif k == 'text': blocchi.append({'type': 'text', 'text': x.get('text') or ''}) elif k == 'reasoning': blocchi.append({'type': 'thinking', 'thinking': oc_testo(x.get('text') or x.get('content'))}) righe += oc_risposta(mid, modello, m.get('tokens'), blocchi, ris) elif tipo == 'user': righe += oc_umano([{'type': 'text', 'text': m.get('text') or ''}]) elif (tx := oc_testo(m.get('text') or m.get('content'))): righe += oc_umano([{'type': 'text', 'text': tx, 'synthetic': True}]) fino = [tc, mid] except (sqlite3.Error, ValueError): pass finally: c.close() return (righe, fino) def oc_figlie(db, sid): import sqlite3 try: c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2) except sqlite3.Error: return [] try: tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')} figli = {} for tab in ('session', 'session_v2'): if tab in tabelle: for i, padre in c.execute('select id, parent_id from ' + tab + ' where parent_id is not null'): figli.setdefault(padre, []).append(i) except sqlite3.Error: return [] finally: c.close() out, coda = ([], [sid]) while coda: for i in figli.get(coda.pop(), []): if i not in out: out.append(i) coda.append(i) return out def somma(d): for k, v in d.items(): t[k] = t.get(k, 0) + int(v or 0) import re _CAR_PER_TOKEN = 3.2 _FONTI_MAX = 64 _COMANDO_DELMINIO = re.compile('(?:^|[\\s;&|(\\"\\x27])delminio\\s+[a-z]|delminio\\.sh\\b') def _fonti_lungo(x): if isinstance(x, str): return len(x) if isinstance(x, list): return sum((6000 if isinstance(b, dict) and b.get('type') == 'image' else _fonti_lungo(b) for b in x)) if isinstance(x, dict) and x.get('type') == 'text': return len(x.get('text') or '') return len(json.dumps(x, ensure_ascii=False)) def _fonti_tool(nome, argomenti): nome = str(nome or '?') if 'delminio' in nome.lower(): op = argomenti.get('operation') if isinstance(argomenti, dict) else None return 'delminio:' + str(op or nome.rsplit('__', 1)[-1])[:30] testo = argomenti if isinstance(argomenti, str) else json.dumps(argomenti, ensure_ascii=False) if nome in ('Bash', 'bash', 'exec_command', 'shell', 'exec', 'run_shell_command') or 'shell' in nome.lower(): return 'delminio:comando' if _COMANDO_DELMINIO.search(testo or '') else 'comando' if nome.startswith('mcp__'): return 'mcp:' + nome.split('__')[1][:30] return 'tool:' + nome[:30] def fonti_nuovo(): return {'E': {}, 'R': {}, 'G': {}, 'pend': [], 'dopo': [], 'tid': {}, 'prev': 0, 'n': 0, 'ultimo': None} def _fonti_pezzo(a, fonte, car): if car > 0: a['pend'].append([fonte, int(car)]) def _fonti_risposta(a, ctx, pezzi): E = a['E'] if a['n'] == 0: stima = {} for f, c in pezzi: stima[f] = stima.get(f, 0) + c / _CAR_PER_TOKEN tot = sum(stima.values()) scala = min(1.0, ctx / tot) if tot else 0 for f, v in stima.items(): E[f] = E.get(f, 0) + v * scala E['sistema'] = E.get('sistema', 0) + max(0, ctx - tot * scala) elif ctx < a['prev']: scala = ctx / a['prev'] for f in E: E[f] *= scala else: delta = ctx - a['prev'] car = sum((c for _, c in pezzi)) if not car: E['altro'] = E.get('altro', 0) + delta for f, c in pezzi: E[f] = E.get(f, 0) + delta * c / car if car else E.get(f, 0) for f, v in E.items(): a['R'][f] = a['R'].get(f, 0) + v motori = sorted({f for f, _ in pezzi if f.split(':')[0] in ('delminio', 'comando', 'tool', 'mcp')}) if not motori: motori = ['persona'] if any((f == 'persona' for f, _ in pezzi)) else ['altro'] for f in motori: a['G'][f] = a['G'].get(f, 0) + ctx / len(motori) a['prev'] = ctx a['n'] += 1 def fonti_riga(a, d): t = d.get('type') pl = d.get('payload') if isinstance(d.get('payload'), dict) else {} if t == 'attachment' and isinstance(d.get('attachment'), dict): at = d['attachment'] k = str(at.get('type') or '') if k == 'hook_additional_context': _fonti_pezzo(a, 'gancio:' + str(at.get('hookEvent') or '?')[:30], _fonti_lungo(at.get('content') or '')) elif k not in ('hook_success', 'prompt_snapshot', ''): _fonti_pezzo(a, 'cli:' + k[:40], _fonti_lungo({x: y for x, y in at.items() if x != 'type'})) return if t == 'user' and isinstance(d.get('message'), dict) and (not d.get('isSidechain')): c = d['message'].get('content') if isinstance(c, str): _fonti_pezzo(a, 'cli:meta' if d.get('isMeta') else 'persona', len(c)) return for b in c if isinstance(c, list) else []: if not isinstance(b, dict): continue if b.get('type') == 'tool_result': _fonti_pezzo(a, a['tid'].pop(b.get('tool_use_id'), 'tool:?'), _fonti_lungo(b.get('content') or '')) elif b.get('type') == 'text': x = b.get('text') or '' f = 'gancio:posta' if POSTA.search(x) else 'cli:promemoria' if '' in x or d.get('isMeta') else 'persona' _fonti_pezzo(a, f, len(x)) elif b.get('type') == 'image': _fonti_pezzo(a, 'persona', 6000) return if t == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict) and (not d.get('isSidechain')): m = d['message'] if m.get('id') != a['ultimo']: u = m['usage'] a['ultimo'] = m.get('id') _fonti_risposta(a, int(u.get('input_tokens') or 0) + int(u.get('cache_read_input_tokens') or 0) + int(u.get('cache_creation_input_tokens') or 0), a['pend']) a['pend'] = [] for b in m.get('content') or []: if not isinstance(b, dict): continue if b.get('type') == 'tool_use': a['tid'][b.get('id')] = _fonti_tool(b.get('name'), b.get('input') or {}) _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(b.get('input') or {})) elif b.get('type') == 'thinking': _fonti_pezzo(a, 'modello:pensiero', len(b.get('thinking') or '') or len(b.get('signature') or '') // 2) elif b.get('type') == 'text': _fonti_pezzo(a, 'modello:testo', len(b.get('text') or '')) return if t == 'assistant' and isinstance(d.get('usageMetadata'), dict): _fonti_risposta(a, int(d['usageMetadata'].get('promptTokenCount') or 0), a['pend']) a['pend'] = [] for p in (d.get('message') or {}).get('parts') or []: if not isinstance(p, dict): continue if isinstance(p.get('functionCall'), dict): fc = p['functionCall'] a['tid'][fc.get('id') or fc.get('name')] = _fonti_tool(fc.get('name'), fc.get('args') or {}) _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(fc.get('args') or {})) elif p.get('text'): _fonti_pezzo(a, 'modello:pensiero' if p.get('thought') else 'modello:testo', len(p['text'])) return if t == 'tool_result': for p in (d.get('message') or {}).get('parts') or []: fr = p.get('functionResponse') if isinstance(p, dict) else None if isinstance(fr, dict): f = a['tid'].pop(fr.get('id'), None) or a['tid'].pop(fr.get('name'), None) or _fonti_tool(fr.get('name'), {}) _fonti_pezzo(a, f, _fonti_lungo(fr.get('response') or '')) return if t == 'user' and isinstance(d.get('message'), dict): for p in d['message'].get('parts') or []: if isinstance(p, dict) and p.get('text'): _fonti_pezzo(a, 'cli:avviso' if d.get('subtype') else 'persona', len(p['text'])) return if t == 'session_meta': _fonti_pezzo(a, 'sistema', _fonti_lungo(pl.get('base_instructions') or '')) elif t == 'response_item': k = pl.get('type') if k == 'message': car = _fonti_lungo(pl.get('content') or []) if pl.get('role') == 'assistant': a['dopo'].append(['modello:testo', car]) else: testo = json.dumps(pl.get('content') or [], ensure_ascii=False) f = 'persona' if pl.get('role') == 'user' and '' not in testo and ('AGENTS.md' not in testo) else 'cli:istruzioni' _fonti_pezzo(a, f, car) elif k == 'reasoning': a['dopo'].append(['modello:pensiero', len(pl.get('encrypted_content') or '') // 3 or _fonti_lungo(pl.get('summary') or [])]) elif k in ('function_call', 'custom_tool_call', 'local_shell_call'): arg = pl.get('arguments') or pl.get('input') or pl.get('action') or {} if isinstance(arg, str): try: arg = json.loads(arg) except ValueError: pass a['tid'][pl.get('call_id')] = _fonti_tool(pl.get('name') or 'shell', arg) a['dopo'].append(['modello:chiamate', _fonti_lungo(arg)]) elif k in ('function_call_output', 'custom_tool_call_output', 'local_shell_call_output'): _fonti_pezzo(a, a['tid'].pop(pl.get('call_id'), 'tool:?'), _fonti_lungo(pl.get('output') or '')) elif t == 'event_msg' and pl.get('type') == 'token_count': u = (pl.get('info') or {}).get('last_token_usage') or {} tot = ((pl.get('info') or {}).get('total_token_usage') or {}).get('total_tokens') if u and tot != a.get('tot_codex'): a['tot_codex'] = tot _fonti_risposta(a, int(u.get('input_tokens') or 0), a.pop('prima', []) + a['pend']) a['pend'] = [] a['prima'], a['dopo'] = (a['dopo'], []) def fonti_fuori(a): tutte = sorted(set(a['E']) | set(a['R']) | set(a['G']), key=lambda f: -a['R'].get(f, 0)) out, resto = ({}, [0, 0, 0]) for i, f in enumerate(tutte): v = [round(a['E'].get(f, 0)), round(a['R'].get(f, 0)), round(a['G'].get(f, 0))] if i < _FONTI_MAX - 1: out[f] = v else: resto = [x + y for x, y in zip(resto, v)] if any(resto): out['altro'] = [x + y for x, y in zip(out.get('altro', [0, 0, 0]), resto)] return {'contesto': int(a['prev']), 'fonti': out} def righe_testo(testo): for riga in testo.splitlines(): try: d = json.loads(riga) except ValueError: continue if isinstance(d, dict): yield d a = st.get('a') or fonti_nuovo() st['a'] = a if oc: nuove, st['oc'] = oc_righe(p, sid_oc, st.get('oc')) fine = 0 else: with open(p, 'rb') as f: f.seek(st['off']) pezzo = f.read() fine = pezzo.rfind(b'\n') + 1 nuove = righe_testo(pezzo[:fine].decode('utf-8', 'replace')) for d in nuove: fonti_riga(a, d) pl = d.get('payload') if isinstance(d.get('payload'), dict) else {} if d.get('type') == 'turn_context' and pl.get('model'): st['cli'], st['mod'] = ('codex', str(pl['model'])) elif pl.get('type') == 'token_count': u = (pl.get('info') or {}).get('total_token_usage') or {} if u: st['cli'] = 'codex' letta = int(u.get('cached_input_tokens') or 0) st['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)} st['n'] += 1 elif d.get('type') == 'assistant' and isinstance(d.get('usageMetadata'), dict): u = d['usageMetadata'] st['cli'], st['mod'] = ('qwen', str(d.get('model') or st['mod'])) letta = int(u.get('cachedContentTokenCount') or 0) somma({'input': max(0, int(u.get('promptTokenCount') or 0) - letta), 'cache_letta': letta, 'output': int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0)}) st['n'] += 1 elif d.get('type') == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict): m = d['message'] if m.get('model') and (not str(m['model']).startswith('<')): st['mod'] = str(m['model']) st['cli'] = 'opencode' if oc else 'claude' u = m['usage'] nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)} if m.get('id') != st['id']: if st['id']: somma(st['u']) st['id'] = m.get('id') or '' st['n'] += 1 st['u'] = nuovo st['off'] += fine for k in list(a['tid'])[:-200]: del a['tid'][k] tot = dict(t) if st['cli'] in ('claude', 'codex', 'opencode'): for k, v in st['u'].items(): tot[k] = (tot.get(k, 0) if st['cli'] != 'codex' else 0) + v atteso = sum((tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta'))) if atteso and abs(sum(a['R'].values()) - atteso) > max(1000, atteso // 100): a = fonti_nuovo() if oc: tutte = oc_righe(p, sid_oc, [0, ''])[0] else: with open(p, 'rb') as f: tutte = righe_testo(f.read(st['off']).decode('utf-8', 'replace')) for d in tutte: fonti_riga(a, d) for k in list(a['tid'])[:-200]: del a['tid'][k] st['a'] = a sid = os.path.basename(p).rsplit('.', 1)[0] radice = {'claude': os.path.join(os.path.dirname(p), sid, 'subagents'), 'qwen': os.path.join(os.path.dirname(os.path.dirname(p)), 'subagents', sid)}.get(st['cli']) ag = st.setdefault('ag', {}) file_agenti = sorted(glob.glob(os.path.join(radice, '**', 'agent-*.jsonl'), recursive=True)) if radice else [] if st['cli'] == 'codex': casa = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p)))) padri = st.setdefault('padri', {}) nato = st.setdefault('nato', os.path.getmtime(p) - 86400) for f in glob.glob(os.path.join(casa, '*', '*', '*', 'rollout-*.jsonl')): if f in padri or f == p: continue try: if os.path.getmtime(f) < nato: continue with open(f, 'rb') as h: m = json.loads(h.readline() or b'{}').get('payload') or {} except (OSError, ValueError): continue sp = ((m.get('source') or {}).get('subagent') or {}).get('thread_spawn') if isinstance(m.get('source'), dict) else None padri[f] = [str(m.get('id') or ''), str((sp or {}).get('parent_thread_id') or '')] try: with open(p, 'rb') as h: mio = str((json.loads(h.readline() or b'{}').get('payload') or {}).get('id') or '') except (OSError, ValueError): mio = '' famiglia, cresce = ({mio or str(e.get('session_id') or '')}, True) while cresce: cresce = False for i, padre in padri.values(): if padre in famiglia and i and (i not in famiglia): famiglia.add(i) cresce = True file_agenti = sorted((f for f, (i, padre) in padri.items() if padre in famiglia)) if oc: file_agenti = ['oc:' + i for i in oc_figlie(p, sid_oc)] for f in file_agenti: if f.startswith('oc:'): s = ag.get(f) or {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''} ag[f] = s righe_ag, s['oc'] = oc_righe(p, f[3:], s.get('oc')) fn = 0 else: try: dimf = os.path.getsize(f) except OSError: continue s = ag.get(f) if not s or s['off'] > dimf: s = ag[f] = {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''} with open(f, 'rb') as h: h.seek(s['off']) pz = h.read() fn = pz.rfind(b'\n') + 1 righe_ag = righe_testo(pz[:fn].decode('utf-8', 'replace')) for d in righe_ag: pl = d.get('payload') if isinstance(d.get('payload'), dict) else {} if d.get('type') == 'turn_context' and pl.get('model'): s['mod'] = str(pl['model']) elif pl.get('type') == 'token_count' and (pl.get('info') or {}).get('total_token_usage'): u = pl['info']['total_token_usage'] letta = int(u.get('cached_input_tokens') or 0) s['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)} s['n'] += 1 if d.get('type') != 'assistant': continue if isinstance(d.get('usageMetadata'), dict): u = d['usageMetadata'] letta = int(u.get('cachedContentTokenCount') or 0) for k, v in (('input', max(0, int(u.get('promptTokenCount') or 0) - letta)), ('cache_letta', letta), ('output', int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0))): s['t'][k] = s['t'].get(k, 0) + v s['n'] += 1 s['mod'] = str(d.get('model') or s['mod']) elif isinstance((d.get('message') or {}).get('usage'), dict): m = d['message'] u = m['usage'] if m.get('model') and (not str(m['model']).startswith('<')): s['mod'] = str(m['model']) nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)} if m.get('id') != s['id']: if s['id']: for k, v in s['u'].items(): s['t'][k] = s['t'].get(k, 0) + v s['id'] = m.get('id') or '' s['n'] += 1 s['u'] = nuovo s['off'] += fn agenti = {} for s in ag.values(): for k in ('input', 'cache_letta', 'cache_scritta', 'output'): agenti[k] = agenti.get(k, 0) + s['t'].get(k, 0) + s['u'].get(k, 0) agenti['risposte'] = agenti.get('risposte', 0) + s['n'] agenti['modello'] = s['mod'] or agenti.get('modello', '') tmp = stato_f + '.nuovo' json.dump(st, open(tmp, 'w')) os.replace(tmp, stato_f) if not st['cli']: sys.exit(0) fuori = {'conversazione': str(e.get('session_id') or os.path.basename(p))[:80], 'cli': st['cli'], 'modello': st['mod'][:80], 'risposte': st['n'], **{k: tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta', 'output')}, **fonti_fuori(a)} if agenti.get('risposte'): fuori['agenti'] = {**agenti, 'modello': agenti.get('modello', '')[:80]} print(json.dumps(fuori))