Files
aimsight-optimizer/outils/suivre.py
T

46 lines
2.7 KiB
Python

"""Suit le flux d'un agent du batch pendant qu'il tourne (batches/<jour>/scan.jsonl ou improve.jsonl, écrit par claude -p) et
imprime ce qui compte : l'ouverture (source d'authentification, modèle, plugins), les sous-agents lancés, les commandes git et
de mesure, les fichiers écrits, les erreurs d'outil, la fin et son coût. python3 outils/suivre.py <flux.jsonl> [--fin]
(--fin : depuis la fin du fichier, pour reprendre une séance déjà commencée)."""
import json, sys, time
chemin = sys.argv[1]
while True:
try:
f = open(chemin, encoding="utf-8"); break
except FileNotFoundError:
time.sleep(1)
if "--fin" in sys.argv:
f.seek(0, 2)
outils = {}
while True:
l = f.readline()
if not l:
time.sleep(1); continue
if not l.startswith("{"):
print("RAW", l[:200], flush=True); continue
d = json.loads(l)
t, sub, par = d.get("type"), d.get("subtype"), d.get("parent_tool_use_id")
qui = "sous-agent" if par else "orchestrateur"
if t == "system" and sub == "init":
print(f"INIT apiKeySource={d.get('apiKeySource')} model={d.get('model')} plugins={[p['name'] for p in d.get('plugins', [])]} agents={[a for a in d.get('agents', []) if ':' in a]}", flush=True)
elif t == "assistant":
for c in d["message"].get("content", []):
if c.get("type") != "tool_use":
continue
i = c["input"]; outils[c["id"]] = (c["name"], i)
if c["name"] in ("Agent", "Task"):
print(f"AGENT {i.get('subagent_type')} lancé : {i.get('description')}", flush=True)
elif c["name"] == "Bash" and any(k in i.get("command", "") for k in ("git -C", "git commit", "regression.py", "score.py", "revert")):
print(f"BASH ({qui}) {i['command'][:220]}", flush=True)
elif c["name"] in ("Write", "Edit") and "/scripts/" in i.get("file_path", "") or c["name"] == "Write" and i.get("file_path", "").endswith(".md"):
print(f"{c['name'].upper()} ({qui}) {i.get('file_path')}", flush=True)
elif t == "user":
for c in d["message"].get("content", []) if isinstance(d["message"].get("content"), list) else []:
if c.get("type") == "tool_result" and c.get("is_error"):
n, i = outils.get(c.get("tool_use_id"), ("?", {}))
print(f"ERREUR ({qui}) {n} {str(i.get('command') or i.get('file_path') or '')[:120]} -> {str(c.get('content'))[:250]}", flush=True)
elif t == "result":
print(f"FIN {sub} tours={d.get('num_turns')} durée={round((d.get('duration_ms') or 0)/1000)}s coût_équiv={d.get('total_cost_usd')} refus={d.get('permission_denials')}", flush=True)
print("RÉPONSE", (d.get("result") or "")[:600].replace("\n", " | "), flush=True)
break