133 lines
7 KiB
Python
133 lines
7 KiB
Python
#!/usr/bin/env python3
|
|
"""Token usage + duration for one audit run.
|
|
|
|
usage.py <audit-dir> [--json]
|
|
|
|
Window: <audit-dir>/.started_at .. .finished_at (or now), epoch ms.
|
|
Attribution: any session (main, subagent, headless worker) whose transcript mentions
|
|
the audit dir path; only model calls made inside the window are counted.
|
|
|
|
Sources (read-only):
|
|
Claude Code ~/.claude/projects/*/**/*.jsonl (assistant message.usage, deduped by message id)
|
|
OpenCode ~/.local/share/opencode/opencode.db (message.data.tokens; subagents = child sessions)
|
|
"""
|
|
import glob, json, os, sqlite3, sys, time
|
|
from collections import defaultdict
|
|
from datetime import datetime
|
|
|
|
def iso_ms(s):
|
|
try: return int(datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp() * 1000)
|
|
except Exception: return None
|
|
|
|
def read_ms(path, default=None):
|
|
try: return int(open(path).read().strip())
|
|
except Exception: return default
|
|
|
|
def empty(): return {"calls": 0, "input": 0, "cache_write": 0, "cache_read": 0, "output": 0, "sessions": set()}
|
|
|
|
def claude_code(audit_dir, start, end, rows):
|
|
needle = audit_dir.encode()
|
|
root = os.path.expanduser("~/.claude/projects")
|
|
for f in glob.glob(os.path.join(root, "**", "*.jsonl"), recursive=True):
|
|
try:
|
|
if os.path.getmtime(f) * 1000 < start: continue
|
|
with open(f, "rb") as fh: data = fh.read()
|
|
except OSError: continue
|
|
if needle not in data: continue
|
|
kind = "subagent" if "/subagents/" in f else "session"
|
|
seen = {}
|
|
for line in data.splitlines():
|
|
try: o = json.loads(line)
|
|
except Exception: continue
|
|
m = o.get("message") or {}
|
|
if o.get("type") != "assistant" or not m.get("usage"): continue
|
|
ts = iso_ms(o.get("timestamp", ""))
|
|
if ts is None or ts < start or ts > end: continue
|
|
seen[m.get("id") or id(o)] = (m.get("model") or "?", m["usage"]) # last write wins
|
|
for model, u in seen.values():
|
|
r = rows[("claude-code", kind, model)]
|
|
r["calls"] += 1; r["sessions"].add(f)
|
|
r["input"] += u.get("input_tokens") or 0
|
|
r["cache_write"] += u.get("cache_creation_input_tokens") or 0
|
|
r["cache_read"] += u.get("cache_read_input_tokens") or 0
|
|
r["output"] += u.get("output_tokens") or 0
|
|
|
|
def opencode(audit_dir, start, end, rows):
|
|
db = os.path.expanduser("~/.local/share/opencode/opencode.db")
|
|
if not os.path.exists(db): return
|
|
try: c = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
|
|
except Exception: return
|
|
try:
|
|
roots = {r[0] for r in c.execute(
|
|
"select distinct p.session_id from part p join session s on s.id=p.session_id "
|
|
"where s.time_updated >= ? and p.data like ?", (start, f"%{audit_dir}%"))}
|
|
# include all descendants (subagent sessions) of matching sessions
|
|
allids, frontier = set(roots), set(roots)
|
|
while frontier:
|
|
q = ",".join("?" * len(frontier))
|
|
kids = {r[0] for r in c.execute(f"select id from session where parent_id in ({q})", tuple(frontier))}
|
|
frontier = kids - allids; allids |= kids
|
|
parent = dict(c.execute("select id, parent_id from session"))
|
|
for sid in allids:
|
|
kind = "subagent" if parent.get(sid) else "session"
|
|
for (d,) in c.execute("select data from message where session_id=?", (sid,)):
|
|
o = json.loads(d); t = o.get("tokens")
|
|
ts = (o.get("time") or {}).get("created")
|
|
if o.get("role") != "assistant" or not t or ts is None or ts < start or ts > end: continue
|
|
r = rows[("opencode", kind, f'{o.get("providerID")}/{o.get("modelID")}')]
|
|
r["calls"] += 1; r["sessions"].add(sid)
|
|
r["input"] += t.get("input") or 0
|
|
r["cache_write"] += (t.get("cache") or {}).get("write") or 0
|
|
r["cache_read"] += (t.get("cache") or {}).get("read") or 0
|
|
r["output"] += (t.get("output") or 0) + (t.get("reasoning") or 0)
|
|
finally: c.close()
|
|
|
|
def fmt_dur(ms):
|
|
s = max(0, ms // 1000); return f"{s//3600}h {s%3600//60:02d}m {s%60:02d}s" if s >= 3600 else f"{s//60}m {s%60:02d}s"
|
|
|
|
def main():
|
|
audit_dir = os.path.abspath(sys.argv[1]); as_json = "--json" in sys.argv
|
|
start = read_ms(os.path.join(audit_dir, ".started_at"))
|
|
if start is None: sys.exit("usage.py: no .started_at in audit dir (run audit.sh init)")
|
|
fin = read_ms(os.path.join(audit_dir, ".finished_at")); end = fin or int(time.time() * 1000)
|
|
rows = defaultdict(empty)
|
|
claude_code(audit_dir, start, end, rows); opencode(audit_dir, start, end, rows)
|
|
|
|
phases = []
|
|
tl = os.path.join(audit_dir, "timeline.tsv")
|
|
if os.path.exists(tl):
|
|
marks = [l.rstrip("\n").split("\t") for l in open(tl) if l.strip()]
|
|
marks = [(int(t), n) for t, n in marks]
|
|
for i, (t, n) in enumerate(marks):
|
|
nxt = marks[i + 1][0] if i + 1 < len(marks) else end
|
|
phases.append((n, nxt - t))
|
|
|
|
tot = empty()
|
|
for r in rows.values():
|
|
for k in ("calls", "input", "cache_write", "cache_read", "output"): tot[k] += r[k]
|
|
if as_json:
|
|
print(json.dumps({"start_ms": start, "end_ms": end, "finished": bool(fin), "duration_ms": end - start,
|
|
"phases": [{"phase": n, "ms": ms} for n, ms in phases],
|
|
"rows": [dict(harness=h, kind=k, model=m, **{x: v for x, v in r.items() if x != "sessions"}, session_count=len(r["sessions"]))
|
|
for (h, k, m), r in sorted(rows.items())],
|
|
"total": {k: v for k, v in tot.items() if k != "sessions"}}, indent=2)); return
|
|
|
|
n = lambda v: f"{v:,}"
|
|
out = [f"**Duration:** {fmt_dur(end - start)} wall clock "
|
|
f"({datetime.fromtimestamp(start/1000):%Y-%m-%d %H:%M} → {datetime.fromtimestamp(end/1000):%H:%M}"
|
|
f"{'' if fin else ', still running'})", ""]
|
|
if phases:
|
|
out += ["| Phase | Duration |", "|---|---|"] + [f"| {p} | {fmt_dur(ms)} |" for p, ms in phases] + [""]
|
|
out += ["| Harness | Kind | Model | Sessions | Calls | Input (uncached) | Cache write | Cache read | Output | Total input |",
|
|
"|---|---|---|---|---|---|---|---|---|---|"]
|
|
for (h, k, m), r in sorted(rows.items()):
|
|
ti = r["input"] + r["cache_write"] + r["cache_read"]
|
|
out.append(f"| {h} | {k} | {m} | {len(r['sessions'])} | {n(r['calls'])} | {n(r['input'])} | {n(r['cache_write'])} | {n(r['cache_read'])} | {n(r['output'])} | {n(ti)} |")
|
|
ti = tot["input"] + tot["cache_write"] + tot["cache_read"]
|
|
out.append(f"| **Total** | | | | **{n(tot['calls'])}** | **{n(tot['input'])}** | **{n(tot['cache_write'])}** | **{n(tot['cache_read'])}** | **{n(tot['output'])}** | **{n(ti)}** |")
|
|
out += ["", "_Total input = uncached + cache write + cache read; output includes reasoning/thinking tokens. "
|
|
"Counted: model calls inside the audit window from sessions whose transcript mentions this audit dir._"]
|
|
if not rows: out.append("_No matching sessions found — usage unavailable for this harness._")
|
|
print("\n".join(out))
|
|
|
|
if __name__ == "__main__": main()
|