-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodex_app_tracker.py
More file actions
3323 lines (2940 loc) · 129 KB
/
codex_app_tracker.py
File metadata and controls
3323 lines (2940 loc) · 129 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
"""
Local AI coding usage tracker.
Reads Codex desktop/app rollout logs, Claude Code transcripts, and Cursor AI
tracking metadata, generates CSV/JSON/HTML reports, and can send conservative
WakaTime "ai coding" heartbeats for recent Codex app activity.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import html
import json
import os
import queue
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
try:
from zoneinfo import ZoneInfo
except Exception: # pragma: no cover - Python without zoneinfo support.
ZoneInfo = None # type: ignore[assignment]
VERSION = "0.2.0"
TRACKER_DIR = Path(__file__).resolve().parent
DEFAULT_CODEX_HOME = Path.home() / ".codex"
DEFAULT_CLAUDE_HOME = Path.home() / ".claude"
DEFAULT_CURSOR_AI_DB = Path.home() / ".cursor" / "ai-tracking" / "ai-code-tracking.db"
DEFAULT_CURSOR_STATE_DB = (
Path(os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming")))
/ "Cursor" / "User" / "globalStorage" / "state.vscdb"
)
DEFAULT_OUTPUT_DIR = Path.cwd() / "out"
DEFAULT_STATE_FILE = Path.home() / ".codex-usage-tracker" / "state.json"
PRICING_SOURCE_DATE = "2026-05-31"
CODEX_RATE_CARD_URL = "https://help.openai.com/en/articles/20001106-codex-rate-card"
API_PRICING_URL = "https://developers.openai.com/api/docs/pricing"
ANTHROPIC_PRICING_URL = "https://platform.claude.com/docs/en/about-claude/pricing?hsLang=en"
CURSOR_PRICING_URL = "https://cursor.com/en-US/pricing"
OPENAI_USAGE_API_URL = "https://platform.openai.com/docs/api-reference/usage"
OPENAI_COSTS_API_URL = "https://platform.openai.com/docs/api-reference/usage/costs"
ANTHROPIC_USAGE_COST_API_URL = "https://platform.claude.com/docs/en/build-with-claude/usage-cost-api"
ANTHROPIC_CLAUDE_CODE_ANALYTICS_URL = "https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api"
CURSOR_ADMIN_API_URL = "https://docs.cursor.com/account/teams/admin-api"
API_PRICING_BASIS = "standard short-context text token rates"
USAGE_FIELDS = (
"input_tokens",
"cached_input_tokens",
"cache_creation_input_tokens",
"cache_creation_1h_input_tokens",
"output_tokens",
"reasoning_output_tokens",
"total_tokens",
)
SUPPORTED_SOURCES = ("codex", "claude", "cursor")
SOURCE_LABELS = {
"codex": "Codex",
"claude": "Claude Code",
"cursor": "Cursor",
"demo": "Demo",
"(unknown)": "(unknown)",
}
# Rates verified against official OpenAI/Anthropic pages on 2026-05-31.
# Codex credit estimates use the token-based Codex rate card. USD estimates are
# pricing-equivalent calculations, not an official invoice or live balance.
MODEL_RATES: dict[str, dict[str, dict[str, float]]] = {
"gpt-5.5": {
"codex_credits": {"input": 125.0, "cached_input": 12.5, "output": 750.0},
"api_usd_standard_short": {"input": 5.0, "cached_input": 0.5, "output": 30.0},
},
"gpt-5.4": {
"codex_credits": {"input": 62.5, "cached_input": 6.25, "output": 375.0},
"api_usd_standard_short": {"input": 2.5, "cached_input": 0.25, "output": 15.0},
},
"gpt-5.4-mini": {
"codex_credits": {"input": 18.75, "cached_input": 1.875, "output": 113.0},
"api_usd_standard_short": {"input": 0.75, "cached_input": 0.075, "output": 4.5},
},
"gpt-5.3-codex": {
"codex_credits": {"input": 43.75, "cached_input": 4.375, "output": 350.0},
"api_usd_standard_short": {"input": 1.75, "cached_input": 0.175, "output": 14.0},
},
"gpt-5.2": {
"codex_credits": {"input": 43.75, "cached_input": 4.375, "output": 350.0},
"api_usd_standard_short": {"input": 1.75, "cached_input": 0.175, "output": 14.0},
},
"claude-opus-4-8": {
"anthropic_usd": {"input": 5.0, "cache_creation": 6.25, "cache_creation_1h": 10.0, "cached_input": 0.50, "output": 25.0},
},
"claude-opus-4-7": {
"anthropic_usd": {"input": 5.0, "cache_creation": 6.25, "cache_creation_1h": 10.0, "cached_input": 0.50, "output": 25.0},
},
"claude-opus-4-6": {
"anthropic_usd": {"input": 5.0, "cache_creation": 6.25, "cache_creation_1h": 10.0, "cached_input": 0.50, "output": 25.0},
},
"claude-opus-4-5": {
"anthropic_usd": {"input": 5.0, "cache_creation": 6.25, "cache_creation_1h": 10.0, "cached_input": 0.50, "output": 25.0},
},
"claude-opus-4-1": {
"anthropic_usd": {"input": 15.0, "cache_creation": 18.75, "cache_creation_1h": 30.0, "cached_input": 1.50, "output": 75.0},
},
"claude-opus-4": {
"anthropic_usd": {"input": 15.0, "cache_creation": 18.75, "cache_creation_1h": 30.0, "cached_input": 1.50, "output": 75.0},
},
"claude-sonnet-4-6": {
"anthropic_usd": {"input": 3.0, "cache_creation": 3.75, "cache_creation_1h": 6.0, "cached_input": 0.30, "output": 15.0},
},
"claude-sonnet-4-5": {
"anthropic_usd": {"input": 3.0, "cache_creation": 3.75, "cache_creation_1h": 6.0, "cached_input": 0.30, "output": 15.0},
},
"claude-sonnet-4": {
"anthropic_usd": {"input": 3.0, "cache_creation": 3.75, "cache_creation_1h": 6.0, "cached_input": 0.30, "output": 15.0},
},
"claude-haiku-4-5": {
"anthropic_usd": {"input": 1.0, "cache_creation": 1.25, "cache_creation_1h": 2.0, "cached_input": 0.10, "output": 5.0},
},
"claude-haiku-3-5": {
"anthropic_usd": {"input": 0.80, "cache_creation": 1.0, "cache_creation_1h": 1.6, "cached_input": 0.08, "output": 4.0},
},
}
def parse_ts(value: Any) -> datetime | None:
if not isinstance(value, str) or not value:
return None
try:
if value.endswith("Z"):
value = value[:-1] + "+00:00"
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
except ValueError:
return None
def fmt_dt(value: datetime | None, report_tz: Any = None) -> str:
if not value:
return ""
return value.astimezone(report_tz).strftime("%Y-%m-%d %H:%M:%S %Z")
def local_day(value: datetime, report_tz: Any = None) -> str:
return value.astimezone(report_tz).strftime("%Y-%m-%d")
def clean_windows_path(value: Any) -> str:
if not isinstance(value, str):
return ""
if value.startswith("\\\\?\\"):
return value[4:]
return value
def project_name_from_cwd(cwd: str) -> str:
cwd = clean_windows_path(cwd)
if not cwd:
return "(unknown)"
if "\\" in cwd:
trimmed = cwd.rstrip("\\/")
if trimmed:
return re.split(r"[\\/]+", trimmed)[-1] or trimmed
try:
return Path(cwd).name or cwd
except Exception:
return cwd
def zero_usage() -> dict[str, int]:
return {field: 0 for field in USAGE_FIELDS}
def nonnegative_int(value: Any) -> int:
if isinstance(value, bool):
return 0
if isinstance(value, (int, float)):
return max(0, int(value))
return 0
def normalize_usage(value: Any) -> dict[str, int]:
usage = zero_usage()
if not isinstance(value, dict):
return usage
for field in USAGE_FIELDS:
usage[field] = nonnegative_int(value.get(field, 0))
if usage["total_tokens"] == 0:
usage["total_tokens"] = usage["input_tokens"] + usage["output_tokens"]
return usage
def normalize_claude_usage(value: Any) -> dict[str, int]:
usage = zero_usage()
if not isinstance(value, dict):
return usage
base_input = nonnegative_int(value.get("input_tokens", 0))
cache_creation = nonnegative_int(value.get("cache_creation_input_tokens", 0))
cache_read = nonnegative_int(value.get("cache_read_input_tokens", 0))
cache_creation_1h = 0
cache_creation_meta = value.get("cache_creation")
if isinstance(cache_creation_meta, dict):
cache_creation_1h = min(
cache_creation,
nonnegative_int(cache_creation_meta.get("ephemeral_1h_input_tokens", 0)),
)
output = nonnegative_int(value.get("output_tokens", 0))
usage["input_tokens"] = base_input + cache_creation + cache_read
usage["cached_input_tokens"] = cache_read
usage["cache_creation_input_tokens"] = cache_creation
usage["cache_creation_1h_input_tokens"] = cache_creation_1h
usage["output_tokens"] = output
usage["total_tokens"] = usage["input_tokens"] + output
return usage
def add_usage(target: dict[str, int], delta: dict[str, int]) -> None:
for field in USAGE_FIELDS:
target[field] = target.get(field, 0) + int(delta.get(field, 0))
def diff_usage(current: dict[str, int], previous: dict[str, int]) -> dict[str, int]:
delta = zero_usage()
for field in USAGE_FIELDS:
cur = int(current.get(field, 0))
prev = int(previous.get(field, 0))
delta[field] = cur - prev if cur >= prev else cur
return delta
def usage_total(usage: dict[str, int]) -> int:
return int(usage.get("total_tokens", 0))
def parse_epoch_timestamp(value: Any) -> datetime | None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
seconds = float(value)
if seconds > 10_000_000_000:
seconds /= 1000.0
try:
return datetime.fromtimestamp(seconds, timezone.utc)
except Exception:
return None
def parse_source_filter(value: str | None) -> set[str]:
raw = (value or "codex").strip().lower()
if raw in {"", "codex"}:
return {"codex"}
parts = {part.strip().lower() for part in raw.split(",") if part.strip()}
if "all" in parts:
return set(SUPPORTED_SOURCES)
unknown = sorted(parts - set(SUPPORTED_SOURCES))
if unknown:
known = ", ".join((*SUPPORTED_SOURCES, "all"))
raise ValueError(f"unknown source(s): {', '.join(unknown)}. Use one of: {known}")
return parts or {"codex"}
def normalize_app(value: Any) -> str:
text = str(value or "").strip().lower().replace("_", "-")
if not text:
return "(unknown)"
if text in SOURCE_LABELS:
return text
if text.startswith("codex") or "openai" in text:
return "codex"
if text.startswith("claude") or "anthropic" in text:
return "claude"
if text.startswith("cursor"):
return "cursor"
if text.startswith("demo"):
return "demo"
return text
def thread_app(thread: dict[str, Any]) -> str:
app = normalize_app(thread.get("app"))
if app != "(unknown)":
return app
return normalize_app(thread.get("source"))
def app_label(app: Any) -> str:
key = normalize_app(app)
return SOURCE_LABELS.get(key, str(app or key))
def normalize_model(model: str | None) -> str:
if not model:
return ""
return model.strip().lower().replace("_", "-")
def rates_for_model(model: str | None) -> dict[str, dict[str, float]] | None:
normalized = normalize_model(model)
if normalized in MODEL_RATES:
return MODEL_RATES[normalized]
# Handle suffixes like gpt-5.5-something conservatively.
for known, rates in MODEL_RATES.items():
if normalized.startswith(known):
return rates
return None
def estimate_amount(usage: dict[str, int], model: str | None, rate_kind: str) -> float | None:
rates = rates_for_model(model)
if not rates or rate_kind not in rates:
return None
rate = rates[rate_kind]
cached = int(usage.get("cached_input_tokens", 0))
cache_creation = int(usage.get("cache_creation_input_tokens", 0))
cache_creation_1h = min(cache_creation, int(usage.get("cache_creation_1h_input_tokens", 0)))
cache_creation_5m = max(0, cache_creation - cache_creation_1h)
input_total = int(usage.get("input_tokens", 0))
uncached_input = max(0, input_total - cached - cache_creation)
output = int(usage.get("output_tokens", 0))
return (
(uncached_input / 1_000_000.0) * rate["input"]
+ (cached / 1_000_000.0) * rate.get("cached_input", rate["input"])
+ (cache_creation_5m / 1_000_000.0) * rate.get("cache_creation", rate["input"])
+ (cache_creation_1h / 1_000_000.0) * rate.get("cache_creation_1h", rate.get("cache_creation", rate["input"]))
+ (output / 1_000_000.0) * rate["output"]
)
def pricing_metadata() -> dict[str, Any]:
return {
"source_date": PRICING_SOURCE_DATE,
"codex_rate_card_url": CODEX_RATE_CARD_URL,
"api_pricing_url": API_PRICING_URL,
"anthropic_pricing_url": ANTHROPIC_PRICING_URL,
"cursor_pricing_url": CURSOR_PRICING_URL,
"api_pricing_basis": API_PRICING_BASIS,
"caveat": "Codex credits and Claude USD are estimated from local token logs and official token rates. Cursor activity comes from local app data, but official billing, remaining credits, fast mode uplifts, taxes, and plan exceptions must be checked with the vendor.",
}
def read_thread_db(codex_home: Path) -> dict[str, dict[str, Any]]:
db_path = codex_home / "state_5.sqlite"
if not db_path.exists():
return {}
result: dict[str, dict[str, Any]] = {}
uri = f"file:{db_path}?mode=ro"
try:
con = sqlite3.connect(uri, uri=True, timeout=2)
con.row_factory = sqlite3.Row
rows = con.execute(
"""
select id, title, cwd, model, reasoning_effort, created_at, updated_at,
tokens_used, source, thread_source, preview
from threads
"""
).fetchall()
for row in rows:
result[row["id"]] = dict(row)
con.close()
except Exception as exc:
print(f"warning: could not read {db_path}: {exc}", file=sys.stderr)
return result
def iter_rollout_files(codex_home: Path) -> list[Path]:
roots = [codex_home / "sessions", codex_home / "archived_sessions"]
files: list[Path] = []
for root in roots:
if root.exists():
files.extend(root.rglob("rollout-*.jsonl"))
return sorted(set(files), key=lambda p: str(p).lower())
def session_id_from_filename(path: Path) -> str:
match = re.search(r"(019[0-9a-f-]{32,})", path.name, re.IGNORECASE)
if match:
return match.group(1)
return path.stem
def estimate_active_seconds(
timestamps: list[datetime],
max_gap_seconds: int = 15 * 60,
report_tz: Any = None,
) -> tuple[int, dict[str, int]]:
unique = sorted(set(timestamps))
if not unique:
return 0, {}
total = 60
daily: dict[str, int] = defaultdict(int)
daily[local_day(unique[0], report_tz)] += 60
previous = unique[0]
for current in unique[1:]:
delta = int((current - previous).total_seconds())
if 0 < delta <= max_gap_seconds:
add = delta
elif delta > max_gap_seconds:
add = 60
else:
add = 0
if add:
total += add
daily[local_day(current, report_tz)] += add
previous = current
return total, dict(daily)
def parse_rollout(path: Path, db_meta: dict[str, dict[str, Any]], report_tz: Any = None) -> dict[str, Any]:
session_id = ""
cwd = ""
title = ""
source = ""
model = ""
reasoning_effort = ""
cli_version = ""
timestamps: list[datetime] = []
usage_events: list[tuple[datetime, dict[str, int]]] = []
tool_counts: dict[str, int] = defaultdict(int)
line_count = 0
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if not line.strip():
continue
line_count += 1
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
ts = parse_ts(obj.get("timestamp"))
if ts:
timestamps.append(ts)
payload = obj.get("payload")
if not isinstance(payload, dict):
continue
event_type = obj.get("type")
if event_type == "session_meta":
session_id = str(payload.get("id") or session_id)
cwd = clean_windows_path(payload.get("cwd") or cwd)
source = str(payload.get("source") or source)
cli_version = str(payload.get("cli_version") or cli_version)
elif event_type == "turn_context":
cwd = clean_windows_path(payload.get("cwd") or cwd)
model = str(payload.get("model") or model)
reasoning_effort = str(payload.get("effort") or reasoning_effort)
collab = payload.get("collaboration_mode")
if isinstance(collab, dict):
settings = collab.get("settings")
if isinstance(settings, dict):
model = str(settings.get("model") or model)
reasoning_effort = str(settings.get("reasoning_effort") or reasoning_effort)
payload_model = payload.get("model")
if isinstance(payload_model, str):
model = payload_model
info = payload.get("info")
if isinstance(info, dict) and ts:
total_usage = info.get("total_token_usage")
if isinstance(total_usage, dict):
usage_events.append((ts, normalize_usage(total_usage)))
item_type = payload.get("type")
if isinstance(item_type, str) and item_type:
if item_type in {"function_call", "function_call_output", "tool_call", "tool_result"}:
tool_name = str(payload.get("name") or payload.get("tool_name") or item_type)
tool_counts[tool_name] += 1
if not session_id:
session_id = session_id_from_filename(path)
meta = db_meta.get(session_id, {})
title = str(meta.get("title") or title or "")
cwd = clean_windows_path(meta.get("cwd") or cwd)
model = str(meta.get("model") or model or "")
reasoning_effort = str(meta.get("reasoning_effort") or reasoning_effort or "")
source = str(meta.get("source") or source or "")
usage_events.sort(key=lambda item: item[0])
latest_usage = zero_usage()
daily_usage: dict[str, dict[str, int]] = defaultdict(zero_usage)
previous_usage = zero_usage()
for ts, current_usage in usage_events:
delta = diff_usage(current_usage, previous_usage)
if usage_total(delta) > 0:
add_usage(daily_usage[local_day(ts, report_tz)], delta)
previous_usage = current_usage
latest_usage = current_usage
if usage_total(latest_usage) == 0 and isinstance(meta.get("tokens_used"), int):
latest_usage["total_tokens"] = max(0, int(meta["tokens_used"]))
active_seconds, active_daily = estimate_active_seconds(timestamps, report_tz=report_tz)
started_at = min(timestamps) if timestamps else None
ended_at = max(timestamps) if timestamps else None
return {
"thread_id": session_id,
"title": title,
"cwd": cwd,
"project": project_name_from_cwd(cwd),
"app": "codex",
"source": source,
"model": model,
"reasoning_effort": reasoning_effort,
"cli_version": cli_version,
"path": str(path),
"line_count": line_count,
"event_count": line_count,
"request_count": len(usage_events),
"started_at": started_at,
"ended_at": ended_at,
"usage": latest_usage,
"daily_usage": dict(daily_usage),
"event_timestamps": timestamps,
"active_seconds": active_seconds,
"active_daily": active_daily,
"tool_counts": dict(tool_counts),
"estimated_codex_credits": estimate_amount(latest_usage, model, "codex_credits"),
"estimated_api_usd_equiv": estimate_amount(latest_usage, model, "api_usd_standard_short"),
}
def load_threads(codex_home: Path, days: int | None = None, report_tz: Any = None) -> list[dict[str, Any]]:
db_meta = read_thread_db(codex_home)
parsed: dict[str, dict[str, Any]] = {}
cutoff = datetime.now(timezone.utc) - timedelta(days=days) if days else None
for path in iter_rollout_files(codex_home):
try:
thread = parse_rollout(path, db_meta, report_tz=report_tz)
except Exception as exc:
print(f"warning: could not parse {path}: {exc}", file=sys.stderr)
continue
ended_at = thread.get("ended_at")
if cutoff and isinstance(ended_at, datetime) and ended_at < cutoff:
continue
key = thread["thread_id"]
existing = parsed.get(key)
if not existing:
parsed[key] = thread
continue
existing_total = usage_total(existing["usage"])
current_total = usage_total(thread["usage"])
existing_end = existing.get("ended_at") or datetime.min.replace(tzinfo=timezone.utc)
current_end = thread.get("ended_at") or datetime.min.replace(tzinfo=timezone.utc)
if (current_total, current_end) >= (existing_total, existing_end):
parsed[key] = thread
return sorted(parsed.values(), key=lambda item: item.get("ended_at") or datetime.min.replace(tzinfo=timezone.utc), reverse=True)
def iter_claude_files(claude_home: Path) -> list[Path]:
projects = claude_home / "projects"
if not projects.exists():
return []
return sorted(set(projects.rglob("*.jsonl")), key=lambda p: str(p).lower())
def parse_claude_jsonl(path: Path, report_tz: Any = None) -> dict[str, Any]:
session_id = path.stem
cwd = ""
title = ""
cli_version = ""
timestamps: list[datetime] = []
daily_usage: dict[str, dict[str, int]] = defaultdict(zero_usage)
total_usage = zero_usage()
tool_counts: dict[str, int] = defaultdict(int)
model_counts: Counter[str] = Counter()
seen_message_ids: set[str] = set()
line_count = 0
request_count = 0
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if not line.strip():
continue
line_count += 1
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
ts = parse_ts(obj.get("timestamp"))
if ts:
timestamps.append(ts)
if isinstance(obj.get("sessionId"), str):
session_id = obj["sessionId"] or session_id
if isinstance(obj.get("cwd"), str):
cwd = clean_windows_path(obj.get("cwd") or cwd)
if isinstance(obj.get("version"), str):
cli_version = obj.get("version") or cli_version
if isinstance(obj.get("aiTitle"), str) and obj.get("aiTitle"):
title = obj.get("aiTitle") or title
message = obj.get("message")
if not isinstance(message, dict):
continue
model = message.get("model")
if isinstance(model, str) and model:
model_counts[model] += 1
usage = normalize_claude_usage(message.get("usage"))
if usage_total(usage) > 0:
message_id = str(message.get("id") or obj.get("requestId") or obj.get("uuid") or "")
if message_id and message_id in seen_message_ids:
continue
if message_id:
seen_message_ids.add(message_id)
add_usage(total_usage, usage)
request_count += 1
if ts:
add_usage(daily_usage[local_day(ts, report_tz)], usage)
content = message.get("content")
if isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "tool_use":
tool_name = str(item.get("name") or "tool_use")
tool_counts[tool_name] += 1
active_seconds, active_daily = estimate_active_seconds(timestamps, report_tz=report_tz)
started_at = min(timestamps) if timestamps else None
ended_at = max(timestamps) if timestamps else None
model = model_counts.most_common(1)[0][0] if model_counts else ""
if not title:
title = f"Claude Code session {session_id[:8]}"
return {
"thread_id": session_id,
"title": title,
"cwd": cwd,
"project": project_name_from_cwd(cwd),
"app": "claude",
"source": "claude_code",
"model": model,
"reasoning_effort": "",
"cli_version": cli_version,
"path": str(path),
"line_count": line_count,
"event_count": line_count,
"request_count": request_count,
"started_at": started_at,
"ended_at": ended_at,
"usage": total_usage,
"daily_usage": dict(daily_usage),
"event_timestamps": timestamps,
"active_seconds": active_seconds,
"active_daily": active_daily,
"tool_counts": dict(tool_counts),
"estimated_codex_credits": 0.0,
"estimated_api_usd_equiv": estimate_amount(total_usage, model, "anthropic_usd") or 0.0,
}
def load_claude_threads(claude_home: Path, days: int | None = None, report_tz: Any = None) -> list[dict[str, Any]]:
cutoff = datetime.now(timezone.utc) - timedelta(days=days) if days else None
threads: list[dict[str, Any]] = []
for path in iter_claude_files(claude_home):
try:
thread = parse_claude_jsonl(path, report_tz=report_tz)
except Exception as exc:
print(f"warning: could not parse {path}: {exc}", file=sys.stderr)
continue
ended_at = thread.get("ended_at")
if cutoff and isinstance(ended_at, datetime) and ended_at < cutoff:
continue
threads.append(thread)
return sorted(threads, key=lambda item: item.get("ended_at") or datetime.min.replace(tzinfo=timezone.utc), reverse=True)
def load_cursor_threads(cursor_db: Path, days: int | None = None, report_tz: Any = None) -> list[dict[str, Any]]:
if not cursor_db.exists():
return []
cutoff = datetime.now(timezone.utc) - timedelta(days=days) if days else None
groups: dict[str, dict[str, Any]] = {}
summaries: dict[str, str] = {}
try:
con = sqlite3.connect(f"file:{cursor_db}?mode=ro", uri=True, timeout=3)
tables = {
row[0]
for row in con.execute("select name from sqlite_master where type='table'").fetchall()
}
if "conversation_summaries" in tables:
for conversation_id, title in con.execute("select conversationId, title from conversation_summaries"):
if conversation_id and title:
summaries[str(conversation_id)] = str(title)
if "ai_code_hashes" not in tables:
con.close()
return []
rows = con.execute(
"""
select conversationId, requestId, timestamp, source, fileExtension, model
from ai_code_hashes
order by timestamp
"""
)
for conversation_id, request_id, timestamp, source, file_extension, model in rows:
conversation_id = str(conversation_id or request_id or f"cursor-{timestamp}")
group = groups.setdefault(conversation_id, {
"thread_id": f"cursor-{conversation_id}",
"conversation_id": conversation_id,
"timestamps": [],
"requests": set(),
"model_counts": Counter(),
"source_counts": Counter(),
"extension_counts": Counter(),
"line_count": 0,
})
ts = parse_epoch_timestamp(timestamp)
if ts:
group["timestamps"].append(ts)
if request_id:
group["requests"].add(str(request_id))
if source:
group["source_counts"][str(source)] += 1
if file_extension:
group["extension_counts"][str(file_extension)] += 1
if model:
group["model_counts"][str(model)] += 1
group["line_count"] += 1
con.close()
except Exception as exc:
print(f"warning: could not read {cursor_db}: {exc}", file=sys.stderr)
return []
threads: list[dict[str, Any]] = []
for group in groups.values():
timestamps = list(group["timestamps"])
if not timestamps:
continue
started_at = min(timestamps)
ended_at = max(timestamps)
if cutoff and ended_at < cutoff:
continue
model_counts: Counter[str] = group["model_counts"]
source_counts: Counter[str] = group["source_counts"]
active_seconds, active_daily = estimate_active_seconds(timestamps, report_tz=report_tz)
conversation_id = group["conversation_id"]
model = model_counts.most_common(1)[0][0] if model_counts else ""
source = source_counts.most_common(1)[0][0] if source_counts else "cursor"
request_count = len(group["requests"]) or group["line_count"]
threads.append({
"thread_id": group["thread_id"],
"title": summaries.get(conversation_id) or f"Cursor AI edits {conversation_id[:8]}",
"cwd": "",
"project": "Cursor AI edits",
"app": "cursor",
"source": f"cursor_{source}",
"model": model,
"reasoning_effort": "",
"cli_version": "",
"path": str(cursor_db),
"line_count": group["line_count"],
"event_count": group["line_count"],
"request_count": request_count,
"started_at": started_at,
"ended_at": ended_at,
"usage": zero_usage(),
"daily_usage": {},
"event_timestamps": timestamps,
"active_seconds": active_seconds,
"active_daily": active_daily,
"tool_counts": {
"ai_code_events": group["line_count"],
"requests": request_count,
},
"estimated_codex_credits": 0.0,
"estimated_api_usd_equiv": 0.0,
})
return sorted(threads, key=lambda item: item.get("ended_at") or datetime.min.replace(tzinfo=timezone.utc), reverse=True)
def read_cursor_daily_stats(cursor_state_db: Path) -> list[dict[str, Any]]:
if not cursor_state_db.exists():
return []
rows: list[dict[str, Any]] = []
try:
con = sqlite3.connect(f"file:{cursor_state_db}?mode=ro", uri=True, timeout=3)
tables = {
row[0]
for row in con.execute("select name from sqlite_master where type='table'").fetchall()
}
if "ItemTable" not in tables:
con.close()
return []
for key, value in con.execute(
"select key, value from ItemTable where key like 'aiCodeTracking.dailyStats.%' order by key"
):
if isinstance(value, bytes):
value = value.decode("utf-8", errors="replace")
try:
data = json.loads(value)
except Exception:
continue
if not isinstance(data, dict):
continue
date = str(data.get("date") or "")
if not re.match(r"^\d{4}-\d{2}-\d{2}$", date):
match = re.search(r"(\d{4}-\d{2}-\d{2})$", str(key))
date = match.group(1) if match else ""
if not date:
continue
rows.append({
"date": date,
"tab_suggested_lines": nonnegative_int(data.get("tabSuggestedLines")),
"tab_accepted_lines": nonnegative_int(data.get("tabAcceptedLines")),
"composer_suggested_lines": nonnegative_int(data.get("composerSuggestedLines")),
"composer_accepted_lines": nonnegative_int(data.get("composerAcceptedLines")),
})
con.close()
except Exception as exc:
print(f"warning: could not read {cursor_state_db}: {exc}", file=sys.stderr)
return []
return sorted(rows, key=lambda row: row["date"])
def load_selected_threads(args: argparse.Namespace, report_tz: Any = None) -> list[dict[str, Any]]:
sources = parse_source_filter(getattr(args, "sources", None))
threads: list[dict[str, Any]] = []
if "codex" in sources:
threads.extend(load_threads(Path(args.codex_home).expanduser(), days=args.days, report_tz=report_tz))
if "claude" in sources:
threads.extend(load_claude_threads(Path(args.claude_home).expanduser(), days=args.days, report_tz=report_tz))
if "cursor" in sources:
threads.extend(load_cursor_threads(Path(args.cursor_db).expanduser(), days=args.days, report_tz=report_tz))
return sorted(
threads,
key=lambda item: item.get("ended_at") or item.get("started_at") or datetime.min.replace(tzinfo=timezone.utc),
reverse=True,
)
def resolve_timezone(name: str | None) -> Any:
if not name:
return None
if ZoneInfo is None:
print(f"warning: timezone '{name}' ignored because zoneinfo is unavailable", file=sys.stderr)
return None
try:
return ZoneInfo(name)
except Exception:
print(f"warning: timezone '{name}' not found; using local timezone", file=sys.stderr)
return None
def parse_date_bound(value: str | None, report_tz: Any = None, end_of_day: bool = False) -> datetime | None:
if not value:
return None
try:
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
parsed = datetime.strptime(value, "%Y-%m-%d")
if end_of_day:
parsed = parsed + timedelta(days=1) - timedelta(microseconds=1)
else:
normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
parsed = datetime.fromisoformat(normalized)
if parsed.tzinfo is None:
if report_tz is not None:
parsed = parsed.replace(tzinfo=report_tz)
else:
parsed = parsed.astimezone().replace(tzinfo=datetime.now().astimezone().tzinfo)
return parsed.astimezone(timezone.utc)
except ValueError as exc:
raise ValueError(f"invalid date '{value}'. Use YYYY-MM-DD or ISO datetime.") from exc
def filter_threads_by_date(
threads: list[dict[str, Any]],
since: str | None = None,
until: str | None = None,
report_tz: Any = None,
) -> list[dict[str, Any]]:
since_dt = parse_date_bound(since, report_tz=report_tz, end_of_day=False)
until_dt = parse_date_bound(until, report_tz=report_tz, end_of_day=True)
if not since_dt and not until_dt:
return threads
filtered: list[dict[str, Any]] = []
for thread in threads:
started = thread.get("started_at")
ended = thread.get("ended_at")
activity = ended or started
if not isinstance(activity, datetime):
continue
if since_dt and activity < since_dt:
continue
if until_dt and activity > until_dt:
continue
filtered.append(thread)
return filtered
def anonymized_project_label(value: str, index: int) -> str:
source = value or f"unknown-{index}"
digest = hashlib.sha256(source.encode("utf-8", errors="replace")).hexdigest()[:8]
return f"project-{digest}"
def copy_thread(thread: dict[str, Any]) -> dict[str, Any]:
clone = dict(thread)
clone["usage"] = dict(thread.get("usage") or zero_usage())
clone["daily_usage"] = {
day: dict(usage)
for day, usage in (thread.get("daily_usage") or {}).items()
}
clone["active_daily"] = dict(thread.get("active_daily") or {})
clone["tool_counts"] = dict(thread.get("tool_counts") or {})
clone["event_timestamps"] = list(thread.get("event_timestamps") or [])
return clone
def apply_privacy(
threads: list[dict[str, Any]],
redact: bool = False,
hash_projects: bool = False,
) -> list[dict[str, Any]]:
if not redact and not hash_projects:
return threads
project_labels: dict[str, str] = {}
result: list[dict[str, Any]] = []
for index, thread in enumerate(threads, start=1):
clone = copy_thread(thread)
project_key = str(thread.get("cwd") or thread.get("project") or thread.get("thread_id") or index)
if redact:
clone["title"] = "(redacted)"
clone["path"] = ""
if hash_projects:
label = project_labels.setdefault(project_key, anonymized_project_label(project_key, index))
clone["project"] = label
clone["cwd"] = ""
clone["path"] = ""
elif redact:
clone["project"] = "(redacted-project)"
clone["cwd"] = ""
result.append(clone)
return result
def aggregate_threads(threads: list[dict[str, Any]]) -> dict[str, Any]:
total_usage = zero_usage()
total_credits = 0.0
total_usd = 0.0
total_active_seconds = 0
total_event_count = 0
total_request_count = 0
daily: dict[str, dict[str, Any]] = defaultdict(lambda: {
"date": "",
"usage": zero_usage(),
"estimated_codex_credits": 0.0,
"estimated_api_usd_equiv": 0.0,
"active_seconds": 0,
"threads": set(),
})
projects: dict[str, dict[str, Any]] = defaultdict(lambda: {
"app": "",
"project": "",
"cwd": "",