-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_usage_export.py
More file actions
2763 lines (2507 loc) · 100 KB
/
Copy pathclient_usage_export.py
File metadata and controls
2763 lines (2507 loc) · 100 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
from __future__ import annotations
import argparse
import json
import os
import re
import sqlite3
from bisect import bisect_left, bisect_right
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Any
def env_float(name: str, default: float) -> float:
try:
return float(os.environ.get(name, str(default)))
except (TypeError, ValueError):
return default
def write_json_atomic(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
try:
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(temporary, path)
finally:
try:
temporary.unlink(missing_ok=True)
except OSError:
pass
def load_cached_account_30d_windows(
path: Path,
now: datetime,
) -> tuple[bool, str, dict[str, dict[str, Any]]]:
try:
existing = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return False, "", {}
updated_text = str(existing.get("account_30d_updated_at") or "")
updated_at = parse_dt(updated_text)
if updated_at is None:
return False, "", {}
age_seconds = (now - updated_at).total_seconds()
if age_seconds < 0 or age_seconds >= ACCOUNT_30D_CACHE_SECONDS:
return False, "", {}
windows = {
str(provider.get("name") or ""): dict(provider["window_30d"])
for provider in existing.get("providers") or []
if isinstance(provider, dict)
and provider.get("name")
and isinstance(provider.get("window_30d"), dict)
}
return True, updated_text, windows
APP_DIR = Path(__file__).resolve().parent
DEFAULT_OUTPUT = APP_DIR / "client_usage_today.json"
CONFIG_PATH = Path(os.environ.get("CLIENT_USAGE_CONFIG") or APP_DIR / "client_usage_config.json")
SPEED_HISTORY_PATH = Path(os.environ.get("CLIENT_USAGE_SPEED_HISTORY") or APP_DIR / "client_usage_speed_history.json")
ACCOUNT_TIMELINE_PATH = Path(os.environ.get("CLIENT_USAGE_ACCOUNT_TIMELINE") or APP_DIR / "client_usage_account_timeline.json")
ATTRIBUTION_LEDGER_PATH = Path(os.environ.get("CLIENT_USAGE_ATTRIBUTION_LEDGER") or APP_DIR / "client_usage_attribution_ledger.json")
CODEX_DEFAULT_MODEL = os.environ.get("CLIENT_USAGE_CODEX_DEFAULT_MODEL", "gpt-5.5")
MAX_SINGLE_EVENT_TOKENS = int(os.environ.get("CLIENT_USAGE_MAX_SINGLE_EVENT_TOKENS", "2000000"))
CODEX_ACCOUNT_MATCH_WINDOW_SECONDS = int(os.environ.get("CLIENT_USAGE_CODEX_ACCOUNT_MATCH_WINDOW_SECONDS", "600"))
CODEX_CURRENT_ACCOUNT_RECENT_SECONDS = int(os.environ.get("CLIENT_USAGE_CURRENT_ACCOUNT_RECENT_SECONDS", "1800"))
CLIENT_USAGE_ACTIVE_WINDOW_SECONDS = int(os.environ.get("CLIENT_USAGE_ACTIVE_WINDOW_SECONDS", "300"))
ACCOUNT_30D_CACHE_SECONDS = int(os.environ.get("CLIENT_USAGE_ACCOUNT_30D_CACHE_SECONDS", "300"))
UNASSIGNED_CODEX_LABEL = os.environ.get("CLIENT_USAGE_UNASSIGNED_CODEX_LABEL", "Unassigned local")
CODEX_FAST_COST_MULTIPLIER = env_float("CLIENT_USAGE_CODEX_FAST_COST_MULTIPLIER", 2.0)
CODEX_FORCE_SPEED = os.environ.get("CLIENT_USAGE_CODEX_FORCE_SPEED", "").strip().lower()
CODEX_SPEED_OVERRIDES = os.environ.get("CLIENT_USAGE_CODEX_SPEED_OVERRIDES", "").strip()
LOCAL_TZ = timezone(timedelta(hours=8))
JSON_DECODER = json.JSONDecoder()
LOG_FIELD_RE = re.compile(r'(?<![A-Za-z0-9_.-])(?P<key>[A-Za-z0-9_.-]+)=(?P<value>"[^"]*"|\S+)')
INTERNAL_SERVICE_TIER_RE = re.compile(
r'service_tier:\s*Some\((?:Some\()?\"(?P<tier>[^\"]+)\"'
)
PROMPT_CACHE_KEY_RE = re.compile(r'prompt_cache_key:\s*Some\(\"(?P<key>[^\"]+)\"\)')
JSON_PROMPT_CACHE_KEY_RE = re.compile(r'"prompt_cache_key"\s*:\s*"(?P<key>[^"]+)"')
THREAD_ID_RE = re.compile(r'\bthread\.id=(?P<key>[A-Za-z0-9_-]+)')
TURN_ID_RE = re.compile(r'\b(?:turn\.id|turn_id)=(?P<key>[A-Za-z0-9_-]+)')
CONVERSATION_ID_RE = re.compile(r'\bconversation\.id=(?P<key>[A-Za-z0-9_-]+)')
SESSION_LOOP_THREAD_ID_RE = re.compile(r'\bsession_loop\{thread_id=(?P<key>[A-Za-z0-9_-]+)\}')
SUB2API_ROUTED_CODEX_LABEL = os.environ.get("CLIENT_USAGE_SUB2API_ROUTED_CODEX_LABEL", "Codex via Sub2API")
@dataclass
class UsageBucket:
requests: int = 0
input_tokens: int = 0
cached_input_tokens: int = 0
output_tokens: int = 0
cache_creation_input_tokens: int = 0
cache_read_input_tokens: int = 0
cost: float = 0.0
models: dict[str, int] = field(default_factory=dict)
latest_at: datetime | None = None
latest_model: str = ""
latest_app_speed: str = ""
latest_cost_multiplier: float | None = None
latest_speed_badge: str = ""
@property
def total_tokens(self) -> int:
return (
self.input_tokens
+ self.cached_input_tokens
+ self.output_tokens
+ self.cache_creation_input_tokens
+ self.cache_read_input_tokens
)
def add_model(self, model: str, tokens: int) -> None:
model = (model or "unknown").strip() or "unknown"
self.models[model] = self.models.get(model, 0) + max(0, int(tokens or 0))
def mark_latest(
self,
when: datetime | None,
model: str,
app_speed: str = "",
cost_multiplier: float | None = None,
) -> None:
if when is None:
return
if self.latest_at is None or when > self.latest_at:
self.latest_at = when
self.latest_model = (model or "unknown").strip() or "unknown"
normalized_speed = normalize_codex_speed(app_speed)
self.latest_app_speed = normalized_speed
self.latest_cost_multiplier = cost_multiplier
self.latest_speed_badge = speed_badge(cost_multiplier)
@dataclass
class UsageEvent:
when: datetime
model: str
input_tokens: int
cached_tokens: int
output_tokens: int
app_speed: str = ""
cost_multiplier: float | None = None
session_id: str = ""
request_key: str = ""
route: str = ""
request_at: datetime | None = None
@property
def total_tokens(self) -> int:
return max(0, self.input_tokens) + max(0, self.cached_tokens) + max(0, self.output_tokens)
@dataclass
class AccountMarker:
when: datetime
label: str
model: str = ""
kind: str = "request"
@dataclass
class SpeedMarker:
when: datetime
speed: str
@dataclass
class RouteMarker:
when: datetime
route: str
session_id: str = ""
request_key: str = ""
PRICE_PER_MILLION: list[tuple[str, tuple[float, float, float]]] = [
("gpt-5.5", (5.0, 0.5, 30.0)),
("gpt-5.4-mini", (0.75, 0.075, 4.5)),
("gpt-5.4", (2.5, 0.25, 15.0)),
("gpt-5.3", (2.5, 0.25, 15.0)),
("gpt-5.2", (2.5, 0.25, 15.0)),
("opus", (15.0, 1.5, 75.0)),
("sonnet", (3.0, 0.3, 15.0)),
("haiku", (0.8, 0.08, 4.0)),
]
def model_price(model: str) -> tuple[float, float, float]:
name = (model or "").lower()
for needle, price in PRICE_PER_MILLION:
if needle in name:
return price
return (0.0, 0.0, 0.0)
def estimate_cost(model: str, input_tokens: int, cached_tokens: int, output_tokens: int) -> float:
input_price, cache_price, output_price = model_price(model)
return (
max(0, input_tokens) * input_price
+ max(0, cached_tokens) * cache_price
+ max(0, output_tokens) * output_price
) / 1_000_000
def codex_speed_cost_multiplier(speed: str) -> float:
normalized = (speed or "").strip().lower()
if normalized in {"fast", "quick", "turbo"}:
return max(1.0, CODEX_FAST_COST_MULTIPLIER)
return 1.0
def speed_badge(cost_multiplier: float | None) -> str:
try:
multiplier = float(cost_multiplier or 1.0)
except (TypeError, ValueError):
multiplier = 1.0
return f"FAST x{multiplier:g}" if multiplier > 1 else ""
def codex_service_tier_to_speed(service_tier: Any) -> str:
tier = str(service_tier or "").strip().lower()
if tier in {"priority", "fast", "flex"}:
return "fast"
if tier in {"standard"}:
return "standard"
if tier in {"default", "auto", "none", "null", ""}:
return ""
return ""
def codex_internal_service_tier_speed(text: str) -> str:
match = INTERNAL_SERVICE_TIER_RE.search(text or "")
if not match:
return ""
return codex_service_tier_to_speed(match.group("tier"))
def codex_log_request_key(text: str, response: dict[str, Any] | None = None) -> str:
if response:
key = str(response.get("prompt_cache_key") or "").strip()
if key:
return key
for pattern in (PROMPT_CACHE_KEY_RE, JSON_PROMPT_CACHE_KEY_RE, CONVERSATION_ID_RE, THREAD_ID_RE):
match = pattern.search(text or "")
if match:
return match.group("key").strip()
return ""
def codex_log_ids(text: str, response: dict[str, Any] | None = None) -> list[str]:
keys: list[str] = []
if response:
for value in (response.get("conversation_id"), response.get("thread_id"), response.get("id")):
key = str(value or "").strip()
if key and key not in keys:
keys.append(key)
for pattern in (CONVERSATION_ID_RE, THREAD_ID_RE, TURN_ID_RE, SESSION_LOOP_THREAD_ID_RE, PROMPT_CACHE_KEY_RE, JSON_PROMPT_CACHE_KEY_RE):
for match in pattern.finditer(text or ""):
key = match.group("key").strip()
if key and key not in keys:
keys.append(key)
return keys
def detect_codex_route(text: str) -> str:
lowered = (text or "").lower()
if not lowered:
return ""
if (
"127.0.0.1:8080/v1/responses" in lowered
or "localhost:8080/v1/responses" in lowered
or "[::1]:8080/v1/responses" in lowered
):
return "sub2api"
if "chatgpt.com/backend-api/codex" in lowered or "responses_websocket" in lowered:
return "official"
return ""
def codex_model_name(model: str) -> str:
name = (model or "").strip()
if not name or name.lower() in {"codex", "unknown"}:
return CODEX_DEFAULT_MODEL
return name
def usage_int(usage: dict[str, Any], key: str) -> int:
try:
return int(usage.get(key) or 0)
except (TypeError, ValueError):
return 0
def add_codex_usage(
bucket: UsageBucket,
model: str,
input_tokens: int,
cached_tokens: int,
output_tokens: int,
when: datetime | None = None,
cost_multiplier: float = 1.0,
) -> None:
uncached_input = max(0, input_tokens - max(0, cached_tokens))
cached_input = max(0, cached_tokens)
output = max(0, output_tokens)
total = uncached_input + cached_input + output
if total <= 0 or total > MAX_SINGLE_EVENT_TOKENS:
return
bucket.requests += 1
bucket.input_tokens += uncached_input
bucket.cached_input_tokens += cached_input
bucket.output_tokens += output
multiplier = max(1.0, cost_multiplier)
bucket.cost += estimate_cost(model, uncached_input, cached_input, output) * multiplier
bucket.add_model(model, total)
bucket.mark_latest(when, model, "fast" if multiplier > 1 else "", multiplier)
def make_codex_event(
model: str,
input_tokens: int,
cached_tokens: int,
output_tokens: int,
when: datetime | None,
app_speed: str = "",
cost_multiplier: float | None = None,
session_id: str = "",
request_key: str = "",
route: str = "",
request_at: datetime | None = None,
) -> UsageEvent | None:
if when is None:
return None
uncached_input = max(0, input_tokens - max(0, cached_tokens))
cached_input = max(0, cached_tokens)
output = max(0, output_tokens)
total = uncached_input + cached_input + output
if total <= 0 or total > MAX_SINGLE_EVENT_TOKENS:
return None
return UsageEvent(
when=when,
model=codex_model_name(model),
input_tokens=uncached_input,
cached_tokens=cached_input,
output_tokens=output,
app_speed=normalize_codex_speed(app_speed),
cost_multiplier=cost_multiplier,
session_id=str(session_id or "").strip(),
request_key=str(request_key or "").strip(),
route=str(route or "").strip().lower(),
request_at=request_at,
)
def add_codex_event_to_bucket(bucket: UsageBucket, event: UsageEvent, cost_multiplier: float = 1.0) -> None:
effective_multiplier = event.cost_multiplier if event.cost_multiplier is not None else cost_multiplier
effective_multiplier = max(1.0, float(effective_multiplier or 1.0))
bucket.requests += 1
bucket.input_tokens += event.input_tokens
bucket.cached_input_tokens += event.cached_tokens
bucket.output_tokens += event.output_tokens
bucket.cost += (
estimate_cost(event.model, event.input_tokens, event.cached_tokens, event.output_tokens)
* effective_multiplier
)
bucket.add_model(event.model, event.total_tokens)
event_speed = event.app_speed or ("fast" if effective_multiplier > 1 else "")
bucket.mark_latest(event.when, event.model, event_speed, effective_multiplier)
def add_bucket(target: UsageBucket, source: UsageBucket) -> None:
target.requests += source.requests
target.input_tokens += source.input_tokens
target.cached_input_tokens += source.cached_input_tokens
target.output_tokens += source.output_tokens
target.cache_creation_input_tokens += source.cache_creation_input_tokens
target.cache_read_input_tokens += source.cache_read_input_tokens
target.cost += source.cost
for model, tokens in source.models.items():
target.models[model] = target.models.get(model, 0) + tokens
target.mark_latest(
source.latest_at,
source.latest_model,
source.latest_app_speed,
source.latest_cost_multiplier,
)
def parse_dt(value: Any) -> datetime | None:
if not value:
return None
try:
text = str(value).replace("Z", "+00:00")
dt = datetime.fromisoformat(text)
if dt.tzinfo is not None:
dt = dt.astimezone(LOCAL_TZ).replace(tzinfo=None)
return dt
except Exception:
return None
def epoch_to_local_datetime(value: Any) -> datetime | None:
try:
seconds = int(value or 0)
except (TypeError, ValueError):
return None
if seconds <= 0:
return None
try:
return datetime.fromtimestamp(seconds, tz=LOCAL_TZ).replace(tzinfo=None)
except (OSError, OverflowError, ValueError):
return None
def parse_json_after_marker(text: str, marker: str) -> dict[str, Any] | None:
pos = text.find(marker)
if pos < 0:
return None
payload = text[pos + len(marker):].lstrip()
try:
value, _ = JSON_DECODER.raw_decode(payload)
except json.JSONDecodeError:
return None
if isinstance(value, dict):
return value
return None
def parse_log_fields(text: str) -> dict[str, str]:
fields: dict[str, str] = {}
for match in LOG_FIELD_RE.finditer(text):
value = match.group("value")
if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
value = value[1:-1]
fields[match.group("key")] = value
return fields
def field_int(fields: dict[str, str], key: str) -> int:
try:
return int(fields.get(key) or 0)
except (TypeError, ValueError):
return 0
def codex_event_from_log_fields(text: str, ts: Any) -> UsageEvent | None:
if "event.kind=response.completed" not in text or "input_token_count=" not in text:
return None
fields = parse_log_fields(text)
input_tokens = field_int(fields, "input_token_count")
cached_tokens = field_int(fields, "cached_token_count")
output_tokens = field_int(fields, "output_token_count")
if input_tokens <= 0 and cached_tokens <= 0 and output_tokens <= 0:
return None
when = parse_dt(fields.get("event.timestamp")) or epoch_to_local_datetime(ts)
app_speed = codex_service_tier_to_speed(fields.get("service_tier"))
multiplier = codex_speed_cost_multiplier(app_speed) if app_speed else None
request_key = codex_log_request_key(text)
ids = codex_log_ids(text)
session_id = ids[0] if ids else request_key
return make_codex_event(
fields.get("slug") or fields.get("model") or CODEX_DEFAULT_MODEL,
input_tokens,
cached_tokens,
output_tokens,
when,
app_speed,
multiplier,
session_id=session_id,
request_key=request_key or session_id,
route=detect_codex_route(text),
request_at=when,
)
def codex_fork_replay_cutoff(lines: list[str]) -> datetime | None:
for line in lines[:20]:
try:
row = json.loads(line)
except json.JSONDecodeError:
continue
if row.get("type") != "session_meta":
continue
payload = row.get("payload") or {}
if payload.get("forked_from_id"):
started = parse_dt(row.get("timestamp"))
if started is None:
return None
return started + timedelta(seconds=2)
return None
def iter_recent_jsonl(root: Path, start: datetime) -> list[Path]:
if not root.exists():
return []
paths: list[Path] = []
seen: set[Path] = set()
def add_path(path: Path) -> None:
try:
resolved = path.resolve()
except OSError:
return
if resolved in seen:
return
parts = {part.lower() for part in resolved.parts}
if any(part.startswith("backup-") for part in parts) or ".tmp" in parts:
return
seen.add(resolved)
paths.append(resolved)
day_dir = root / f"{start.year:04d}" / f"{start.month:02d}" / f"{start.day:02d}"
if day_dir.exists():
for path in day_dir.glob("*.jsonl"):
add_path(path)
for path in root.rglob("*.jsonl"):
try:
modified = datetime.fromtimestamp(path.stat().st_mtime)
except OSError:
continue
if modified >= start - timedelta(hours=2):
add_path(path)
return paths
def scan_codex_events(root: Path, start: datetime, end: datetime) -> list[UsageEvent]:
events: list[UsageEvent] = []
seen_events: set[tuple[str, str, int, int, int, int]] = set()
seen_totals: set[tuple[str, int, int, int, int]] = set()
for path in iter_recent_jsonl(root, start):
last_total = {"input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0}
seen: set[tuple[int, int, int, int]] = set()
try:
lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
continue
session_id = ""
for meta_line in lines[:20]:
try:
meta_row = json.loads(meta_line)
except json.JSONDecodeError:
continue
if meta_row.get("type") != "session_meta":
continue
meta_payload = meta_row.get("payload") or {}
session_id = str(meta_payload.get("id") or "").strip()
break
fork_replay_cutoff = codex_fork_replay_cutoff(lines)
for line in lines:
try:
row = json.loads(line)
except json.JSONDecodeError:
continue
if row.get("type") != "event_msg":
continue
payload = row.get("payload") or {}
if payload.get("type") != "token_count":
continue
info = payload.get("info") or {}
total = info.get("total_token_usage") or {}
ts = parse_dt(row.get("timestamp"))
current = {
"input_tokens": usage_int(total, "input_tokens"),
"cached_input_tokens": usage_int(total, "cached_input_tokens"),
"output_tokens": usage_int(total, "output_tokens"),
}
key = (
current["input_tokens"],
current["cached_input_tokens"],
current["output_tokens"],
usage_int(total, "reasoning_output_tokens"),
)
if key in seen:
continue
seen.add(key)
if ts is None or ts < start:
last_total = current
continue
if ts >= end:
continue
model = codex_model_name(str(row.get("model") or payload.get("model") or "codex"))
total_key = (
model,
current["input_tokens"],
current["cached_input_tokens"],
current["output_tokens"],
usage_int(total, "reasoning_output_tokens"),
)
if fork_replay_cutoff is not None and ts <= fork_replay_cutoff:
seen_totals.add(total_key)
last_total = current
continue
if total_key in seen_totals:
last_total = current
continue
seen_totals.add(total_key)
last_usage = info.get("last_token_usage") or {}
if last_usage:
input_tokens = usage_int(last_usage, "input_tokens")
cached_tokens = usage_int(last_usage, "cached_input_tokens")
output_tokens = usage_int(last_usage, "output_tokens")
event_key = (
str(row.get("timestamp") or ""),
model,
input_tokens,
cached_tokens,
output_tokens,
usage_int(last_usage, "reasoning_output_tokens"),
)
if event_key not in seen_events:
seen_events.add(event_key)
event = make_codex_event(
model,
input_tokens,
cached_tokens,
output_tokens,
ts,
session_id=session_id,
request_key=session_id,
)
if event is not None:
events.append(event)
last_total = current
continue
delta_input = current["input_tokens"] - last_total["input_tokens"]
delta_cached = current["cached_input_tokens"] - last_total["cached_input_tokens"]
delta_output = current["output_tokens"] - last_total["output_tokens"]
if delta_input < 0 or delta_cached < 0 or delta_output < 0:
delta_input = current["input_tokens"]
delta_cached = current["cached_input_tokens"]
delta_output = current["output_tokens"]
if delta_input <= 0 and delta_cached <= 0 and delta_output <= 0:
continue
event_key = (
str(row.get("timestamp") or ""),
model,
delta_input,
delta_cached,
delta_output,
usage_int(total, "reasoning_output_tokens"),
)
if event_key not in seen_events:
seen_events.add(event_key)
event = make_codex_event(
model,
delta_input,
delta_cached,
delta_output,
ts,
session_id=session_id,
request_key=session_id,
)
if event is not None:
events.append(event)
last_total = current
events.sort(key=lambda event: event.when)
return events
def scan_codex_route_markers(home: Path, start: datetime, end: datetime) -> list[RouteMarker]:
db_path = home / ".codex" / "logs_2.sqlite"
if not db_path.exists():
return []
start_epoch = int(start.replace(tzinfo=LOCAL_TZ).timestamp()) - 1800
end_epoch = int(end.replace(tzinfo=LOCAL_TZ).timestamp()) + 300
try:
con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
rows = con.execute(
"""
SELECT ts, feedback_log_body
FROM logs
WHERE ts >= ?
AND ts < ?
AND (
feedback_log_body LIKE '%/v1/responses%'
OR feedback_log_body LIKE '%chatgpt.com/backend-api/codex%'
OR feedback_log_body LIKE '%responses_websocket%'
)
ORDER BY ts ASC, ts_nanos ASC
""",
(start_epoch, end_epoch),
).fetchall()
con.close()
except sqlite3.Error:
return []
markers: list[RouteMarker] = []
for ts, body in rows:
text = str(body or "")
route = detect_codex_route(text)
if not route:
continue
when = epoch_to_local_datetime(ts)
if when is None:
continue
ids = codex_log_ids(text)
request_key = codex_log_request_key(text)
if request_key and request_key not in ids:
ids.append(request_key)
for key in ids:
markers.append(RouteMarker(when=when, route=route, session_id=key, request_key=key))
markers.sort(key=lambda marker: marker.when)
return markers
def apply_codex_route_hints(events: list[UsageEvent], markers: list[RouteMarker]) -> None:
if not events or not markers:
return
by_key: dict[str, list[RouteMarker]] = {}
for marker in markers:
for key in (marker.session_id, marker.request_key):
key = (key or "").strip()
if key:
by_key.setdefault(key, []).append(marker)
marker_times = {
key: [marker.when for marker in sorted(value, key=lambda item: item.when)]
for key, value in by_key.items()
}
for key, value in list(by_key.items()):
by_key[key] = sorted(value, key=lambda item: item.when)
for event in events:
if event.route:
continue
candidates = [key for key in (event.session_id, event.request_key) if key]
for key in candidates:
markers_for_key = by_key.get(key)
times_for_key = marker_times.get(key)
if not markers_for_key or not times_for_key:
continue
pos = bisect_right(times_for_key, event.when) - 1
if pos >= 0:
marker = markers_for_key[pos]
event.route = marker.route
if event.request_at is None:
event.request_at = marker.when
break
def scan_codex_logs2_events(home: Path, start: datetime, end: datetime) -> list[UsageEvent]:
db_path = home / ".codex" / "logs_2.sqlite"
if not db_path.exists():
return []
marker = "Received message "
start_epoch = int(start.replace(tzinfo=LOCAL_TZ).timestamp()) - 300
end_epoch = int(end.replace(tzinfo=LOCAL_TZ).timestamp()) + 300
events: list[UsageEvent] = []
seen_response_ids: set[str] = set()
speed_by_request: dict[str, str] = {}
try:
con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
rows = con.execute(
"""
SELECT ts, feedback_log_body
FROM logs
WHERE ts >= ?
AND ts < ?
AND (
feedback_log_body LIKE '%response.completed%'
OR feedback_log_body LIKE '%service_tier: Some(%'
)
ORDER BY ts ASC, ts_nanos ASC
""",
(start_epoch, end_epoch),
).fetchall()
con.close()
except sqlite3.Error:
return []
for ts, body in rows:
text = str(body or "")
request_key = codex_log_request_key(text)
internal_speed = codex_internal_service_tier_speed(text)
if request_key and internal_speed:
speed_by_request[request_key] = internal_speed
message = parse_json_after_marker(text, marker)
if message is None:
event = codex_event_from_log_fields(text, ts)
if event is not None:
event_key = codex_log_request_key(text)
if event_key and event_key in speed_by_request:
event.app_speed = speed_by_request[event_key]
event.cost_multiplier = codex_speed_cost_multiplier(event.app_speed)
if event is not None:
events.append(event)
continue
if message.get("type") != "response.completed":
event = codex_event_from_log_fields(text, ts)
if event is not None:
event_key = codex_log_request_key(text)
if event_key and event_key in speed_by_request:
event.app_speed = speed_by_request[event_key]
event.cost_multiplier = codex_speed_cost_multiplier(event.app_speed)
if event is not None:
events.append(event)
continue
response = message.get("response") or {}
if not isinstance(response, dict):
continue
response_id = str(response.get("id") or "")
if response_id and response_id in seen_response_ids:
continue
usage = response.get("usage") or {}
if not isinstance(usage, dict):
continue
details = usage.get("input_tokens_details") or {}
if not isinstance(details, dict):
details = {}
when = (
epoch_to_local_datetime(response.get("completed_at"))
or epoch_to_local_datetime(response.get("created_at"))
or epoch_to_local_datetime(ts)
)
response_key = codex_log_request_key(text, response)
ids = codex_log_ids(text, response)
session_id = ids[0] if ids else response_key
app_speed = internal_speed or ""
if response_key and not app_speed:
app_speed = speed_by_request.get(response_key, "")
if not app_speed:
app_speed = codex_service_tier_to_speed(response.get("service_tier"))
multiplier = codex_speed_cost_multiplier(app_speed) if app_speed else None
if when is None or when < start or when >= end:
continue
event = make_codex_event(
str(response.get("model") or CODEX_DEFAULT_MODEL),
usage_int(usage, "input_tokens"),
usage_int(details, "cached_tokens"),
usage_int(usage, "output_tokens"),
when,
app_speed,
multiplier,
session_id=session_id,
request_key=response_key or session_id,
route=detect_codex_route(text),
)
if event is None:
continue
if response_id:
seen_response_ids.add(response_id)
events.append(event)
return events
def dedupe_usage_events(events: list[UsageEvent]) -> list[UsageEvent]:
seen: dict[tuple[int, str, int, int, int], int] = {}
result: list[UsageEvent] = []
for event in sorted(events, key=lambda item: item.when):
key = (
int(event.when.replace(tzinfo=LOCAL_TZ).timestamp()),
event.model,
event.input_tokens,
event.cached_tokens,
event.output_tokens,
)
if key in seen:
existing_idx = seen[key]
existing = result[existing_idx]
existing_score = usage_event_info_score(existing)
event_score = usage_event_info_score(event)
if event_score > existing_score:
result[existing_idx] = event
continue
seen[key] = len(result)
result.append(event)
return result
def codex_event_id(event: UsageEvent) -> str:
parts = [
(event.session_id or event.request_key or "").strip(),
str(int(event.when.replace(tzinfo=LOCAL_TZ).timestamp() * 1000)),
event.model,
str(event.input_tokens),
str(event.cached_tokens),
str(event.output_tokens),
]
return "|".join(parts)
def legacy_codex_event_id(event: UsageEvent) -> str:
if event.request_at is None:
return codex_event_id(event)
parts = [
(event.session_id or event.request_key or "").strip(),
str(int(event.request_at.replace(tzinfo=LOCAL_TZ).timestamp() * 1000)),
event.model,
str(event.input_tokens),
str(event.cached_tokens),
str(event.output_tokens),
]
return "|".join(parts)
def ledger_label_for_event(
event: UsageEvent,
ledger: dict[str, str] | None,
) -> tuple[str, str]:
stable_id = codex_event_id(event)
if ledger is None:
return "", stable_id
label = ledger.get(stable_id, "")
if label:
return label, stable_id
legacy_id = legacy_codex_event_id(event)
label = ledger.get(legacy_id, "")
if label and stable_id:
ledger[stable_id] = label
return label, stable_id
def usage_event_attribution_time(event: UsageEvent) -> datetime:
return event.request_at or event.when
def usage_event_info_score(event: UsageEvent) -> int:
score = 0
if event.route:
score += 8
if event.session_id:
score += 4
if event.request_key:
score += 2
if event.cost_multiplier is not None:
score += 1
if event.request_at is not None:
score += 1
return score
def scan_all_codex_events(home: Path, sessions_root: Path, start: datetime, end: datetime) -> list[UsageEvent]:
events = scan_codex_events(sessions_root, start, end)
events.extend(scan_codex_logs2_events(home, start, end))
route_markers = scan_codex_route_markers(home, start, end)
apply_codex_route_hints(events, route_markers)
return dedupe_usage_events(events)
def bucket_from_codex_events(events: list[UsageEvent]) -> UsageBucket:
bucket = UsageBucket()
for event in events:
add_codex_event_to_bucket(bucket, event)
return bucket
def scan_codex(root: Path, start: datetime, end: datetime) -> UsageBucket:
return bucket_from_codex_events(scan_codex_events(root, start, end))
def local_epoch_ms(value: datetime) -> int:
return int(value.replace(tzinfo=LOCAL_TZ).timestamp() * 1000)
def ms_to_local_datetime(value: int | float | str | None) -> datetime | None:
try:
millis = int(value or 0)
except (TypeError, ValueError):
return None
if millis <= 0:
return None
return datetime.fromtimestamp(millis / 1000, tz=LOCAL_TZ).replace(tzinfo=None)
def cockpit_account_label(account_id: str, email: str, api_key_label: str) -> str:
email = (email or "").strip()
if email:
return f"Codex local - {email}"
api_key_label = (api_key_label or "").strip()
if api_key_label:
return f"Codex local - {api_key_label}"
account_id = (account_id or "").strip()
if account_id:
return f"Codex local - {account_id}"
return "Codex local - Unknown"
def current_codex_account_label(home: Path) -> str:
codex_dir = home / ".codex"
for name in (".cockpit_codex_auth.json", "auth.json"):
path = codex_dir / name
if not path.exists():
continue
try:
data = json.loads(path.read_text(encoding="utf-8", errors="ignore"))
except Exception:
continue
email = str(data.get("email") or data.get("OPENAI_EMAIL") or "").strip()
if not email:
tokens = data.get("tokens") if isinstance(data, dict) else None
if isinstance(tokens, dict):
email = str(tokens.get("email") or "").strip()
if email:
return f"Codex local - {email}"
api_provider_name = str(data.get("api_provider_name") or "").strip()