forked from splunk/token-meter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeter.py
More file actions
5200 lines (4737 loc) · 223 KB
/
Copy pathmeter.py
File metadata and controls
5200 lines (4737 loc) · 223 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
"""
Token Meter - a live cost and efficiency instrument for Claude Code and Codex.
Tails local agent logs, parses each execution as it lands, and serves a
localhost dashboard over SSE with Current and Global views. Stdlib only; nothing
leaves your machine.
python3 meter.py -> http://localhost:8722
Claude correctness note: one API response (message.id) can be split across
several JSONL lines, one per content block, and each line repeats the same usage
block. Claude parsing dedupes by message.id so costs are not double-counted.
Codex uses token_count events instead; those are already one usage slice.
"""
import calendar
import datetime
import glob
import hashlib
import html
import json
import os
import queue
import re
import secrets
import shlex
import shutil
import subprocess
import time
import threading
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, quote, urlparse
CLAUDE_PROJECTS = os.path.expanduser("~/.claude/projects")
CLAUDE_DESKTOP_DATA_ROOTS = [os.path.expanduser("~/Library/Application Support/Claude")]
CLAUDE_DESKTOP_SESSIONS = os.path.join(CLAUDE_DESKTOP_DATA_ROOTS[0], "claude-code-sessions")
CLAUDE_SETTINGS = os.path.expanduser("~/.claude/settings.json")
CLAUDE_ROOT_CONFIG = os.path.expanduser("~/.claude.json")
CODEX_SESSIONS = os.path.expanduser("~/.codex/sessions")
CODEX_INDEX = os.path.expanduser("~/.codex/session_index.jsonl")
CODEX_CONFIG = os.path.expanduser("~/.codex/config.toml")
TOKEN_METER_SETTINGS = os.path.expanduser(
os.environ.get("TOKEN_METER_SETTINGS", "~/.token-meter/settings.json")
)
PORT = 8722
DEFAULT_FRUSTRATION_TERMS = [
"fuck", "fck", "fucked", "fucking", "shit", "shitty", "bullshit",
"idiot", "stupid", "useless", "crap", "damn", "wtf",
]
MAX_FRUSTRATION_TERMS = 64
MAX_FRUSTRATION_TERM_LENGTH = 40
CLAUDE_PRICE = {
"claude-opus-4-8": {"input": 15.0, "output": 75.0, "cache_write": 18.75, "cache_read": 1.50},
"claude-fable-5": {"input": 15.0, "output": 75.0, "cache_write": 18.75, "cache_read": 1.50},
# Introductory pricing through 2026-08-31; standard pricing is $3/$15 afterward.
"claude-sonnet-5": {"input": 2.0, "output": 10.0, "cache_write": 2.50, "cache_read": 0.20},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_write": 3.75, "cache_read": 0.30},
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_write": 1.25, "cache_read": 0.10},
}
# Public OpenAI API pricing, per 1M tokens. Codex subscription accounting can
# differ by plan, so the UI labels OpenAI/Codex costs as API-rate estimates.
OPENAI_PRICE = {
# GPT-5.6 Sol / flagship pricing. Terra and Luna use lower rates.
"gpt-5.6": {"input": 5.0, "output": 30.0, "cache_write": 6.25, "cache_read": 0.50},
"gpt-5.5": {"input": 5.0, "output": 30.0, "cache_write": 0.0, "cache_read": 0.50},
"gpt-5.4": {"input": 2.50, "output": 15.0, "cache_write": 0.0, "cache_read": 0.25},
"gpt-5.4-mini": {"input": 0.75, "output": 4.50, "cache_write": 0.0, "cache_read": 0.075},
}
DEFAULT_CLAUDE_MODEL = "claude-opus-4-8"
DEFAULT_OPENAI_MODEL = "gpt-5.5"
CHARS_PER_TOKEN = 4
TRACE_LIMIT = 220
EXEC_LIMIT = 180
MENUBAR_CONTEXT_SOFT_PCT = 0.65
MENUBAR_CONTEXT_WATCH_PCT = 0.70
MENUBAR_CONTEXT_INTERVENE_PCT = 0.85
MENUBAR_COST_SPIKE = 0.50
LOW_YIELD_RATIO = 0.005
LOW_YIELD_COST = 0.05
LOW_YIELD_CONTEXT_PCT = 0.25
LOW_YIELD_INPUT_TOKENS = 60000
TOOL_OVERSIZED_TOKENS = 8000
PLUGIN_ID_RE = re.compile(r"^[A-Za-z0-9_.@:/-]{1,180}$")
SKILL_PATH_RE = re.compile(r"(?:^|[/\\])([^/\\\s'\"]+)[/\\]SKILL\.md(?:\b|$)", re.IGNORECASE)
DATA_URL_RE = re.compile(r"data:image/[^;\s]+;base64,[A-Za-z0-9+/=]+")
BASE64_FIELD_RE = re.compile(r'("(?:data|image_url)"\s*:\s*")([A-Za-z0-9+/=]{512,})(")')
subscribers, subscribers_lock = [], threading.Lock()
STATE = {}
_xsess = {"data": None, "at": 0.0}
_XSESS_TTL = 15.0
_XSESS_LIVE_REFRESH_S = 2.0
_summary_cache = {}
_ACTION_TOKEN = secrets.token_urlsafe(24)
AGENT_ACCESS_SERVER = "tokenmeter"
AGENT_CURRENT_MAX_AGE_S = 6 * 60 * 60
def parse_iso(ts):
# Logs are UTC (trailing Z). calendar.timegm treats the struct as UTC, so
# idle/elapsed line up with time.time().
try:
return calendar.timegm(time.strptime((ts or "").split(".")[0], "%Y-%m-%dT%H:%M:%S"))
except Exception:
return None
def local_dt(ts):
return time.strftime("%Y-%m-%d %I:%M:%S %p", time.localtime(ts)).lower() if ts else ""
def local_tm(ts):
return time.strftime("%H:%M:%S", time.localtime(ts)) if ts else ""
def duration_label(seconds):
seconds = int(seconds or 0)
if seconds < 60:
return f"{seconds}s"
minutes, sec = divmod(seconds, 60)
if minutes < 60:
return f"{minutes}m {sec:02d}s"
hours, minutes = divmod(minutes, 60)
return f"{hours}h {minutes:02d}m"
def _merge_execution_intervals(intervals):
"""Return wall-active seconds after collapsing overlapping execution windows."""
clean = sorted(
(float(start), float(end))
for start, end in intervals
if start is not None and end is not None and float(end) > float(start)
)
merged = []
for start, end in clean:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return sum(end - start for start, end in merged)
def _claude_user_prompt(obj):
if obj.get("type") != "user":
return False
msg = obj.get("message") if isinstance(obj.get("message"), dict) else {}
content = msg.get("content")
if isinstance(content, str):
return bool(content.strip())
if not isinstance(content, list):
return False
return any(
isinstance(block, dict)
and block.get("type") == "text"
and str(block.get("text") or "").strip()
for block in content
)
def execution_timing(provider, objs):
"""Build trace-backed active execution time, excluding idle gaps."""
intervals = []
reported = observed = 0
open_start = open_last = None
for obj in objs:
ts = parse_iso(obj.get("timestamp", ""))
if provider == "claude":
if _claude_user_prompt(obj):
if open_start and open_last and open_last > open_start:
intervals.append((open_start, open_last))
observed += 1
open_start = ts or open_start
open_last = ts or open_last
continue
if obj.get("type") != "system" or obj.get("subtype") != "turn_duration":
if open_start and ts and obj.get("type") == "assistant":
open_last = ts if open_last is None else max(open_last, ts)
continue
duration_ms = obj.get("durationMs")
try:
duration_ms = float(duration_ms or 0)
except (TypeError, ValueError):
duration_ms = 0
if ts and duration_ms > 0:
intervals.append((ts - duration_ms / 1000.0, ts))
reported += 1
elif open_start and ts and ts > open_start:
intervals.append((open_start, ts))
observed += 1
open_start = open_last = None
continue
payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}
ptype = payload.get("type")
if ptype == "task_started":
if open_start and open_last and open_last > open_start:
intervals.append((open_start, open_last))
observed += 1
open_start = ts or open_start
open_last = ts or open_last
continue
if ptype != "task_complete":
if open_start and ts:
open_last = ts if open_last is None else max(open_last, ts)
continue
duration_ms = payload.get("duration_ms")
try:
duration_ms = float(duration_ms or 0)
except (TypeError, ValueError):
duration_ms = 0
if ts and duration_ms > 0:
intervals.append((ts - duration_ms / 1000.0, ts))
reported += 1
elif open_start and ts and ts > open_start:
intervals.append((open_start, ts))
observed += 1
open_start = open_last = None
if open_start and open_last and open_last > open_start:
intervals.append((open_start, open_last))
observed += 1
duration_s = _merge_execution_intervals(intervals)
if reported and observed:
basis = "reported + observed"
elif reported:
basis = "reported"
elif observed:
basis = "observed"
else:
basis = "unavailable"
return {
"duration_s": duration_s,
"available": duration_s > 0,
"reported_executions": reported,
"observed_executions": observed,
"execution_count": reported + observed,
"basis": basis,
}
def load(path):
out = []
if not path:
return out
try:
for line in open(path, encoding="utf-8").read().splitlines():
if not line.strip():
continue
try:
out.append(json.loads(line))
except Exception:
pass
except FileNotFoundError:
pass
return out
def load_json(path, default=None):
try:
with open(path, encoding="utf-8") as fh:
value = json.load(fh)
return value
except (FileNotFoundError, json.JSONDecodeError, OSError):
return {} if default is None else default
def atomic_write_text(path, text):
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
tmp = os.path.join(directory, f".{os.path.basename(path)}.token-meter-{os.getpid()}")
mode = None
try:
mode = os.stat(path).st_mode & 0o777
except OSError:
pass
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(text)
fh.flush()
os.fsync(fh.fileno())
if mode is not None:
os.chmod(tmp, mode)
os.replace(tmp, path)
def normalize_frustration_terms(values):
"""Normalize a user-editable term list while preserving display order."""
if isinstance(values, str):
values = re.split(r"[,\n]", values)
if not isinstance(values, list):
raise ValueError("Frustration terms must be a list or comma-separated text.")
normalized = []
seen = set()
for value in values:
term = " ".join(str(value or "").strip().lower().split())
if not term:
continue
if len(term) > MAX_FRUSTRATION_TERM_LENGTH:
raise ValueError(f"Each frustration term must be {MAX_FRUSTRATION_TERM_LENGTH} characters or fewer.")
if any(ord(char) < 32 for char in term):
raise ValueError("Frustration terms cannot contain control characters.")
if term not in seen:
normalized.append(term)
seen.add(term)
if len(normalized) > MAX_FRUSTRATION_TERMS:
raise ValueError(f"Use at most {MAX_FRUSTRATION_TERMS} frustration terms.")
return normalized
def frustration_settings(path=None):
path = path or TOKEN_METER_SETTINGS
settings = load_json(path, {})
if not isinstance(settings, dict):
settings = {}
if "frustration_terms" not in settings:
terms = list(DEFAULT_FRUSTRATION_TERMS)
else:
try:
terms = normalize_frustration_terms(settings.get("frustration_terms"))
except ValueError:
terms = list(DEFAULT_FRUSTRATION_TERMS)
return {
"terms": terms,
"defaults": list(DEFAULT_FRUSTRATION_TERMS),
"max_terms": MAX_FRUSTRATION_TERMS,
}
def set_frustration_terms(values, path=None):
"""Persist the machine-wide frustration lexicon used by every session."""
path = path or TOKEN_METER_SETTINGS
try:
terms = normalize_frustration_terms(values)
except ValueError as error:
return {"ok": False, "error": str(error)}
settings = load_json(path, {})
if not isinstance(settings, dict):
settings = {}
settings["frustration_terms"] = terms
try:
atomic_write_text(path, json.dumps(settings, indent=2, ensure_ascii=False) + "\n")
except OSError as error:
return {"ok": False, "error": f"Token Meter could not save settings: {error}"}
return {
"ok": True,
"terms": terms,
"defaults": list(DEFAULT_FRUSTRATION_TERMS),
"max_terms": MAX_FRUSTRATION_TERMS,
}
def toml_named_sections(path, table):
"""Read simple enabled state from named TOML sections without a TOML dependency."""
try:
with open(path, encoding="utf-8") as fh:
text = fh.read()
except OSError:
return {}
header = re.compile(rf'^\[{re.escape(table)}\.(?:"([^"]+)"|([^\.\]]+))\]\s*$', re.MULTILINE)
matches = list(header.finditer(text))
result = {}
for index, match in enumerate(matches):
name = (match.group(1) or match.group(2) or "").strip()
end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
body = text[match.end():end]
enabled_match = re.search(r'^\s*enabled\s*=\s*(true|false)\s*$', body, re.MULTILINE | re.IGNORECASE)
result[name] = {
"enabled": enabled_match is None or enabled_match.group(1).lower() == "true",
"start": match.start(), "body_start": match.end(), "end": end,
}
return result
def safe_mtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
def home_shorten(path):
home = os.path.expanduser("~")
return path.replace(home, "~", 1) if path and path.startswith(home) else path
def decode_claude_project(name):
user = os.environ.get("USER", "")
prefix = "-Users-" + user
if user and name.startswith(prefix):
name = "~" + name[len(prefix):]
return name.strip("-").replace("-", "/").replace("~/", "~/")
def claude_trace_cwd(path, max_lines=120):
"""Prefer Claude's recorded cwd over its lossy hyphen-encoded folder name."""
try:
with open(path, encoding="utf-8") as fh:
for index, line in enumerate(fh):
if index >= max_lines:
break
if not line.strip():
continue
try:
row = json.loads(line)
except (TypeError, json.JSONDecodeError):
continue
cwd = row.get("cwd") if isinstance(row, dict) else None
if isinstance(cwd, str) and cwd.strip():
return cwd.strip()
except OSError:
pass
return ""
def codex_id_from_path(path, meta=None):
if meta and meta.get("session_id"):
return meta["session_id"]
base = os.path.basename(path).rsplit(".", 1)[0]
match = re.search(r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})", base)
return match.group(1) if match else base
def normalize_dynamic_tools(dynamic_tools):
"""Flatten old function arrays and newer namespace-grouped tool catalogs."""
out = []
for item in dynamic_tools or []:
if not isinstance(item, dict):
out.append({
"namespace": "unknown", "name": str(item) or "?", "kind": "tool",
"defer_loading": False, "definition_tokens": 0,
})
continue
children = item.get("tools")
rows = children if isinstance(children, list) else [item]
parent_namespace = item.get("namespace") or item.get("name") or "unknown"
parent_deferred = bool(item.get("deferLoading"))
for child in rows:
if not isinstance(child, dict):
child = {"name": str(child)}
name = child.get("name") or "?"
namespace = child.get("namespace") or parent_namespace or "unknown"
raw_identity = name
if name.startswith("mcp__"):
ident = tool_identity(name)
namespace = ident["namespace"]
kind = "mcp"
elif str(namespace).startswith("mcp__"):
parts = str(namespace).split("__")
namespace = parts[1] if len(parts) > 1 and parts[1] else "mcp"
raw_identity = f"mcp__{namespace}__{name}"
kind = "mcp"
else:
kind = "tool"
definition = {
"description": child.get("description") or "",
"inputSchema": child.get("inputSchema") or child.get("input_schema") or {},
}
out.append({
"namespace": namespace,
"name": raw_identity,
"kind": kind,
"defer_loading": bool(child.get("deferLoading", parent_deferred)),
"definition_tokens": len(json.dumps(definition, sort_keys=True)) // CHARS_PER_TOKEN,
})
return out[:240]
def catalog_counts(catalog):
advertised = len(catalog or [])
deferred = sum(1 for row in catalog or [] if row.get("defer_loading"))
return {"advertised": advertised, "eager": max(0, advertised - deferred), "deferred": deferred}
def codex_meta(path):
meta = {"session_id": None, "cwd": None, "model": None, "model_provider": None,
"tools_loaded": 0, "tools_eager": 0, "tools_deferred": 0,
"tool_catalog": [], "tool_namespaces": []}
try:
with open(path, encoding="utf-8") as fh:
for i, line in enumerate(fh):
if i > 120:
break
if not line.strip():
continue
try:
obj = json.loads(line)
except Exception:
continue
payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}
if obj.get("type") == "session_meta":
meta["session_id"] = payload.get("session_id") or payload.get("id") or meta["session_id"]
meta["cwd"] = payload.get("cwd") or meta["cwd"]
meta["model_provider"] = payload.get("model_provider") or meta["model_provider"]
dynamic_tools = payload.get("dynamic_tools")
if isinstance(dynamic_tools, list):
meta["tool_catalog"] = normalize_dynamic_tools(dynamic_tools)
counts = catalog_counts(meta["tool_catalog"])
meta["tools_loaded"] = counts["advertised"]
meta["tools_eager"] = counts["eager"]
meta["tools_deferred"] = counts["deferred"]
meta["tool_namespaces"] = sorted(set(t["namespace"] for t in meta["tool_catalog"]))
elif obj.get("type") == "turn_context":
meta["cwd"] = payload.get("cwd") or meta["cwd"]
meta["model"] = payload.get("model") or meta["model"]
except FileNotFoundError:
pass
return meta
def codex_index():
idx = {}
for row in load(CODEX_INDEX):
sid = row.get("id")
if sid:
idx[sid] = row
return idx
def claude_desktop_metadata_paths(root=None):
if root:
return glob.glob(os.path.join(root, "**", "local_*.json"), recursive=True)
paths = []
for data_root in CLAUDE_DESKTOP_DATA_ROOTS:
paths.extend(glob.glob(os.path.join(data_root, "claude-code-sessions", "*", "*", "local_*.json")))
paths.extend(glob.glob(os.path.join(data_root, "local-agent-mode-sessions", "*", "*", "local_*.json")))
return paths
def claude_desktop_index(root=None):
"""Map Claude Desktop metadata onto CLI trace ids."""
idx = {}
for path in claude_desktop_metadata_paths(root):
try:
with open(path, encoding="utf-8") as fh:
row = json.load(fh)
except (FileNotFoundError, json.JSONDecodeError, OSError):
continue
if not isinstance(row, dict):
continue
cli_id = row.get("cliSessionId")
if not cli_id:
continue
title = compact_text(row.get("title") or "", 90)
if title.lower() in ("untitled", "untitled session"):
title = ""
source_kind = "agent" if f"{os.sep}local-agent-mode-sessions{os.sep}" in path else "project"
origin_cwd = row.get("originCwd") or ""
raw_cwd = origin_cwd or row.get("cwd") or ""
no_project = bool(source_kind == "agent" and not origin_cwd and os.path.basename(raw_cwd) == "outputs")
candidate = {
"client": "claude_desktop",
"label": "Claude Desktop",
"desktop_session_id": row.get("sessionId") or os.path.basename(path).rsplit(".", 1)[0],
"cli_session_id": cli_id,
"cwd": raw_cwd,
"project": "No project" if no_project else home_shorten(raw_cwd),
"source_kind": source_kind,
"title": title or None,
"model": row.get("model"),
"metadata_path": path,
"metadata_mtime": safe_mtime(path),
"last_activity_ms": int(row.get("lastActivityAt") or 0),
}
previous = idx.get(cli_id)
if not previous or (candidate["last_activity_ms"], candidate["metadata_mtime"]) > (
previous["last_activity_ms"], previous["metadata_mtime"]):
idx[cli_id] = candidate
return idx
def claude_local_agent_sources(desktop_idx):
sources = []
for desktop in desktop_idx.values():
if desktop.get("source_kind") != "agent":
continue
metadata_path = desktop.get("metadata_path") or ""
session_root = metadata_path.rsplit(".json", 1)[0]
trace_pattern = os.path.join(
session_root, ".claude", "projects", "*", f"{desktop.get('cli_session_id')}.jsonl"
)
for path in glob.glob(trace_pattern):
sources.append({
"provider": "claude", "client": "claude_desktop", "label": "Claude Desktop",
"id": desktop.get("cli_session_id"),
"desktop_session_id": desktop.get("desktop_session_id"),
"session": os.path.basename(path), "path": path,
"metadata_path": metadata_path,
"project": desktop.get("project") or "No project",
"mtime": max(safe_mtime(path), float(desktop.get("metadata_mtime") or 0)),
"title": desktop.get("title"), "model": desktop.get("model"),
"desktop_source_kind": "agent",
})
return sources
def all_session_sources():
sources = []
desktop_idx = claude_desktop_index()
known_paths = set()
for path in glob.glob(os.path.join(CLAUDE_PROJECTS, "*", "*.jsonl")):
sid = os.path.basename(path).rsplit(".", 1)[0]
project_raw = os.path.basename(os.path.dirname(path))
desktop = desktop_idx.get(sid) or {}
trace_cwd = claude_trace_cwd(path)
project = desktop.get("project") or home_shorten(trace_cwd) or decode_claude_project(project_raw)
source = {
"provider": "claude",
"client": desktop.get("client") or "claude_code",
"label": desktop.get("label") or "Claude Code",
"id": sid,
"desktop_session_id": desktop.get("desktop_session_id"),
"session": os.path.basename(path),
"path": path,
"metadata_path": desktop.get("metadata_path"),
"project": project,
"mtime": max(safe_mtime(path), float(desktop.get("metadata_mtime") or 0)),
"title": desktop.get("title"),
"model": desktop.get("model"),
}
sources.append(source)
known_paths.add(path)
for source in claude_local_agent_sources(desktop_idx):
if source["path"] not in known_paths:
sources.append(source)
known_paths.add(source["path"])
idx = codex_index()
for path in glob.glob(os.path.join(CODEX_SESSIONS, "*", "*", "*", "*.jsonl")):
meta = codex_meta(path)
sid = codex_id_from_path(path, meta)
cwd = meta.get("cwd") or os.path.dirname(path)
sources.append({
"provider": "codex",
"label": "Codex",
"id": sid,
"session": os.path.basename(path),
"path": path,
"project": home_shorten(cwd),
"mtime": safe_mtime(path),
"title": (idx.get(sid) or {}).get("thread_name"),
"model": meta.get("model") or DEFAULT_OPENAI_MODEL,
"tools_loaded": meta.get("tools_loaded") or 0,
"tools_eager": meta.get("tools_eager") or 0,
"tools_deferred": meta.get("tools_deferred") or 0,
"tool_catalog": meta.get("tool_catalog") or [],
"tool_namespaces": meta.get("tool_namespaces") or [],
})
return sources
def source_from_path(path):
for source in all_session_sources():
if source["path"] == path:
return source
if path and path.startswith(os.path.expanduser("~/.codex/")):
meta = codex_meta(path)
sid = codex_id_from_path(path, meta)
return {
"provider": "codex", "label": "Codex", "id": sid, "session": os.path.basename(path),
"path": path, "project": home_shorten(meta.get("cwd") or os.path.dirname(path)),
"mtime": safe_mtime(path), "title": None, "model": meta.get("model") or DEFAULT_OPENAI_MODEL,
"tools_loaded": meta.get("tools_loaded") or 0,
"tools_eager": meta.get("tools_eager") or 0,
"tools_deferred": meta.get("tools_deferred") or 0,
"tool_catalog": meta.get("tool_catalog") or [],
"tool_namespaces": meta.get("tool_namespaces") or [],
}
sid = os.path.basename(path).rsplit(".", 1)[0]
trace_cwd = claude_trace_cwd(path)
return {
"provider": "claude", "client": "claude_code", "label": "Claude Code", "id": sid,
"session": os.path.basename(path),
"path": path,
"project": home_shorten(trace_cwd) or decode_claude_project(os.path.basename(os.path.dirname(path))),
"mtime": safe_mtime(path), "title": None,
}
def newest_source():
sources = all_session_sources()
return max(sources, key=lambda s: s["mtime"]) if sources else None
def find_session(sid, sources=None):
source_pool = sources if sources is not None else all_session_sources()
for source in source_pool:
stem = os.path.basename(source["path"]).rsplit(".", 1)[0]
if sid in (source["id"], source["session"], stem, source.get("desktop_session_id")):
return source
return None
def trash_session_log(session_id, sources=None, trash_dir=None, mover=None):
"""Move one exact, currently discovered session log to Trash."""
session_id = str(session_id or "").strip()
if not session_id or len(session_id) > 240:
return {"ok": False, "error": "A valid session ID is required.", "error_code": "invalid_id"}
source_pool = list(sources) if sources is not None else all_session_sources()
source = find_session(session_id, sources=source_pool)
if not source or str(source.get("id") or "") != session_id:
return {"ok": False, "error": "Session is not in the discovered log inventory.",
"error_code": "not_found"}
path = str(source.get("path") or "")
if not path.endswith(".jsonl") or not os.path.isfile(path):
return {"ok": False, "error": "The discovered session log is not available.",
"error_code": "not_found"}
trash_dir = os.path.expanduser(trash_dir or "~/.Trash")
mover = mover or shutil.move
try:
os.makedirs(trash_dir, exist_ok=True)
base = f"Token Meter - {os.path.basename(path)}"
stem, ext = os.path.splitext(base)
destination = os.path.join(trash_dir, base)
suffix = 2
while os.path.exists(destination):
destination = os.path.join(trash_dir, f"{stem} {suffix}{ext}")
suffix += 1
mover(path, destination)
except OSError:
return {"ok": False, "error": "Token Meter could not move the session log to Trash.",
"error_code": "trash_failed"}
_summary_cache.pop(path, None)
_xsess["data"], _xsess["at"] = None, 0.0
return {
"ok": True,
"changed": True,
"session_id": session_id,
"title": source.get("title") or "(untitled log)",
"project": source.get("project") or "",
"provider": source.get("provider") or "",
"trash_name": os.path.basename(destination),
"message": "Session log moved to Trash.",
}
def price_for(model, provider="claude"):
model = model or (DEFAULT_OPENAI_MODEL if provider == "codex" else DEFAULT_CLAUDE_MODEL)
table = OPENAI_PRICE if provider == "codex" else CLAUDE_PRICE
default = DEFAULT_OPENAI_MODEL if provider == "codex" else DEFAULT_CLAUDE_MODEL
if model in table:
return table[model], False
compact = model.replace(" ", "-").lower()
for key, price in table.items():
if compact.startswith(key):
return price, False
return table[default], True
def cost_of(u, model, provider="claude"):
p, _ = price_for(model, provider)
return {
"input": u.get("input_tokens", 0) * p["input"] / 1e6,
"cache_write": u.get("cache_creation_input_tokens", 0) * p["cache_write"] / 1e6,
"cache_read": u.get("cache_read_input_tokens", 0) * p["cache_read"] / 1e6,
"output": u.get("output_tokens", 0) * p["output"] / 1e6,
}
def usage_tokens(u):
return (u.get("input_tokens", 0) + u.get("cache_creation_input_tokens", 0)
+ u.get("cache_read_input_tokens", 0) + u.get("output_tokens", 0))
def usage_io_tokens(u):
"""Return total trace-reported input, including cache, and output."""
return (
int(u.get("input_tokens", 0) or 0)
+ int(u.get("cache_creation_input_tokens", 0) or 0)
+ int(u.get("cache_read_input_tokens", 0) or 0),
int(u.get("output_tokens", 0) or 0),
)
def add_model_summary(stats, model, usage, cost):
input_tokens, output_tokens = usage_io_tokens(usage)
row = stats.setdefault(model or "unknown", {
"cost": 0.0, "tokens": 0, "input_tokens": 0,
"output_tokens": 0, "executions": 0,
})
row["cost"] += float(cost or 0)
row["tokens"] += input_tokens + output_tokens
row["input_tokens"] += input_tokens
row["output_tokens"] += output_tokens
row["executions"] += 1
return input_tokens, output_tokens
def add_model_daily(stats, model, usage, cost, ts):
"""Accumulate exact trace-reported model I/O into local calendar days."""
if not ts:
return
input_tokens, output_tokens = usage_io_tokens(usage)
day = time.strftime("%Y-%m-%d", time.localtime(ts))
key = (model or "unknown", day)
row = stats.setdefault(key, {
"model": model or "unknown", "day": day, "cost": 0.0,
"input_tokens": 0, "output_tokens": 0, "executions": 0,
})
row["cost"] += float(cost or 0)
row["input_tokens"] += input_tokens
row["output_tokens"] += output_tokens
row["executions"] += 1
def claude_performance_samples(objs):
"""Return completed Claude turn samples with attributable reported timing."""
messages = {rec["id"]: rec for rec in iter_claude_messages(objs)}
samples = []
current = None
def ensure_current():
nonlocal current
if current is None:
current = {"message_ids": [], "seen": set()}
return current
def close_turn(obj):
nonlocal current
duration_ms = obj.get("durationMs")
try:
duration_ms = float(duration_ms or 0)
except (TypeError, ValueError):
duration_ms = 0
group = current
current = None
if not group or duration_ms <= 0:
return
records = [messages[mid] for mid in group["message_ids"] if mid in messages and not messages[mid].get("side")]
models = {rec.get("model") or DEFAULT_CLAUDE_MODEL for rec in records if rec.get("usage")}
if len(models) != 1:
return
input_tokens = output_tokens = 0
tool_ids = set()
for rec in records:
in_count, out_count = usage_io_tokens(rec.get("usage") or {})
input_tokens += in_count
output_tokens += out_count
for block in rec.get("content") or []:
if isinstance(block, dict) and block.get("type") == "tool_use":
tool_ids.add(block.get("id") or (block.get("name"), len(tool_ids)))
if output_tokens <= 0:
return
ts = parse_iso(obj.get("timestamp", "")) or max((rec.get("ts") or 0 for rec in records), default=0)
samples.append({
"provider": "claude", "model": next(iter(models)),
"day": time.strftime("%Y-%m-%d", time.localtime(ts)) if ts else "",
"ts": ts or 0, "input_tokens": input_tokens, "output_tokens": output_tokens,
"duration_s": duration_ms / 1000.0, "generation_s": duration_ms / 1000.0,
"ttft_s": 0.0, "tool_calls": len(tool_ids), "timing_basis": "turn_duration",
})
for obj in objs:
otype = obj.get("type")
if otype == "user":
msg = obj.get("message") if isinstance(obj.get("message"), dict) else {}
if claude_user_text(msg).strip():
current = {"message_ids": [], "seen": set()}
continue
if otype == "assistant":
msg = obj.get("message") if isinstance(obj.get("message"), dict) else {}
mid = msg.get("id") or obj.get("uuid")
group = ensure_current()
if mid not in group["seen"]:
group["seen"].add(mid)
group["message_ids"].append(mid)
continue
if otype == "system" and obj.get("subtype") == "turn_duration":
close_turn(obj)
return samples
def codex_performance_samples(objs, default_model=None):
"""Return completed Codex task samples with model-attributable timing."""
model = default_model or DEFAULT_OPENAI_MODEL
samples = []
current = None
def ensure_current(ts=0):
nonlocal current
if current is None:
current = {"started_ts": ts or 0, "usage": {}, "tool_calls": 0}
return current
def close_task(payload, ts):
nonlocal current
task = current
current = None
if not task or len(task["usage"]) != 1:
return
duration_ms = payload.get("duration_ms")
ttft_ms = payload.get("time_to_first_token_ms")
try:
duration_ms = float(duration_ms or 0)
ttft_ms = float(ttft_ms or 0)
except (TypeError, ValueError):
return
if duration_ms <= 0:
return
sample_model, counts = next(iter(task["usage"].items()))
output_tokens = int(counts.get("output_tokens") or 0)
if output_tokens <= 0:
return
duration_s = duration_ms / 1000.0
generation_s = (duration_ms - ttft_ms) / 1000.0 if 0 < ttft_ms < duration_ms else duration_s
samples.append({
"provider": "codex", "model": sample_model,
"day": time.strftime("%Y-%m-%d", time.localtime(ts)) if ts else "",
"ts": ts or 0, "input_tokens": int(counts.get("input_tokens") or 0),
"output_tokens": output_tokens, "duration_s": duration_s,
"generation_s": generation_s, "ttft_s": max(0.0, ttft_ms / 1000.0),
"tool_calls": int(task.get("tool_calls") or 0), "timing_basis": "task_complete",
})
for obj in objs:
payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}
ptype = payload.get("type")
ts = parse_iso(obj.get("timestamp", "")) or 0
if obj.get("type") == "turn_context":
model = payload.get("model") or model
continue
if ptype == "task_started":
current = {"started_ts": ts, "usage": {}, "tool_calls": 0}
continue
if ptype in ("function_call", "custom_tool_call", "web_search_call", "tool_search_call"):
ensure_current(ts)["tool_calls"] += 1
continue
if ptype == "token_count":
raw = ((payload.get("info") or {}).get("last_token_usage") or {})
if not raw:
continue
usage = codex_usage(raw)
task = ensure_current(ts)
row = task["usage"].setdefault(model, {"input_tokens": 0, "output_tokens": 0})
input_count, output_count = usage_io_tokens(usage)
row["input_tokens"] += input_count
row["output_tokens"] += output_count
continue
if ptype == "task_complete":
close_task(payload, ts)
return samples
def performance_summary(samples, total_output_tokens=0):
"""Summarize weighted observed output throughput without averaging rates."""
timed = [row for row in (samples or []) if row.get("output_tokens", 0) > 0 and row.get("duration_s", 0) > 0]
tool_free = [row for row in timed if int(row.get("tool_calls") or 0) == 0]
selected = tool_free or timed
basis = "tool_free" if tool_free else ("end_to_end" if timed else "unavailable")
def seconds(row):
if basis == "tool_free":
return float(row.get("generation_s") or row.get("duration_s") or 0)
return float(row.get("duration_s") or 0)
measured_seconds = sum(seconds(row) for row in selected)
measured_output = sum(int(row.get("output_tokens") or 0) for row in selected)
latest = max(selected, key=lambda row: row.get("ts") or 0) if selected else None
latest_seconds = seconds(latest) if latest else 0
ttft_rows = [float(row.get("ttft_s") or 0) for row in selected if row.get("ttft_s", 0) > 0]
denominator = int(total_output_tokens or 0)
return {
"available": bool(measured_seconds > 0 and measured_output > 0),
"output_tps": (measured_output / measured_seconds) if measured_seconds > 0 else 0,
"latest_output_tps": ((latest.get("output_tokens") or 0) / latest_seconds) if latest_seconds > 0 else 0,
"basis": basis,
"sample_count": len(selected),
"timed_samples": len(timed),
"tool_free_samples": len(tool_free),
"measured_output_tokens": measured_output,
"measured_seconds": measured_seconds,
"timing_coverage": (measured_output / denominator) if denominator > 0 else 0,
"avg_ttft_ms": (sum(ttft_rows) * 1000 / len(ttft_rows)) if ttft_rows else 0,
}
def codex_usage(raw):
raw = raw or {}
input_total = int(raw.get("input_tokens") or 0)
cached = int(raw.get("cached_input_tokens") or 0)
return {
"input_tokens": max(0, input_total - cached),
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": cached,
"output_tokens": int(raw.get("output_tokens") or 0),
"reasoning_output_tokens": int(raw.get("reasoning_output_tokens") or 0),
"total_tokens": int(raw.get("total_tokens") or 0),
}