delminio-client / kit / en / consumi-client
raw · sha256 8966af17ccf3353d5ff475f07a8cec54b2446ab3ef7249c71665c4328527868d
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"""I token di una conversazione, letti dalla CLI e mai il testo (F868)."""
4import glob, json, os, re, sys
5POSTA = re.compile('^ \\S+ → \\S+ \\d\\d:\\d\\d UTC$', re.M)
6stato_f = sys.argv[1]
7try:
8 e = json.load(sys.stdin)
9 p = e.get('transcript_path') or ''
10 dim = os.path.getsize(p)
11except Exception:
12 sys.exit(0)
13try:
14 st = json.load(open(stato_f))
15except Exception:
16 st = {}
17oc = e.get('cli') == 'opencode'
18sid_oc = str(e.get('session_id') or '')
19chiave = p + '#' + sid_oc if oc else p
20if st.get('p') != chiave or (not oc and st.get('off', 0) > dim):
21 st = {'p': chiave, 'off': 0, 'cli': '', 'mod': '', 't': {}, 'id': '', 'u': {}, 'n': 0}
22t = st['t']
23
24def oc_testo(x):
25 if isinstance(x, str):
26 return x
27 if isinstance(x, list):
28 return ''.join((oc_testo(b) for b in x))
29 if isinstance(x, dict):
30 return str(x.get('text') or x.get('output') or '')
31 return ''
32
33def oc_risposta(mid, modello, tok, blocchi, risultati):
34 tok = tok or {}
35 cache = tok.get('cache') or {}
36 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)}
37 out = [{'type': 'assistant', 'message': {'id': mid, 'model': modello, 'usage': u, 'content': blocchi}}]
38 if risultati:
39 out.append({'type': 'user', 'message': {'content': risultati}})
40 return out
41
42def oc_umano(parti):
43 out = []
44 for x in parti:
45 if x.get('type') != 'text' or not x.get('text'):
46 continue
47 if x.get('synthetic'):
48 out.append({'type': 'attachment', 'attachment': {'type': 'hook_additional_context', 'hookEvent': 'opencode', 'content': x['text']}})
49 else:
50 out.append({'type': 'user', 'message': {'content': [{'type': 'text', 'text': x['text']}]}})
51 return out
52
53def oc_righe(db, sid, dopo):
54 import sqlite3
55 righe, fino = ([], list(dopo or [0, '']))
56 try:
57 c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
58 except sqlite3.Error:
59 return (righe, fino)
60 try:
61 tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
62 dove = 'session_id=? and (time_created>? or (time_created=? and id>?)) order by time_created, id'
63 arg = (sid, fino[0], fino[0], fino[1])
64 if 'session_message' in tabelle:
65 for mid, tc, tipo, d in c.execute('select id, time_created, type, data from session_message where ' + dove, arg).fetchall():
66 m = json.loads(d)
67 if tipo == 'assistant':
68 if not (m.get('time') or {}).get('completed'):
69 break
70 mod = m.get('model') or {}
71 modello = (str(mod.get('providerID') or '') + '/' + str(mod.get('id') or '')).strip('/')
72 blocchi, ris = ([], [])
73 for x in m.get('content') or []:
74 k = x.get('type')
75 if k == 'tool':
76 s = x.get('state') or {}
77 blocchi.append({'type': 'tool_use', 'id': x.get('id'), 'name': x.get('name'), 'input': s.get('input') or {}})
78 if s.get('status') in ('completed', 'error'):
79 ris.append({'type': 'tool_result', 'tool_use_id': x.get('id'), 'content': oc_testo(s.get('content') or s.get('error') or '')})
80 elif k == 'text':
81 blocchi.append({'type': 'text', 'text': x.get('text') or ''})
82 elif k == 'reasoning':
83 blocchi.append({'type': 'thinking', 'thinking': oc_testo(x.get('text') or x.get('content'))})
84 righe += oc_risposta(mid, modello, m.get('tokens'), blocchi, ris)
85 elif tipo == 'user':
86 righe += oc_umano([{'type': 'text', 'text': m.get('text') or ''}])
87 elif (tx := oc_testo(m.get('text') or m.get('content'))):
88 righe += oc_umano([{'type': 'text', 'text': tx, 'synthetic': True}])
89 fino = [tc, mid]
90 except (sqlite3.Error, ValueError):
91 pass
92 finally:
93 c.close()
94 return (righe, fino)
95
96def oc_figlie(db, sid):
97 import sqlite3
98 try:
99 c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
100 except sqlite3.Error:
101 return []
102 try:
103 tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
104 figli = {}
105 for tab in ('session', 'session_v2'):
106 if tab in tabelle:
107 for i, padre in c.execute('select id, parent_id from ' + tab + ' where parent_id is not null'):
108 figli.setdefault(padre, []).append(i)
109 except sqlite3.Error:
110 return []
111 finally:
112 c.close()
113 out, coda = ([], [sid])
114 while coda:
115 for i in figli.get(coda.pop(), []):
116 if i not in out:
117 out.append(i)
118 coda.append(i)
119 return out
120
121def somma(d):
122 for k, v in d.items():
123 t[k] = t.get(k, 0) + int(v or 0)
124import re
125_CAR_PER_TOKEN = 3.2
126_FONTI_MAX = 64
127_COMANDO_DELMINIO = re.compile('(?:^|[\\s;&|(\\"\\x27])delminio\\s+[a-z]|delminio\\.sh\\b')
128
129def _fonti_lungo(x):
130 if isinstance(x, str):
131 return len(x)
132 if isinstance(x, list):
133 return sum((6000 if isinstance(b, dict) and b.get('type') == 'image' else _fonti_lungo(b) for b in x))
134 if isinstance(x, dict) and x.get('type') == 'text':
135 return len(x.get('text') or '')
136 return len(json.dumps(x, ensure_ascii=False))
137
138def _fonti_tool(nome, argomenti):
139 nome = str(nome or '?')
140 if 'delminio' in nome.lower():
141 op = argomenti.get('operation') if isinstance(argomenti, dict) else None
142 return 'delminio:' + str(op or nome.rsplit('__', 1)[-1])[:30]
143 testo = argomenti if isinstance(argomenti, str) else json.dumps(argomenti, ensure_ascii=False)
144 if nome in ('Bash', 'bash', 'exec_command', 'shell', 'exec', 'run_shell_command') or 'shell' in nome.lower():
145 return 'delminio:comando' if _COMANDO_DELMINIO.search(testo or '') else 'comando'
146 if nome.startswith('mcp__'):
147 return 'mcp:' + nome.split('__')[1][:30]
148 return 'tool:' + nome[:30]
149
150def fonti_nuovo():
151 return {'E': {}, 'R': {}, 'G': {}, 'pend': [], 'dopo': [], 'tid': {}, 'prev': 0, 'n': 0, 'ultimo': None}
152
153def _fonti_pezzo(a, fonte, car):
154 if car > 0:
155 a['pend'].append([fonte, int(car)])
156
157def _fonti_risposta(a, ctx, pezzi):
158 E = a['E']
159 if a['n'] == 0:
160 stima = {}
161 for f, c in pezzi:
162 stima[f] = stima.get(f, 0) + c / _CAR_PER_TOKEN
163 tot = sum(stima.values())
164 scala = min(1.0, ctx / tot) if tot else 0
165 for f, v in stima.items():
166 E[f] = E.get(f, 0) + v * scala
167 E['sistema'] = E.get('sistema', 0) + max(0, ctx - tot * scala)
168 elif ctx < a['prev']:
169 scala = ctx / a['prev']
170 for f in E:
171 E[f] *= scala
172 else:
173 delta = ctx - a['prev']
174 car = sum((c for _, c in pezzi))
175 if not car:
176 E['altro'] = E.get('altro', 0) + delta
177 for f, c in pezzi:
178 E[f] = E.get(f, 0) + delta * c / car if car else E.get(f, 0)
179 for f, v in E.items():
180 a['R'][f] = a['R'].get(f, 0) + v
181 motori = sorted({f for f, _ in pezzi if f.split(':')[0] in ('delminio', 'comando', 'tool', 'mcp')})
182 if not motori:
183 motori = ['persona'] if any((f == 'persona' for f, _ in pezzi)) else ['altro']
184 for f in motori:
185 a['G'][f] = a['G'].get(f, 0) + ctx / len(motori)
186 a['prev'] = ctx
187 a['n'] += 1
188
189def fonti_riga(a, d):
190 t = d.get('type')
191 pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
192 if t == 'attachment' and isinstance(d.get('attachment'), dict):
193 at = d['attachment']
194 k = str(at.get('type') or '')
195 if k == 'hook_additional_context':
196 _fonti_pezzo(a, 'gancio:' + str(at.get('hookEvent') or '?')[:30], _fonti_lungo(at.get('content') or ''))
197 elif k not in ('hook_success', 'prompt_snapshot', ''):
198 _fonti_pezzo(a, 'cli:' + k[:40], _fonti_lungo({x: y for x, y in at.items() if x != 'type'}))
199 return
200 if t == 'user' and isinstance(d.get('message'), dict) and (not d.get('isSidechain')):
201 c = d['message'].get('content')
202 if isinstance(c, str):
203 _fonti_pezzo(a, 'cli:meta' if d.get('isMeta') else 'persona', len(c))
204 return
205 for b in c if isinstance(c, list) else []:
206 if not isinstance(b, dict):
207 continue
208 if b.get('type') == 'tool_result':
209 _fonti_pezzo(a, a['tid'].pop(b.get('tool_use_id'), 'tool:?'), _fonti_lungo(b.get('content') or ''))
210 elif b.get('type') == 'text':
211 x = b.get('text') or ''
212 f = 'gancio:posta' if POSTA.search(x) else 'cli:promemoria' if '<system-reminder>' in x or d.get('isMeta') else 'persona'
213 _fonti_pezzo(a, f, len(x))
214 elif b.get('type') == 'image':
215 _fonti_pezzo(a, 'persona', 6000)
216 return
217 if t == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict) and (not d.get('isSidechain')):
218 m = d['message']
219 if m.get('id') != a['ultimo']:
220 u = m['usage']
221 a['ultimo'] = m.get('id')
222 _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'])
223 a['pend'] = []
224 for b in m.get('content') or []:
225 if not isinstance(b, dict):
226 continue
227 if b.get('type') == 'tool_use':
228 a['tid'][b.get('id')] = _fonti_tool(b.get('name'), b.get('input') or {})
229 _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(b.get('input') or {}))
230 elif b.get('type') == 'thinking':
231 _fonti_pezzo(a, 'modello:pensiero', len(b.get('thinking') or '') or len(b.get('signature') or '') // 2)
232 elif b.get('type') == 'text':
233 _fonti_pezzo(a, 'modello:testo', len(b.get('text') or ''))
234 return
235 if t == 'assistant' and isinstance(d.get('usageMetadata'), dict):
236 _fonti_risposta(a, int(d['usageMetadata'].get('promptTokenCount') or 0), a['pend'])
237 a['pend'] = []
238 for p in (d.get('message') or {}).get('parts') or []:
239 if not isinstance(p, dict):
240 continue
241 if isinstance(p.get('functionCall'), dict):
242 fc = p['functionCall']
243 a['tid'][fc.get('id') or fc.get('name')] = _fonti_tool(fc.get('name'), fc.get('args') or {})
244 _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(fc.get('args') or {}))
245 elif p.get('text'):
246 _fonti_pezzo(a, 'modello:pensiero' if p.get('thought') else 'modello:testo', len(p['text']))
247 return
248 if t == 'tool_result':
249 for p in (d.get('message') or {}).get('parts') or []:
250 fr = p.get('functionResponse') if isinstance(p, dict) else None
251 if isinstance(fr, dict):
252 f = a['tid'].pop(fr.get('id'), None) or a['tid'].pop(fr.get('name'), None) or _fonti_tool(fr.get('name'), {})
253 _fonti_pezzo(a, f, _fonti_lungo(fr.get('response') or ''))
254 return
255 if t == 'user' and isinstance(d.get('message'), dict):
256 for p in d['message'].get('parts') or []:
257 if isinstance(p, dict) and p.get('text'):
258 _fonti_pezzo(a, 'cli:avviso' if d.get('subtype') else 'persona', len(p['text']))
259 return
260 if t == 'session_meta':
261 _fonti_pezzo(a, 'sistema', _fonti_lungo(pl.get('base_instructions') or ''))
262 elif t == 'response_item':
263 k = pl.get('type')
264 if k == 'message':
265 car = _fonti_lungo(pl.get('content') or [])
266 if pl.get('role') == 'assistant':
267 a['dopo'].append(['modello:testo', car])
268 else:
269 testo = json.dumps(pl.get('content') or [], ensure_ascii=False)
270 f = 'persona' if pl.get('role') == 'user' and '<environment_context>' not in testo and ('AGENTS.md' not in testo) else 'cli:istruzioni'
271 _fonti_pezzo(a, f, car)
272 elif k == 'reasoning':
273 a['dopo'].append(['modello:pensiero', len(pl.get('encrypted_content') or '') // 3 or _fonti_lungo(pl.get('summary') or [])])
274 elif k in ('function_call', 'custom_tool_call', 'local_shell_call'):
275 arg = pl.get('arguments') or pl.get('input') or pl.get('action') or {}
276 if isinstance(arg, str):
277 try:
278 arg = json.loads(arg)
279 except ValueError:
280 pass
281 a['tid'][pl.get('call_id')] = _fonti_tool(pl.get('name') or 'shell', arg)
282 a['dopo'].append(['modello:chiamate', _fonti_lungo(arg)])
283 elif k in ('function_call_output', 'custom_tool_call_output', 'local_shell_call_output'):
284 _fonti_pezzo(a, a['tid'].pop(pl.get('call_id'), 'tool:?'), _fonti_lungo(pl.get('output') or ''))
285 elif t == 'event_msg' and pl.get('type') == 'token_count':
286 u = (pl.get('info') or {}).get('last_token_usage') or {}
287 tot = ((pl.get('info') or {}).get('total_token_usage') or {}).get('total_tokens')
288 if u and tot != a.get('tot_codex'):
289 a['tot_codex'] = tot
290 _fonti_risposta(a, int(u.get('input_tokens') or 0), a.pop('prima', []) + a['pend'])
291 a['pend'] = []
292 a['prima'], a['dopo'] = (a['dopo'], [])
293
294def fonti_fuori(a):
295 tutte = sorted(set(a['E']) | set(a['R']) | set(a['G']), key=lambda f: -a['R'].get(f, 0))
296 out, resto = ({}, [0, 0, 0])
297 for i, f in enumerate(tutte):
298 v = [round(a['E'].get(f, 0)), round(a['R'].get(f, 0)), round(a['G'].get(f, 0))]
299 if i < _FONTI_MAX - 1:
300 out[f] = v
301 else:
302 resto = [x + y for x, y in zip(resto, v)]
303 if any(resto):
304 out['altro'] = [x + y for x, y in zip(out.get('altro', [0, 0, 0]), resto)]
305 return {'contesto': int(a['prev']), 'fonti': out}
306
307def righe_testo(testo):
308 for riga in testo.splitlines():
309 try:
310 d = json.loads(riga)
311 except ValueError:
312 continue
313 if isinstance(d, dict):
314 yield d
315a = st.get('a') or fonti_nuovo()
316st['a'] = a
317if oc:
318 nuove, st['oc'] = oc_righe(p, sid_oc, st.get('oc'))
319 fine = 0
320else:
321 with open(p, 'rb') as f:
322 f.seek(st['off'])
323 pezzo = f.read()
324 fine = pezzo.rfind(b'\n') + 1
325 nuove = righe_testo(pezzo[:fine].decode('utf-8', 'replace'))
326for d in nuove:
327 fonti_riga(a, d)
328 pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
329 if d.get('type') == 'turn_context' and pl.get('model'):
330 st['cli'], st['mod'] = ('codex', str(pl['model']))
331 elif pl.get('type') == 'token_count':
332 u = (pl.get('info') or {}).get('total_token_usage') or {}
333 if u:
334 st['cli'] = 'codex'
335 letta = int(u.get('cached_input_tokens') or 0)
336 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)}
337 st['n'] += 1
338 elif d.get('type') == 'assistant' and isinstance(d.get('usageMetadata'), dict):
339 u = d['usageMetadata']
340 st['cli'], st['mod'] = ('qwen', str(d.get('model') or st['mod']))
341 letta = int(u.get('cachedContentTokenCount') or 0)
342 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)})
343 st['n'] += 1
344 elif d.get('type') == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict):
345 m = d['message']
346 if m.get('model') and (not str(m['model']).startswith('<')):
347 st['mod'] = str(m['model'])
348 st['cli'] = 'opencode' if oc else 'claude'
349 u = m['usage']
350 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)}
351 if m.get('id') != st['id']:
352 if st['id']:
353 somma(st['u'])
354 st['id'] = m.get('id') or ''
355 st['n'] += 1
356 st['u'] = nuovo
357st['off'] += fine
358for k in list(a['tid'])[:-200]:
359 del a['tid'][k]
360tot = dict(t)
361if st['cli'] in ('claude', 'codex', 'opencode'):
362 for k, v in st['u'].items():
363 tot[k] = (tot.get(k, 0) if st['cli'] != 'codex' else 0) + v
364atteso = sum((tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta')))
365if atteso and abs(sum(a['R'].values()) - atteso) > max(1000, atteso // 100):
366 a = fonti_nuovo()
367 if oc:
368 tutte = oc_righe(p, sid_oc, [0, ''])[0]
369 else:
370 with open(p, 'rb') as f:
371 tutte = righe_testo(f.read(st['off']).decode('utf-8', 'replace'))
372 for d in tutte:
373 fonti_riga(a, d)
374 for k in list(a['tid'])[:-200]:
375 del a['tid'][k]
376 st['a'] = a
377sid = os.path.basename(p).rsplit('.', 1)[0]
378radice = {'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'])
379ag = st.setdefault('ag', {})
380file_agenti = sorted(glob.glob(os.path.join(radice, '**', 'agent-*.jsonl'), recursive=True)) if radice else []
381if st['cli'] == 'codex':
382 casa = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p))))
383 padri = st.setdefault('padri', {})
384 nato = st.setdefault('nato', os.path.getmtime(p) - 86400)
385 for f in glob.glob(os.path.join(casa, '*', '*', '*', 'rollout-*.jsonl')):
386 if f in padri or f == p:
387 continue
388 try:
389 if os.path.getmtime(f) < nato:
390 continue
391 with open(f, 'rb') as h:
392 m = json.loads(h.readline() or b'{}').get('payload') or {}
393 except (OSError, ValueError):
394 continue
395 sp = ((m.get('source') or {}).get('subagent') or {}).get('thread_spawn') if isinstance(m.get('source'), dict) else None
396 padri[f] = [str(m.get('id') or ''), str((sp or {}).get('parent_thread_id') or '')]
397 try:
398 with open(p, 'rb') as h:
399 mio = str((json.loads(h.readline() or b'{}').get('payload') or {}).get('id') or '')
400 except (OSError, ValueError):
401 mio = ''
402 famiglia, cresce = ({mio or str(e.get('session_id') or '')}, True)
403 while cresce:
404 cresce = False
405 for i, padre in padri.values():
406 if padre in famiglia and i and (i not in famiglia):
407 famiglia.add(i)
408 cresce = True
409 file_agenti = sorted((f for f, (i, padre) in padri.items() if padre in famiglia))
410if oc:
411 file_agenti = ['oc:' + i for i in oc_figlie(p, sid_oc)]
412for f in file_agenti:
413 if f.startswith('oc:'):
414 s = ag.get(f) or {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
415 ag[f] = s
416 righe_ag, s['oc'] = oc_righe(p, f[3:], s.get('oc'))
417 fn = 0
418 else:
419 try:
420 dimf = os.path.getsize(f)
421 except OSError:
422 continue
423 s = ag.get(f)
424 if not s or s['off'] > dimf:
425 s = ag[f] = {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
426 with open(f, 'rb') as h:
427 h.seek(s['off'])
428 pz = h.read()
429 fn = pz.rfind(b'\n') + 1
430 righe_ag = righe_testo(pz[:fn].decode('utf-8', 'replace'))
431 for d in righe_ag:
432 pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
433 if d.get('type') == 'turn_context' and pl.get('model'):
434 s['mod'] = str(pl['model'])
435 elif pl.get('type') == 'token_count' and (pl.get('info') or {}).get('total_token_usage'):
436 u = pl['info']['total_token_usage']
437 letta = int(u.get('cached_input_tokens') or 0)
438 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)}
439 s['n'] += 1
440 if d.get('type') != 'assistant':
441 continue
442 if isinstance(d.get('usageMetadata'), dict):
443 u = d['usageMetadata']
444 letta = int(u.get('cachedContentTokenCount') or 0)
445 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))):
446 s['t'][k] = s['t'].get(k, 0) + v
447 s['n'] += 1
448 s['mod'] = str(d.get('model') or s['mod'])
449 elif isinstance((d.get('message') or {}).get('usage'), dict):
450 m = d['message']
451 u = m['usage']
452 if m.get('model') and (not str(m['model']).startswith('<')):
453 s['mod'] = str(m['model'])
454 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)}
455 if m.get('id') != s['id']:
456 if s['id']:
457 for k, v in s['u'].items():
458 s['t'][k] = s['t'].get(k, 0) + v
459 s['id'] = m.get('id') or ''
460 s['n'] += 1
461 s['u'] = nuovo
462 s['off'] += fn
463agenti = {}
464for s in ag.values():
465 for k in ('input', 'cache_letta', 'cache_scritta', 'output'):
466 agenti[k] = agenti.get(k, 0) + s['t'].get(k, 0) + s['u'].get(k, 0)
467 agenti['risposte'] = agenti.get('risposte', 0) + s['n']
468 agenti['modello'] = s['mod'] or agenti.get('modello', '')
469tmp = stato_f + '.nuovo'
470json.dump(st, open(tmp, 'w'))
471os.replace(tmp, stato_f)
472if not st['cli']:
473 sys.exit(0)
474fuori = {'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)}
475if agenti.get('risposte'):
476 fuori['agenti'] = {**agenti, 'modello': agenti.get('modello', '')[:80]}
477print(json.dumps(fuori))