-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1657 lines (1480 loc) · 62.5 KB
/
Copy pathserver.py
File metadata and controls
executable file
·1657 lines (1480 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
server.py — Web backend for the auditit session viewer.
Serves:
GET / → Web UI (index.html)
GET /api/sessions → List all sessions
GET /api/sessions/<session-id>/events → All events (JSONL or gz)
GET /api/sessions/<session-id>/stream → SSE stream (live tail)
GET /api/sessions/<session-id>/meta → metadata + summary
Layout: ~/.claude-audit/<session-id>/audit.jsonl(.gz) — flat, no date
partitioning. Sub-agent dirs live as siblings: <session-id>__agent__<id>/.
The frontend groups/sorts by started_at and last_active_at as needed.
Cost is computed at serve time from summary.json's raw `usage` dict and
`model` name, against the PRICING table below. Keep docs/claude-pricing.md
in sync when pricing changes.
"""
import gzip
import json
import os
import shutil
import subprocess
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
from pathlib import Path
from urllib.parse import unquote
AUDIT_DIR = Path.home() / ".claude-audit"
SKILLS_DIR = Path.home() / ".claude" / "skills"
REPO_DIR = Path(__file__).resolve().parent
def _read_repo_version():
try:
commit = subprocess.check_output(
["git", "-C", str(REPO_DIR), "rev-parse", "--short=7", "HEAD"],
stderr=subprocess.DEVNULL, text=True,
).strip()
date = subprocess.check_output(
["git", "-C", str(REPO_DIR), "log", "-1", "--format=%cI", "HEAD"],
stderr=subprocess.DEVNULL, text=True,
).strip()
return {"commit": commit, "date": date}
except Exception:
return {"commit": "", "date": ""}
REPO_VERSION = _read_repo_version()
# A session is considered "live" only if its audit.jsonl was touched within
# this many seconds. Beyond that, any stuck directory (sub-agent leftover,
# killed main session, whatever) is safe to delete.
ACTIVE_WINDOW_S = 60
# ── Pricing (per-million-token, USD, standard tier) ──────────────────
#
# Source: https://platform.claude.com/docs/en/about-claude/pricing
# Snapshot: 2026-04-11, mirrored in docs/claude-pricing.md.
#
# Keys are lowercased and matched by substring against the transcript's
# model field (e.g. "claude-haiku-4-5-20251001" matches "claude-haiku-4-5").
PRICING: dict[str, dict[str, float]] = {
# Opus
"claude-opus-4-6": {"in": 5.00, "out": 25.00, "cw5m": 6.25, "cw1h": 10.00, "cr": 0.50},
"claude-opus-4-5": {"in": 5.00, "out": 25.00, "cw5m": 6.25, "cw1h": 10.00, "cr": 0.50},
"claude-opus-4-1": {"in": 15.00, "out": 75.00, "cw5m": 18.75, "cw1h": 30.00, "cr": 1.50},
"claude-opus-4": {"in": 15.00, "out": 75.00, "cw5m": 18.75, "cw1h": 30.00, "cr": 1.50},
# Sonnet
"claude-sonnet-4-6": {"in": 3.00, "out": 15.00, "cw5m": 3.75, "cw1h": 6.00, "cr": 0.30},
"claude-sonnet-4-5": {"in": 3.00, "out": 15.00, "cw5m": 3.75, "cw1h": 6.00, "cr": 0.30},
"claude-sonnet-4": {"in": 3.00, "out": 15.00, "cw5m": 3.75, "cw1h": 6.00, "cr": 0.30},
# Haiku
"claude-haiku-4-5": {"in": 1.00, "out": 5.00, "cw5m": 1.25, "cw1h": 2.00, "cr": 0.10},
"claude-haiku-3-5": {"in": 0.80, "out": 4.00, "cw5m": 1.00, "cw1h": 1.60, "cr": 0.08},
"claude-haiku-3": {"in": 0.25, "out": 1.25, "cw5m": 0.30, "cw1h": 0.50, "cr": 0.03},
}
def _is_session_active(session_dir: Path) -> bool:
"""Return True only if a session directory is still being written to.
Not-active covers every case where we can safely delete:
- summary.json exists (normal SessionEnd completion)
- audit.jsonl.gz exists (atomic compress already done)
- audit.jsonl missing (empty dir, nothing to lose)
- audit.jsonl contains a SessionEnd event (hook fired but compress
step failed for some reason)
- audit.jsonl is stale — last mtime older than ACTIVE_WINDOW_S.
This is the catch-all for sub-agent leftovers (sub-agents have
their own session_id but never fire SessionStart/SessionEnd) and
for main sessions killed with -9 before they could reach SessionEnd.
"""
if (session_dir / "summary.json").exists():
return False
if (session_dir / "audit.jsonl.gz").exists():
return False
jsonl = session_dir / "audit.jsonl"
if not jsonl.exists():
return False
try:
age = time.time() - jsonl.stat().st_mtime
except OSError:
return False
if age > ACTIVE_WINDOW_S:
return False
# Young file — look for a SessionEnd event we just failed to compress.
try:
with open(jsonl, "rb") as f:
data = f.read()
if b'"event":"SessionEnd"' in data:
return False
except OSError:
pass
return True
def _match_pricing(model: str) -> dict | None:
if not model:
return None
m = model.lower()
if m in PRICING:
return PRICING[m]
# Prefer longest prefix match so "claude-opus-4-6" wins over "claude-opus-4".
best_key: str | None = None
for key in PRICING:
if key in m and (best_key is None or len(key) > len(best_key)):
best_key = key
return PRICING[best_key] if best_key else None
# ── Context window sizes ─────────────────────────────────────────────
#
# Source: https://platform.claude.com/docs/en/about-claude/models
# Snapshot: 2026-04-11, mirrored in docs/claude-context-windows.md.
# Opus 4.6 and Sonnet 4.6 ship a 1M context at standard pricing; every
# other listed model is 200k. Unknown models fall back to 200k.
DEFAULT_CTX_WINDOW = 200_000
CTX_WINDOW: dict[str, int] = {
"claude-opus-4-6": 1_000_000,
"claude-sonnet-4-6": 1_000_000,
"claude-opus-4-5": 200_000,
"claude-opus-4-1": 200_000,
"claude-opus-4": 200_000,
"claude-sonnet-4-5": 200_000,
"claude-sonnet-4": 200_000,
"claude-haiku-4-5": 200_000,
"claude-haiku-3-5": 200_000,
"claude-haiku-3": 200_000,
}
def _match_ctx_window(model: str) -> int:
if not model:
return DEFAULT_CTX_WINDOW
m = model.lower()
if m in CTX_WINDOW:
return CTX_WINDOW[m]
best_key: str | None = None
for key in CTX_WINDOW:
if key in m and (best_key is None or len(key) > len(best_key)):
best_key = key
return CTX_WINDOW[best_key] if best_key else DEFAULT_CTX_WINDOW
def compute_ctx(model: str, ctx_peak_tokens: int) -> dict:
"""Return a dict with ctx_peak_tokens / ctx_window / ctx_peak_pct.
All three are always present so the Web UI can conditionally render.
ctx_peak_pct is a float in [0, 1+]; values > 1.0 are clamped by the
UI display but kept raw here for diagnostics.
"""
peak = int(ctx_peak_tokens or 0)
window = _match_ctx_window(model)
pct = (peak / window) if window else 0.0
return {
"ctx_peak_tokens": peak,
"ctx_window": window,
"ctx_peak_pct": round(pct, 4),
}
def compute_cost(model: str, usage: dict) -> float:
"""Return the dollar cost of a session given its model and cleaned usage.
Expects the shape hook.sh writes to summary.json:
{input_tokens, output_tokens, cache_read_input_tokens,
cache_creation_input_tokens, cache_creation_5m_tokens,
cache_creation_1h_tokens}
Falls back to attributing all `cache_creation_input_tokens` to 5m cache
writes when the 5m/1h split is absent (older sessions).
Unknown model → 0.0.
"""
if not isinstance(usage, dict):
return 0.0
price = _match_pricing(model)
if not price:
return 0.0
inp = usage.get("input_tokens", 0) or 0
out = usage.get("output_tokens", 0) or 0
cr = usage.get("cache_read_input_tokens", 0) or 0
cw5m = usage.get("cache_creation_5m_tokens", 0) or 0
cw1h = usage.get("cache_creation_1h_tokens", 0) or 0
# Old sessions stored only the total; attribute it to 5m as a conservative guess.
cw_total = usage.get("cache_creation_input_tokens", 0) or 0
if cw_total and not (cw5m or cw1h):
cw5m = cw_total
M = 1_000_000
cost = (
inp * price["in"] / M +
out * price["out"] / M +
cr * price["cr"] / M +
cw5m * price["cw5m"] / M +
cw1h * price["cw1h"] / M
)
return round(cost, 6)
SUBAGENT_SEP = "__agent__"
def _load_subagent_meta(session_dir: Path) -> dict | None:
"""Return the meta.json written by hook.sh for sub-agent dirs, or None."""
meta_path = session_dir / "meta.json"
if not meta_path.exists():
return None
try:
with open(meta_path) as f:
m = json.load(f)
except (OSError, json.JSONDecodeError):
return None
if not isinstance(m, dict) or not m.get("is_subagent"):
return None
return m
def _last_active_iso(session_dir: Path) -> str:
"""ISO-8601 UTC of the LAST EVENT in the session's audit log.
Reads the last line of audit.jsonl (or .gz) and parses its `ts`. This
is the truth: file mtimes can be bumped by migrations, cp, tar, or any
write — but every event line carries its own timestamp.
Cached into metadata.json keyed by the audit file's current size so we
only re-read when the file actually grew. For finished sessions (.gz)
the cache is permanent because the file size never changes again.
Returns "" when the session has no readable events.
"""
jsonl = session_dir / "audit.jsonl"
gz = session_dir / "audit.jsonl.gz"
# Resume case: both files coexist. Prefer .jsonl (newer events) but
# fall back to .gz if .jsonl is empty (resume just started, no event
# written yet). For a single-file session, this picks the only one.
if jsonl.exists() and jsonl.stat().st_size > 0:
src = jsonl
elif gz.exists():
src = gz
elif jsonl.exists():
src = jsonl
else:
return ""
try:
size = src.stat().st_size
except OSError:
return ""
# Cache lookup
meta_path = session_dir / "metadata.json"
cached = None
if meta_path.exists():
try:
with open(meta_path) as f:
cached = json.load(f) or {}
except (OSError, json.JSONDecodeError):
cached = None
if cached and cached.get("_last_active_src") == src.name \
and cached.get("_last_active_size") == size \
and cached.get("last_active_at"):
return cached["last_active_at"]
# Recompute: pull the LAST non-empty line from the audit log.
last_line = b""
try:
if src.name.endswith(".gz"):
with gzip.open(src, "rb") as f:
for line in f:
if line.strip():
last_line = line
else:
# Tail read — seek backward in 8KB chunks until we have at least
# one full newline-terminated line. Avoids decompressing or
# walking very long files.
with open(src, "rb") as f:
f.seek(0, 2)
end = f.tell()
if not end:
return ""
chunk = 8192
tail = b""
pos = end
while pos > 0 and tail.count(b"\n") < 2:
pos = max(0, pos - chunk)
f.seek(pos)
tail = f.read(end - pos)
# Last non-empty line of tail
for line in reversed(tail.splitlines()):
if line.strip():
last_line = line
break
except OSError:
return ""
if not last_line:
return ""
try:
obj = json.loads(last_line)
except (json.JSONDecodeError, UnicodeDecodeError):
return ""
ts = obj.get("ts", "") or ""
# Write through the cache (best-effort; never raise).
if ts and meta_path.parent.exists():
try:
new_meta = dict(cached) if isinstance(cached, dict) else {}
new_meta["last_active_at"] = ts
new_meta["_last_active_src"] = src.name
new_meta["_last_active_size"] = size
tmp = meta_path.with_name(meta_path.name + ".tmp")
with open(tmp, "w") as f:
json.dump(new_meta, f, indent=2)
os.replace(tmp, meta_path)
except OSError:
pass
return ts
def list_sessions() -> dict:
"""Return {sessions: [...], by_root: {...}} for the Web UI.
Each session entry carries is_subagent / parent_session_id / depth
so the UI can nest sub-agents under their parent.
Layout (post-flatten): ~/.claude-audit/<sid>/ for parents,
~/.claude-audit/<sid>__agent__<id>/ for sub-agents (siblings, not
nested). Sorting/grouping by date is the frontend's job — we just
expose started_at and last_active_at.
"""
sessions: list[dict] = []
if not AUDIT_DIR.exists():
return {"sessions": sessions}
# First pass: collect non-subagent (parent) dirs so we can resolve
# cwd inheritance for sub-agents.
parent_meta_cache: dict[str, dict] = {}
for session_dir in sorted(AUDIT_DIR.iterdir()):
if not session_dir.is_dir():
continue
sid = session_dir.name
if sid.startswith("_") or sid.startswith("."):
continue
# Old date-partitioned dirs still on disk during transition look
# like "20YY-MM-DD". Skip them — the migration script handles them.
if sid.startswith("20") and len(sid) == 10 and sid[4] == "-":
continue
if SUBAGENT_SEP in sid:
continue # collected in the second pass below
meta = _load_meta(session_dir, sid)
parent_meta_cache[sid] = meta
for session_dir in sorted(AUDIT_DIR.iterdir()):
if not session_dir.is_dir():
continue
sid = session_dir.name
if sid.startswith("_") or sid.startswith("."):
continue
if sid.startswith("20") and len(sid) == 10 and sid[4] == "-":
continue
summary = _load_summary(session_dir)
count = _count_events(session_dir)
status = "active" if _is_session_active(session_dir) else "completed"
last_active = _last_active_iso(session_dir)
sub_meta = _load_subagent_meta(session_dir)
is_subagent = sub_meta is not None or SUBAGENT_SEP in sid
env = _load_env(session_dir)
if is_subagent:
parent_name = sid.rsplit(SUBAGENT_SEP, 1)[0] if SUBAGENT_SEP in sid else ""
agent_id = (sub_meta or {}).get("agent_id", "") or sid.rsplit(SUBAGENT_SEP, 1)[-1]
agent_type = (sub_meta or {}).get("agent_type", "")
description = (sub_meta or {}).get("description", "")
start_ts = (sub_meta or {}).get("start_ts", "") or summary.get("start_ts", "")
depth = sid.count(SUBAGENT_SEP)
root_name = sid.split(SUBAGENT_SEP, 1)[0]
root_meta = parent_meta_cache.get(root_name, {})
root_env = _load_env(AUDIT_DIR / root_name) if (AUDIT_DIR / root_name).is_dir() else {}
sessions.append({
"id": sid,
"prompt": description,
"model": "",
"cwd": root_meta.get("cwd", ""),
"count": count,
"turns": summary.get("num_tool_calls", 0),
"cost": None,
"duration_ms": summary.get("duration_ms", 0),
"status": status,
"started_at": start_ts,
"last_active_at": last_active,
"is_subagent": True,
"parent_session_id": parent_name,
"root_session_id": root_name,
"agent_id": agent_id,
"agent_type": agent_type,
"depth": depth,
"reason": summary.get("reason", ""),
# Inherit mode from root session — a sub-agent of a
# scripted run is itself scripted for filtering purposes.
"mode": detect_mode(root_env or env),
})
else:
meta = parent_meta_cache.get(sid, {})
model = summary.get("model", "") or meta.get("model", "")
cost = compute_cost(model, summary.get("usage", {}))
sessions.append({
"id": sid,
"prompt": meta.get("prompt", ""),
"model": model,
"cwd": meta.get("cwd", ""),
"count": count,
"turns": summary.get("num_turns", 0),
"cost": cost,
"duration_ms": summary.get("duration_ms", 0),
"status": status,
"started_at": meta.get("started_at", ""),
"last_active_at": last_active,
"is_subagent": False,
"parent_session_id": "",
"root_session_id": sid,
"depth": 0,
"mode": detect_mode(env),
})
return {"sessions": sessions}
def _load_meta(session_dir: Path, sid: str) -> dict:
"""Return metadata.json if parseable, otherwise extract from events.
metadata.json may exist but only contain the last_active_at cache
without the SessionStart fields (if _last_active_iso ran before
anyone else populated the file). In that case we still need to
extract from events to recover prompt/model/cwd.
Concurrent-write tolerance: the file can be rewritten under us by
either _last_active_iso (atomic via os.replace) or the older
non-atomic path in _extract_meta_from_events. Any parse failure
falls through to the event-based extractor.
"""
meta_path = session_dir / "metadata.json"
if meta_path.exists():
try:
with open(meta_path) as f:
cached = json.load(f)
# Only trust the cache if it carries the real metadata,
# not just the last_active_at helper fields.
if isinstance(cached, dict) and (
cached.get("model") or cached.get("prompt") or cached.get("cwd")
):
return cached
except (OSError, json.JSONDecodeError):
pass
# Fallback: extract from events (also covers the "only last_active"
# shell case created by _last_active_iso on a session that has not
# yet had its real metadata extracted).
return _extract_meta_from_events(session_dir, sid)
def _extract_meta_from_events(session_dir: Path, sid: str) -> dict:
"""Walk the audit log(s) for the SessionStart + first UserPromptSubmit.
For resumed sessions we must read BOTH the .gz (original SessionStart
lives there) and the .jsonl (resume delta). Reading only one would
miss either the start event or any newer prompt.
"""
meta = {"prompt": "", "model": "", "cwd": "", "started_at": ""}
# _audit_sources returns gz first then jsonl, chronological for our
# purposes — which is what we want here (earliest SessionStart wins).
sources = _audit_sources(session_dir)
if not sources:
return meta
for path in sources:
opener = gzip.open if path.name.endswith(".gz") else open
try:
with opener(path, "rt", encoding="utf-8", errors="replace") as f:
for line in f:
try:
obj = json.loads(line)
except (json.JSONDecodeError, UnicodeDecodeError):
continue
d = obj.get("data", {}) if isinstance(obj.get("data"), dict) else {}
if obj.get("event") == "SessionStart":
if not meta["model"]:
meta["model"] = d.get("model", "") or ""
if not meta["cwd"]:
meta["cwd"] = d.get("cwd", "") or ""
if not meta["started_at"]:
meta["started_at"] = obj.get("ts", "") or ""
elif obj.get("event") == "UserPromptSubmit":
prompt = (d.get("prompt", "") or "")[:200]
if prompt and not meta["prompt"]:
meta["prompt"] = prompt
if meta["model"] and meta["prompt"]:
break
except Exception:
continue
if meta["model"] and meta["prompt"]:
break
# Persist so we don't re-parse next time. Merge with any cache that
# _last_active_iso already dropped in — preserve its fields.
if meta.get("model") or meta.get("prompt"):
meta_path = session_dir / "metadata.json"
merged = {}
if meta_path.exists():
try:
with open(meta_path) as f:
existing = json.load(f)
if isinstance(existing, dict):
merged = dict(existing)
except (OSError, json.JSONDecodeError):
pass
for k, v in meta.items():
if v and not merged.get(k):
merged[k] = v
# Atomic write — protects concurrent readers from mid-write tearing.
try:
tmp = meta_path.with_name(meta_path.name + ".tmp")
with open(tmp, "w") as f:
json.dump(merged, f, ensure_ascii=False, indent=2)
os.replace(tmp, meta_path)
except OSError:
pass
return merged
return meta
# Known third-party proxy hostnames → canonical provider name. Matched by
# substring against the netloc of ANTHROPIC_BASE_URL (captured at hook time
# into <session>/env.json). Keep this short — when the host is not matched
# we fall back to the raw host for display.
PROVIDER_HOSTS: list[tuple[str, str]] = [
("moonshot.cn", "moonshot"),
("moonshot.ai", "moonshot"),
("kimi.moonshot", "moonshot"),
("z.ai", "zhipu"),
("bigmodel.cn", "zhipu"),
("dashscope.aliyuncs", "qwen"),
("dashscope-intl", "qwen"),
("deepseek.com", "deepseek"),
("api.openai.com", "openai"),
("bedrock-runtime", "bedrock"),
("bedrock.", "bedrock"),
("aiplatform.google", "vertex"),
("api.x.ai", "xai"),
("api.anthropic.com", "anthropic"),
]
def _host_of(url: str) -> str:
if not url:
return ""
u = url.strip()
# Strip scheme
if "://" in u:
u = u.split("://", 1)[1]
# Keep only netloc (drop path/query)
for sep in ("/", "?", "#"):
if sep in u:
u = u.split(sep, 1)[0]
# Drop port
if ":" in u:
u = u.split(":", 1)[0]
return u.lower()
def _load_env(session_dir: Path) -> dict:
"""Return env.json content (ANTHROPIC_BASE_URL / Bedrock / Vertex flags).
Written by hook.sh on the first event of each session. Missing file
means a pre-env-capture session (historical) — caller falls back to
model-name heuristics in that case.
"""
p = session_dir / "env.json"
if not p.exists():
return {}
try:
with open(p) as f:
return json.load(f) or {}
except Exception:
return {}
def detect_mode(env: dict | None = None) -> str:
"""Return "scripted" or "interactive" based on env.json flags.
Scripted = the parent Claude process was invoked with `-p` / `--print`
(headless). Interactive = anything else. Historical sessions without
env.json default to "interactive" (most common, and we do not want to
hide them retroactively).
"""
env = env or {}
if env.get("is_headless") is True:
return "scripted"
return "interactive"
def detect_provider(model: str, env: dict | None = None) -> str:
"""Infer the API provider, preferring env-based signals over model name.
Priority:
1. env.json flags: use_bedrock / use_vertex → bedrock / vertex
2. env.json anthropic_base_url → known-host map or raw host
3. model name prefix (historical sessions with no env.json)
"""
env = env or {}
if str(env.get("use_bedrock", "")).lower() in ("1", "true", "yes"):
return "bedrock"
if str(env.get("use_vertex", "")).lower() in ("1", "true", "yes"):
return "vertex"
base_url = env.get("anthropic_base_url", "") or ""
host = _host_of(base_url)
if host:
for needle, name in PROVIDER_HOSTS:
if needle in host:
return name
# Unmapped third-party host — return the host as the provider label
# so the UI still renders something meaningful (e.g. "api.foo.com").
return host
# Historical fallback: model-name prefix heuristic
if not model:
return "unknown"
m = model.lower().strip()
if m == "<synthetic>":
return "synthetic"
if m.startswith("anthropic.") or ".anthropic." in m:
return "bedrock"
if "@" in m and "claude-" in m:
return "vertex"
if m.startswith("claude-"):
return "anthropic"
if m.startswith("qwen"): return "qwen"
if m.startswith("glm"): return "zhipu"
if m.startswith("kimi") or m.startswith("moonshot"): return "moonshot"
if m.startswith("deepseek"): return "deepseek"
if m.startswith("gpt-") or m.startswith("o1") or m.startswith("o3") or m.startswith("o4"):
return "openai"
if m.startswith("gemini"): return "gemini"
if m.startswith("grok"): return "xai"
return "other"
def build_stats(exclude_scripted: bool = False) -> dict:
"""Aggregate across all main sessions for the Dashboard view.
Sub-agent directories are skipped — their token/cost usage is already
captured in the parent session's transcript, so counting them would
double-count.
When `exclude_scripted=True`, sessions whose env.json marks them as
headless (claude -p invocation) are omitted from every aggregate.
The frontend passes this flag when its scripted-filter toggle is off.
Returns:
totals: totals across all sessions (session count, cost, tokens,
duration). Tokens are split into input / output / cache_read /
cache_creation (5m+1h combined).
by_model: per-model aggregates (same fields as totals minus duration).
by_date: per-day aggregates (sorted ascending), for trend chart.
top_by_cost: top 20 sessions by cost.
top_by_ctx: top 20 sessions by ctx_peak_pct.
"""
from datetime import datetime as _dt, timezone as _tz, timedelta as _td
now_utc = _dt.now(_tz.utc)
def _parse_ts(s):
if not isinstance(s, str):
return None
try:
return _dt.fromisoformat(s.replace("Z", "+00:00"))
except (ValueError, TypeError, AttributeError):
return None
totals = {
"sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"duration_ms": 0, "turns": 0,
# Rolling windows, populated below as we iterate.
"last_1h_cost": 0.0,
"last_24h_cost": 0.0,
"last_7d_cost": 0.0,
}
by_model: dict[str, dict] = {}
by_provider: dict[str, dict] = {}
by_date: dict[str, dict] = {}
by_hour: dict[str, dict] = {} # "YYYY-MM-DDTHH:00Z" → agg
by_week: dict[str, dict] = {} # ISO week key "YYYY-Www" → agg
all_sessions: list[dict] = []
if not AUDIT_DIR.exists():
return {"totals": totals, "by_model": [], "by_provider": [],
"by_date": [], "by_hour": [], "by_week": [],
"top_by_cost": [], "top_by_ctx": [], "top_cost_windows": []}
for session_dir in sorted(AUDIT_DIR.iterdir()):
if not session_dir.is_dir():
continue
sid = session_dir.name
if sid.startswith("_") or sid.startswith("."):
continue
# Old date-partitioned dirs left over during transition — skip.
if sid.startswith("20") and len(sid) == 10 and sid[4] == "-":
continue
# Sub-agent directories — their usage lives in the parent's transcript.
if SUBAGENT_SEP in sid:
continue
summary = _load_summary(session_dir)
if not summary:
continue
usage = summary.get("usage", {}) or {}
inp = int(usage.get("input_tokens", 0) or 0)
out = int(usage.get("output_tokens", 0) or 0)
cr = int(usage.get("cache_read_input_tokens", 0) or 0)
cw = int(usage.get("cache_creation_input_tokens", 0) or 0)
if not cw:
cw = (int(usage.get("cache_creation_5m_tokens", 0) or 0)
+ int(usage.get("cache_creation_1h_tokens", 0) or 0))
meta = _load_meta(session_dir, sid)
env = _load_env(session_dir)
if exclude_scripted and detect_mode(env) == "scripted":
continue
model = summary.get("model", "") or meta.get("model", "") or "unknown"
provider = detect_provider(model, env)
cost = compute_cost(model, usage)
dur = int(summary.get("duration_ms", 0) or 0)
turns = int(summary.get("num_turns", 0) or 0)
# calls/hr normalised from turns over duration. Clamp tiny durations
# to 0 to avoid extreme outliers from 0/near-0 ms sessions.
calls_per_hr = (turns * 3_600_000.0 / dur) if dur >= 1000 else 0.0
ctx = compute_ctx(model, summary.get("ctx_peak_tokens", 0))
# Bucket the session into a date. With the flat layout this comes
# from started_at (or last_active_at as a fallback) — there is no
# date in the path. Keep the YYYY-MM-DD slice for the trend chart.
date_bucket = (meta.get("started_at", "") or _last_active_iso(session_dir))[:10]
if not date_bucket:
date_bucket = "unknown"
totals["sessions"] += 1
totals["cost"] += cost
totals["input_tokens"] += inp
totals["output_tokens"] += out
totals["cache_read_tokens"] += cr
totals["cache_creation_tokens"] += cw
totals["duration_ms"] += dur
totals["turns"] += turns
bm = by_model.setdefault(model, {
"model": model, "provider": provider, "sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"turns": 0, "duration_ms": 0,
})
bm["sessions"] += 1
bm["cost"] += cost
bm["input_tokens"] += inp
bm["output_tokens"] += out
bm["cache_read_tokens"] += cr
bm["cache_creation_tokens"] += cw
bm["turns"] += turns
bm["duration_ms"] += dur
bp = by_provider.setdefault(provider, {
"provider": provider, "sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"turns": 0, "duration_ms": 0,
})
bp["sessions"] += 1
bp["cost"] += cost
bp["input_tokens"] += inp
bp["output_tokens"] += out
bp["cache_read_tokens"] += cr
bp["cache_creation_tokens"] += cw
bp["turns"] += turns
bp["duration_ms"] += dur
bd = by_date.setdefault(date_bucket, {
"date": date_bucket, "sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"turns": 0, "duration_ms": 0,
})
bd["sessions"] += 1
bd["cost"] += cost
bd["input_tokens"] += inp
bd["output_tokens"] += out
bd["cache_read_tokens"] += cr
bd["cache_creation_tokens"] += cw
bd["turns"] += turns
bd["duration_ms"] += dur
# Hour- and week-level buckets. We attribute the WHOLE session's
# cost to the hour/week it started — we do not have per-event
# cost data to split across hours for long-running sessions, so
# this is a documented approximation (same as by_date).
started_at = meta.get("started_at", "") or _last_active_iso(session_dir)
bucket_dt = _parse_ts(started_at)
if bucket_dt is not None:
hour_key = bucket_dt.strftime("%Y-%m-%dT%H:00Z")
bh = by_hour.setdefault(hour_key, {
"hour": hour_key, "sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"turns": 0, "duration_ms": 0,
})
bh["sessions"] += 1
bh["cost"] += cost
bh["input_tokens"] += inp
bh["output_tokens"] += out
bh["cache_read_tokens"] += cr
bh["cache_creation_tokens"] += cw
bh["turns"] += turns
bh["duration_ms"] += dur
# ISO week: year + "-W" + 2-digit week. isocalendar() returns
# a tuple; use .isoformat() friendly key.
iso_year, iso_week, _ = bucket_dt.isocalendar()
week_key = f"{iso_year}-W{iso_week:02d}"
bw = by_week.setdefault(week_key, {
"week": week_key, "sessions": 0, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0,
"cache_read_tokens": 0, "cache_creation_tokens": 0,
"turns": 0, "duration_ms": 0,
})
bw["sessions"] += 1
bw["cost"] += cost
bw["input_tokens"] += inp
bw["output_tokens"] += out
bw["cache_read_tokens"] += cr
bw["cache_creation_tokens"] += cw
bw["turns"] += turns
bw["duration_ms"] += dur
# Rolling totals: attribute to "last N" windows if the session
# started within that window. Same coarse-attribution caveat.
age = now_utc - bucket_dt
if age <= _td(hours=1):
totals["last_1h_cost"] += cost
if age <= _td(hours=24):
totals["last_24h_cost"] += cost
if age <= _td(days=7):
totals["last_7d_cost"] += cost
all_sessions.append({
"id": sid,
"date": date_bucket,
"model": model,
"provider": provider,
"mode": detect_mode(env),
"cost": round(cost, 4),
"turns": turns,
"duration_ms": dur,
"calls_per_hr": round(calls_per_hr, 1),
"prompt": meta.get("prompt", "")[:200],
"cwd": meta.get("cwd", ""),
"ctx_peak_pct": ctx["ctx_peak_pct"],
"ctx_peak_tokens": ctx["ctx_peak_tokens"],
"ctx_window": ctx["ctx_window"],
})
# Round totals for cleaner JSON; compute calls/hr from aggregated duration
def _cph(turns: int, dur_ms: int) -> float:
return round(turns * 3_600_000.0 / dur_ms, 1) if dur_ms >= 1000 else 0.0
totals["cost"] = round(totals["cost"], 4)
totals["calls_per_hr"] = _cph(totals["turns"], totals["duration_ms"])
for m in by_model.values():
m["cost"] = round(m["cost"], 4)
m["calls_per_hr"] = _cph(m["turns"], m["duration_ms"])
for p in by_provider.values():
p["cost"] = round(p["cost"], 4)
p["calls_per_hr"] = _cph(p["turns"], p["duration_ms"])
for d in by_date.values():
d["cost"] = round(d["cost"], 4)
d["calls_per_hr"] = _cph(d["turns"], d["duration_ms"])
for h in by_hour.values():
h["cost"] = round(h["cost"], 4)
h["calls_per_hr"] = _cph(h["turns"], h["duration_ms"])
for w in by_week.values():
w["cost"] = round(w["cost"], 4)
w["calls_per_hr"] = _cph(w["turns"], w["duration_ms"])
totals["last_1h_cost"] = round(totals["last_1h_cost"], 4)
totals["last_24h_cost"] = round(totals["last_24h_cost"], 4)
totals["last_7d_cost"] = round(totals["last_7d_cost"], 4)
# Trim to display windows — last 30 days / last 72h / last 12 weeks.
# Ascending by key so the UI can plot left-to-right.
cutoff_day = (now_utc - _td(days=30)).strftime("%Y-%m-%d")
cutoff_hour = (now_utc - _td(hours=72)).strftime("%Y-%m-%dT%H:00Z")
by_date_list = sorted(
(d for d in by_date.values() if d["date"] >= cutoff_day),
key=lambda x: x["date"],
)
by_hour_list = sorted(
(h for h in by_hour.values() if h["hour"] >= cutoff_hour),
key=lambda x: x["hour"],
)
by_week_list = sorted(by_week.values(), key=lambda x: x["week"])[-12:]
by_model_list = sorted(by_model.values(), key=lambda x: -x["cost"])
by_provider_list = sorted(by_provider.values(), key=lambda x: -x["cost"])
top_by_cost = sorted(all_sessions, key=lambda x: -x["cost"])[:20]
top_by_ctx = sorted(all_sessions, key=lambda x: -x["ctx_peak_pct"])[:20]
# Most expensive hours: catches "many cheap sessions add up" which
# top_by_cost (individual max) misses.
top_cost_windows = sorted(
by_hour.values(), key=lambda x: -x["cost"],
)[:10]
# Only include hours with non-trivial cost to avoid a list of zeros.
top_cost_windows = [h for h in top_cost_windows if h["cost"] >= 0.001]
return {
"totals": totals,
"by_model": by_model_list,
"by_provider": by_provider_list,
"by_date": by_date_list,
"by_hour": by_hour_list,
"by_week": by_week_list,
"top_by_cost": top_by_cost,
"top_by_ctx": top_by_ctx,
"top_cost_windows": top_cost_windows,
}
def _load_summary(session_dir: Path) -> dict:
summary_path = session_dir / "summary.json"
if summary_path.exists():
with open(summary_path) as f:
return json.load(f)
return {}
def _count_events(session_dir: Path) -> int:
"""Sum events across all audit sources (handles resumed sessions)."""
count = 0
for path in _audit_sources(session_dir):
opener = gzip.open if path.name.endswith(".gz") else open
try:
with opener(path, "rt", encoding="utf-8", errors="replace") as f:
for _ in f:
count += 1
except Exception:
continue
return count
def _audit_sources(session_dir: Path) -> list[Path]:
"""Return the audit log files for a session in chronological order.
A "resumed" session has BOTH audit.jsonl.gz (history from a previous
SessionEnd) AND audit.jsonl (events since the resume). Always read
.gz first when present so the timeline reads start-to-now even after
one or more resumes. The next SessionEnd will merge them back into
a single .gz; until then we just concatenate at read time.
"""
sources = []
gz = session_dir / "audit.jsonl.gz"
jsonl = session_dir / "audit.jsonl"
if gz.exists():
sources.append(gz)
if jsonl.exists():
sources.append(jsonl)
return sources