Repository navigation
Expand file tree
/
Copy pathcodex_usage.py
More file actions
2946 lines (2576 loc) · 108 KB
/
Copy pathcodex_usage.py
File metadata and controls
2946 lines (2576 loc) · 108 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
"""Scan local Codex session logs and render an offline usage dashboard.
Parsing and pricing heuristics are inspired by CodexBar's local usage scanner:
https://github.com/steipete/CodexBar
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import sqlite3
import sys
import time
import urllib.error
import urllib.request
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Callable, Iterable
VERSION = "0.1.4"
COMMANDS = ("dashboard", "daily", "weekly", "monthly", "sessions")
DEFAULT_LIMIT = 10
COMMAND_HELP = {
"dashboard": {
"summary": "Render the full terminal dashboard with cards, daily summary, model breakdown, top sessions, and experimental limit progress.",
"examples": [
"{prog}",
"{prog} dashboard --days 7",
"{prog} dashboard --watch 5",
"{prog} dashboard --censored",
],
},
"daily": {
"summary": "Render a focused day-by-day usage report with input, cached input, output, total tokens, cached ratio, and optional cost.",
"examples": [
"{prog} daily --days 7",
"{prog} daily --since 2026-03-01 --until 2026-03-22",
"{prog} daily --json",
],
},
"weekly": {
"summary": "Render a focused week-by-week usage report using local Monday-based week buckets.",
"examples": [
"{prog} weekly --days 90",
"{prog} weekly --all",
"{prog} weekly --json",
],
},
"monthly": {
"summary": "Render a focused month-by-month usage report across the selected local history window.",
"examples": [
"{prog} monthly --all",
"{prog} monthly --json",
"{prog} monthly --root /path/to/codex-home",
],
},
"sessions": {
"summary": "Render a focused top-sessions report with per-session token totals and optional thread titles.",
"examples": [
"{prog} sessions --days 7",
"{prog} sessions --censored",
"{prog} sessions --json --limit 20",
],
},
}
DEFAULT_REMOTE_PRICING_URL = "https://raw.githubusercontent.com/le-dawg/codex-usage-cli/main/pricing.json"
REMOTE_PRICING_TIMEOUT_SECONDS = 3.0
PRICING_BASE = {
"gpt-5": (1.25e-6, 1e-5, 1.25e-7),
"gpt-5-codex": (1.25e-6, 1e-5, 1.25e-7),
"gpt-5-mini": (2.5e-7, 2e-6, 2.5e-8),
"gpt-5-nano": (5e-8, 4e-7, 5e-9),
"gpt-5-pro": (1.5e-5, 1.2e-4, None),
"gpt-5.1": (1.25e-6, 1e-5, 1.25e-7),
"gpt-5.1-codex": (1.25e-6, 1e-5, 1.25e-7),
"gpt-5.1-codex-max": (1.25e-6, 1e-5, 1.25e-7),
"gpt-5.1-codex-mini": (2.5e-7, 2e-6, 2.5e-8),
"gpt-5.2": (1.75e-6, 1.4e-5, 1.75e-7),
"gpt-5.2-codex": (1.75e-6, 1.4e-5, 1.75e-7),
"gpt-5.2-pro": (2.1e-5, 1.68e-4, None),
"gpt-5.3-chat-latest": (1.75e-6, 1.4e-5, 1.75e-7),
"gpt-5.3-codex": (1.75e-6, 1.4e-5, 1.75e-7),
"gpt-5.3-codex-spark": (0.0, 0.0, 0.0),
"gpt-5.3-codex-spark-preview": (0.0, 0.0, 0.0),
"gpt-5.4": (2.5e-6, 1.5e-5, 2.5e-7),
"gpt-5.4-mini": (7.5e-7, 4.5e-6, 7.5e-8),
"gpt-5.4-nano": (2e-7, 1.25e-6, 2e-8),
"gpt-5.4-pro": (3e-5, 1.8e-4, None),
"gpt-5.5": (5e-6, 3e-5, 5e-7),
"gpt-5.5-pro": (3e-5, 1.8e-4, None),
}
PRICING = dict(PRICING_BASE)
PRICING_SOURCE = "builtin"
PRICING_SOURCE_URL: str | None = None
PRICING_FETCHED_AT: str | None = None
PRICING_ERROR: str | None = None
# Azure OpenAI GPT-5.4 Global Standard SKU (pay-as-you-go, no data-zone residency surcharge)
# Standard Tier (<= 272,000 context tokens):
# Input: $2.50 / 1M -> 2.50e-6 per token
# Cached Input: $0.25 / 1M (90% discount) -> 2.50e-7 per token
# Output: $15.00 / 1M -> 1.50e-5 per token
# Long Context Surcharge Tier (> 272,000 context tokens):
# Input: $5.00 / 1M (2x) -> 5.00e-6 per token
# Cached Input: $0.50 / 1M (2x) -> 5.00e-7 per token
# Output: $22.50 / 1M (1.5x) -> 2.25e-5 per token
DEFAULT_CLAUDE_CONTEXT_THRESHOLD = 272_000
AZURE_GPT54_EU_STD_RATES = (2.50e-6, 1.50e-5, 2.50e-7)
AZURE_GPT54_EU_LONG_RATES = (5.00e-6, 2.25e-5, 5.00e-7)
# Energy heuristic rates are intentionally rough. They provide a consistent
# relative signal from local token counts rather than a wall-power measurement.
BASE_ENERGY_RATES_WH = (2.5e-4, 7.5e-4, 2.5e-5)
MODEL_ENERGY_MULTIPLIER = {
"gpt-5": 1.0,
"gpt-5-codex": 1.0,
"gpt-5-mini": 0.35,
"gpt-5-nano": 0.12,
"gpt-5-pro": 1.6,
"gpt-5.1": 1.0,
"gpt-5.1-codex": 1.0,
"gpt-5.1-codex-max": 1.1,
"gpt-5.1-codex-mini": 0.35,
"gpt-5.2": 1.05,
"gpt-5.2-codex": 1.05,
"gpt-5.2-pro": 1.65,
"gpt-5.3-chat-latest": 1.05,
"gpt-5.3-codex": 1.05,
"gpt-5.3-codex-spark": 0.2,
"gpt-5.3-codex-spark-preview": 0.2,
"gpt-5.4": 1.1,
"gpt-5.4-mini": 0.4,
"gpt-5.4-nano": 0.15,
"gpt-5.4-pro": 1.75,
"gpt-5.5": 1.15,
"gpt-5.5-pro": 1.8,
}
DEFAULT_GRID_INTENSITY_G_CO2E_PER_KWH = 400.0
TREE_ABSORPTION_G_CO2E_PER_YEAR = 22_000.0
MODEL_DATE_SUFFIX = re.compile(r"-\d{4}-\d{2}-\d{2}$")
MODEL_REASONING_SUFFIX = re.compile(r"-(low|medium|high|xhigh)$")
MODEL_TRAILING_NOISE_SUFFIX = re.compile(r"-(latest|stable|snapshot)$")
GPT_VERSION_RE = re.compile(r"^gpt-(\d+(?:\.\d+)?)(.*)$")
SESSION_ID_RE = re.compile(
r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",
re.IGNORECASE,
)
FILENAME_DAY_RE = re.compile(r"(\d{4}-\d{2}-\d{2})")
MODEL_ALIASES = {
"gpt6": "gpt-6",
"gpt6-astra": "gpt-6-astra",
"gpt-6.0": "gpt-6",
"gpt-6.0-astra": "gpt-6-astra",
"gpt-6-astra-preview": "gpt-6-astra",
}
@dataclass
class UsageEvent:
session_id: str
session_title: str | None
day: str
timestamp: str
model: str
input_tokens: int
cached_input_tokens: int
output_tokens: int
plan_type: str | None
estimated_energy_wh: float
estimated_cost_usd: float | None
estimated_cost_is_guess: bool = False
@property
def total_tokens(self) -> int:
return self.input_tokens + self.cached_input_tokens + self.output_tokens
@dataclass
class Aggregate:
input_tokens: int = 0
cached_input_tokens: int = 0
output_tokens: int = 0
events: int = 0
estimated_energy_wh: float = 0.0
estimated_cost_usd: float = 0.0
has_cost: bool = False
has_guessed_cost: bool = False
@property
def total_tokens(self) -> int:
return self.input_tokens + self.cached_input_tokens + self.output_tokens
@property
def cached_ratio(self) -> float:
total_in = self.input_tokens + self.cached_input_tokens
if total_in <= 0:
return 0.0
return self.cached_input_tokens / total_in
@property
def estimated_emissions_g_co2e(self) -> float:
return (self.estimated_energy_wh / 1000.0) * DEFAULT_GRID_INTENSITY_G_CO2E_PER_KWH
@property
def tree_offset_hours(self) -> float:
tree_absorption_per_hour = TREE_ABSORPTION_G_CO2E_PER_YEAR / (365.0 * 24.0)
if tree_absorption_per_hour <= 0:
return 0.0
return self.estimated_emissions_g_co2e / tree_absorption_per_hour
def add(self, event: UsageEvent) -> None:
self.input_tokens += event.input_tokens
self.cached_input_tokens += event.cached_input_tokens
self.output_tokens += event.output_tokens
self.events += 1
self.estimated_energy_wh += event.estimated_energy_wh
if event.estimated_cost_usd is not None:
self.estimated_cost_usd += event.estimated_cost_usd
self.has_cost = True
if event.estimated_cost_is_guess:
self.has_guessed_cost = True
@dataclass
class SessionAggregate(Aggregate):
session_id: str = ""
title: str | None = None
first_day: str | None = None
last_day: str | None = None
first_seen: str | None = None
last_seen: str | None = None
models: dict[str, int] = field(default_factory=dict)
plan_types: dict[str, int] = field(default_factory=dict)
def add(self, event: UsageEvent) -> None:
super().add(event)
self.first_day = min(filter(None, [self.first_day, event.day]), default=event.day)
self.last_day = max(filter(None, [self.last_day, event.day]), default=event.day)
self.first_seen = earlier_timestamp(self.first_seen, event.timestamp)
self.last_seen = later_timestamp(self.last_seen, event.timestamp)
self.models[event.model] = self.models.get(event.model, 0) + event.total_tokens
if event.plan_type:
self.plan_types[event.plan_type] = self.plan_types.get(event.plan_type, 0) + 1
@property
def top_model(self) -> str | None:
if not self.models:
return None
return max(self.models.items(), key=lambda item: item[1])[0]
@dataclass
class ScanDiagnostics:
discovered_files: int = 0
scanned_files: int = 0
duplicate_session_files: int = 0
parsed_events: int = 0
invalid_lines: int = 0
empty_sessions: int = 0
@dataclass
class LimitWindow:
used_percent: float | None = None
window_minutes: int | None = None
reset_after_seconds: int | None = None
reset_at: str | None = None
@dataclass
class LimitBucket:
allowed: bool | None = None
limit_reached: bool | None = None
primary: LimitWindow | None = None
secondary: LimitWindow | None = None
@dataclass
class LimitSnapshot:
captured_at: str | None = None
plan_type: str | None = None
credits_has_credits: bool | None = None
credits_unlimited: bool | None = None
credits_balance: float | None = None
standard: LimitBucket | None = None
code_review: LimitBucket | None = None
additional: dict[str, LimitBucket] = field(default_factory=dict)
@dataclass
class ClaudeSessionAggregate:
session_id: str
project_dir: str
first_seen: str | None = None
last_seen: str | None = None
first_day: str | None = None
last_day: str | None = None
turns: int = 0
uncached_input_tokens: int = 0
cached_input_tokens: int = 0
output_tokens: int = 0
max_context: int = 0
standard_turns: int = 0
long_turns: int = 0
estimated_energy_wh: float = 0.0
estimated_cost_usd: float = 0.0
@property
def total_tokens(self) -> int:
return self.uncached_input_tokens + self.cached_input_tokens + self.output_tokens
@property
def cached_ratio(self) -> float:
total_in = self.uncached_input_tokens + self.cached_input_tokens
return (self.cached_input_tokens / total_in) if total_in > 0 else 0.0
@property
def tier_label(self) -> str:
if self.long_turns > 0:
return f"long ({self.long_turns}x)"
return "standard"
@dataclass
class ClaudeReport:
root: str
since: str | None
until: str | None
summary: Aggregate
daily: dict[str, Aggregate]
daily_session_counts: dict[str, int]
daily_turns: dict[str, int]
daily_long_turns: dict[str, int]
sessions: dict[str, ClaudeSessionAggregate]
diagnostics: ScanDiagnostics
threshold: int
pricing_desc: str = "Azure OpenAI GPT-5.4 Global Standard (Adaptive)"
@dataclass
class UsageReport:
root: str
generated_at: str
since: str | None
until: str | None
summary: Aggregate
daily: dict[str, Aggregate]
daily_session_counts: dict[str, int]
weekly: dict[str, Aggregate]
weekly_session_counts: dict[str, int]
monthly: dict[str, Aggregate]
monthly_session_counts: dict[str, int]
models: dict[str, Aggregate]
sessions: dict[str, SessionAggregate]
plan_types: list[str]
limits: LimitSnapshot | None
diagnostics: ScanDiagnostics
pricing: dict[str, object]
claude: ClaudeReport | None = None
class TerminalUI:
MAX_CARD_COLUMNS = 4
COLORS = {
"reset": "\033[0m",
"bold": "\033[1m",
"dim": "\033[2m",
"cyan": "\033[36m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"red": "\033[31m",
"gray": "\033[90m",
}
SPINNER = ["|", "/", "-", "\\"]
def __init__(self, enabled: bool) -> None:
self.enabled = enabled
self.last_progress_width = 0
self.spinner_index = 0
def style(self, text: str, *names: str) -> str:
if not self.enabled or not names:
return text
prefix = "".join(self.COLORS[name] for name in names)
return f"{prefix}{text}{self.COLORS['reset']}"
def clear(self) -> None:
if self.enabled:
sys.stdout.write("\033[2J\033[H")
sys.stdout.flush()
def update_progress(self, current: int, total: int, path: Path) -> None:
if not self.enabled:
return
spinner = self.SPINNER[self.spinner_index % len(self.SPINNER)]
self.spinner_index += 1
width = shutil.get_terminal_size((100, 24)).columns
path_text = shorten_middle(str(path), max(20, width - 28))
message = f"{spinner} Scanning {current}/{max(total, 1)} {path_text}"
padded = message.ljust(max(self.last_progress_width, len(message)))
sys.stderr.write("\r" + self.style(padded, "cyan"))
sys.stderr.flush()
self.last_progress_width = len(padded)
def finish_progress(self) -> None:
if not self.enabled or self.last_progress_width == 0:
return
sys.stderr.write("\r" + (" " * self.last_progress_width) + "\r")
sys.stderr.flush()
self.last_progress_width = 0
def panel(self, title: str, lines: list[str], color: str = "blue") -> str:
content_widths = [len(strip_ansi(title))]
content_widths.extend(len(strip_ansi(line)) for line in lines)
width = max(content_widths, default=0) + 2
top = f"┌{'─' * (width + 2)}┐"
bottom = f"└{'─' * (width + 2)}┘"
title_line = f"│ {pad_visible(self.style(title, 'bold', color), width)} │"
body = [f"│ {pad_visible(line, width)} │" for line in lines]
return "\n".join([self.style(top, color), title_line, *body, self.style(bottom, color)])
def cards(self, cards: list[tuple[str, str, str, str]]) -> str:
if not cards:
return ""
term_width = shutil.get_terminal_size((100, 24)).columns
card_width = 24
columns = max(1, min(len(cards), self.MAX_CARD_COLUMNS, term_width // (card_width + 2)))
rendered = [self._card(*card, width=card_width) for card in cards]
rows = []
for start in range(0, len(rendered), columns):
batch = rendered[start : start + columns]
split = [item.splitlines() for item in batch]
max_lines = max(len(block) for block in split)
for block in split:
while len(block) < max_lines:
block.append(" " * len(strip_ansi(block[0])))
for idx in range(max_lines):
rows.append(" ".join(block[idx] for block in split))
return "\n".join(rows)
def _card(self, title: str, value: str, subtitle: str, color: str, width: int) -> str:
inner = width - 2
top = self.style(f"┌{'─' * width}┐", color)
bottom = self.style(f"└{'─' * width}┘", color)
lines = [
f"│ {pad_visible(self.style(title, 'bold', color), inner)} │",
f"│ {pad_visible(self.style(value, 'bold'), inner)} │",
f"│ {pad_visible(self.style(subtitle, 'dim'), inner)} │",
]
return "\n".join([top, *lines, bottom])
def default_codex_home() -> Path:
override = os.environ.get("CODEX_HOME", "").strip()
if override:
return Path(override).expanduser()
return Path.home() / ".codex"
def as_int(value: object) -> int:
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return int(value)
return 0
def as_float(value: object) -> float | None:
if isinstance(value, bool):
return float(int(value))
if isinstance(value, (int, float)):
return float(value)
return None
def as_bool(value: object) -> bool | None:
return value if isinstance(value, bool) else None
def parse_rate_per_token(value: object) -> float | None:
numeric = as_float(value)
if numeric is None or numeric < 0:
return None
return numeric / 1_000_000.0
def canonicalize_model_name(raw: str | None) -> str:
if not raw:
return "unknown"
model = raw.strip().lower()
for prefix in ("openai/", "openai:", "models/", "model:"):
while model.startswith(prefix):
model = model.removeprefix(prefix)
model = model.replace("_", "-")
model = re.sub(r"\s+", "-", model)
model = re.sub(r"-{2,}", "-", model).strip("-")
return model or "unknown"
def apply_model_alias(model: str) -> str:
return MODEL_ALIASES.get(model, model)
def parse_remote_pricing_models(payload: object) -> dict[str, tuple[float, float, float | None]]:
if not isinstance(payload, dict):
return {}
raw_models = payload.get("models", payload)
if not isinstance(raw_models, dict):
return {}
parsed: dict[str, tuple[float, float, float | None]] = {}
for model_name, rates in raw_models.items():
if not isinstance(model_name, str):
continue
if not isinstance(rates, dict):
continue
normalized_model = apply_model_alias(canonicalize_model_name(model_name))
if not normalized_model or normalized_model == "unknown":
continue
input_rate = parse_rate_per_token(rates.get("input_per_1m_usd"))
output_rate = parse_rate_per_token(rates.get("output_per_1m_usd"))
if input_rate is None or output_rate is None:
continue
cached_value = rates.get("cached_input_per_1m_usd")
cached_rate = None if cached_value is None else parse_rate_per_token(cached_value)
if cached_value is not None and cached_rate is None:
continue
parsed[normalized_model] = (input_rate, output_rate, cached_rate)
return parsed
def refresh_runtime_pricing(pricing_url: str | None) -> dict[str, object]:
global PRICING, PRICING_SOURCE, PRICING_SOURCE_URL, PRICING_FETCHED_AT, PRICING_ERROR
PRICING = dict(PRICING_BASE)
PRICING_SOURCE = "builtin"
PRICING_SOURCE_URL = None
PRICING_FETCHED_AT = None
PRICING_ERROR = None
metadata: dict[str, object] = {
"source": PRICING_SOURCE,
"url": None,
"fetched_at": None,
"model_count": len(PRICING),
"error": None,
}
if not pricing_url:
metadata["source"] = "builtin-disabled"
return metadata
try:
with urllib.request.urlopen(pricing_url, timeout=REMOTE_PRICING_TIMEOUT_SECONDS) as response:
body = response.read()
payload = json.loads(body.decode("utf-8"))
parsed_models = parse_remote_pricing_models(payload)
if not parsed_models:
raise ValueError("remote pricing payload had no valid models")
PRICING.update(parsed_models)
PRICING_SOURCE = "remote"
PRICING_SOURCE_URL = pricing_url
PRICING_FETCHED_AT = datetime.now().astimezone().isoformat(timespec="seconds")
metadata.update(
{
"source": PRICING_SOURCE,
"url": PRICING_SOURCE_URL,
"fetched_at": PRICING_FETCHED_AT,
"model_count": len(PRICING),
"error": None,
}
)
return metadata
except (urllib.error.URLError, OSError, TimeoutError, json.JSONDecodeError, ValueError) as exc:
PRICING_ERROR = str(exc)
metadata.update(
{
"source": "builtin-fallback",
"url": pricing_url,
"fetched_at": None,
"model_count": len(PRICING),
"error": PRICING_ERROR,
}
)
return metadata
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Local Codex Usage Viewer",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"command",
nargs="?",
choices=COMMANDS,
default="dashboard",
help="Report type to render. Defaults to dashboard.",
)
parser.add_argument(
"--root",
type=Path,
default=default_codex_home(),
help="Codex home directory. Defaults to $CODEX_HOME or ~/.codex.",
)
parser.add_argument(
"--days",
type=int,
default=30,
help="Rolling day window to include. Ignored with --all or --since.",
)
parser.add_argument(
"--all",
action="store_true",
help="Include all locally available history.",
)
parser.add_argument(
"--since",
type=str,
help="Inclusive start date in YYYY-MM-DD format.",
)
parser.add_argument(
"--until",
type=str,
help="Inclusive end date in YYYY-MM-DD format. Defaults to today.",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Rows to show. Defaults to all rows for period reports and 10 rows for dashboard/session sections.",
)
parser.add_argument(
"--daily-limit",
type=int,
default=14,
help="Rows to show in the daily section.",
)
parser.add_argument(
"--watch",
type=float,
default=0.0,
help="Refresh every N seconds.",
)
parser.add_argument(
"--json",
action="store_true",
help="Emit machine-readable JSON instead of the terminal dashboard.",
)
parser.add_argument(
"--no-cost",
action="store_true",
help="Skip estimated-cost calculation and hide cost fields.",
)
parser.add_argument(
"--plain",
action="store_true",
help="Disable ANSI colors.",
)
parser.add_argument(
"--censored",
action="store_true",
help="Hide thread titles in dashboard and JSON output.",
)
parser.add_argument(
"--pricing-url",
type=str,
default=os.environ.get("CUV_PRICING_URL", DEFAULT_REMOTE_PRICING_URL),
help=(
"Remote pricing JSON URL used to refresh heuristic model rates at runtime. "
"Use an empty value to disable remote pricing refresh."
),
)
parser.add_argument(
"-claude",
"--claude",
action="store_true",
help="Include Claude Code session usage and separate cost tables (using Azure GPT-5.4 Global Standard pricing).",
)
parser.add_argument(
"--claude-root",
type=Path,
default=Path(os.environ.get("CLAUDE_HOME", "~/.claude")).expanduser(),
help="Claude Code home directory. Defaults to $CLAUDE_HOME or ~/.claude.",
)
parser.add_argument(
"--claude-threshold",
type=int,
default=DEFAULT_CLAUDE_CONTEXT_THRESHOLD,
help=f"Context token threshold for Azure GPT-5.4 Global Standard pricing adaptation (default: {DEFAULT_CLAUDE_CONTEXT_THRESHOLD}).",
)
parser.add_argument(
"--version",
"-v",
action="version",
version=f"%(prog)s {VERSION}",
)
parser.epilog = build_general_help_epilog(parser.prog)
return parser
def parse_args(parser: argparse.ArgumentParser, argv: list[str] | None = None) -> argparse.Namespace:
return parser.parse_args(argv)
def build_general_help_epilog(prog: str) -> str:
lines = [
"Commands:",
" dashboard Full dashboard view (default)",
" daily Day-by-day usage report",
" weekly Week-by-week usage report",
" monthly Month-by-month usage report",
" sessions Top sessions report",
"",
"Examples:",
f" {prog}",
f" {prog} daily --days 7",
f" {prog} weekly --days 90",
f" {prog} monthly --all",
f" {prog} sessions --days 7 --censored",
f" {prog} help daily",
]
return "\n".join(lines)
def print_command_help(parser: argparse.ArgumentParser, topic: str | None) -> None:
if topic is None:
parser.print_help()
return
command = COMMAND_HELP[topic]
prog = parser.prog
examples = "\n".join(f" {example.format(prog=prog)}" for example in command["examples"])
text = "\n".join(
[
f"{prog} {topic}",
"",
command["summary"],
"",
"Examples:",
examples,
"",
"Common options:",
" --days N Rolling day window",
" --since YYYY-MM-DD Inclusive start date",
" --until YYYY-MM-DD Inclusive end date",
" --all Include all local history",
" --limit N Cap report rows",
" --json Emit machine-readable JSON",
" --censored Hide thread titles and local path",
" --no-cost Hide heuristic cost estimates",
" --pricing-url URL Runtime pricing JSON source",
" --root /path/to/codex-home Scan a different Codex home",
]
)
print(text)
def maybe_handle_help_command(parser: argparse.ArgumentParser, argv: list[str]) -> bool:
if not argv:
return False
if argv[0] == "help":
if len(argv) > 2:
parser.error("help accepts at most one topic")
topic = argv[1] if len(argv) == 2 else None
if topic is not None and topic not in COMMANDS:
parser.error(f"unknown help topic: {topic}")
print_command_help(parser, topic)
return True
if argv[0] in COMMANDS and any(arg in ("-h", "--help") for arg in argv[1:]):
print_command_help(parser, argv[0])
return True
return False
def parse_day(text: str) -> date:
return date.fromisoformat(text)
def choose_window(args: argparse.Namespace) -> tuple[date | None, date | None]:
if args.all:
return None, None
today = datetime.now().astimezone().date()
until = parse_day(args.until) if args.until else today
since = parse_day(args.since) if args.since else until - timedelta(days=max(args.days - 1, 0))
return since, until
def list_session_files(root: Path, since: date | None, until: date | None) -> list[Path]:
sessions_root = root / "sessions"
archived_root = root / "archived_sessions"
files: list[Path] = []
yielded: set[Path] = set()
# Expand the scan partition window by 1 day on each end so that sessions active across
# UTC/local midnight boundaries or starting on an adjacent calendar day are discovered.
# Individual events are still strictly filtered by their exact local day in collect_events.
scan_since = since - timedelta(days=1) if since is not None else None
scan_until = until + timedelta(days=1) if until is not None else None
for path in iter_partitioned_files(sessions_root, scan_since, scan_until):
files.append(path)
yielded.add(path)
if archived_root.is_dir():
for path in sorted(archived_root.glob("*.jsonl")):
if path in yielded:
continue
day = day_from_filename(path.name)
if day is not None and scan_since is not None and scan_until is not None and (day < scan_since or day > scan_until):
continue
files.append(path)
return files
def iter_partitioned_files(root: Path, since: date | None, until: date | None) -> Iterable[Path]:
if not root.is_dir():
return
if since is None or until is None:
yield from sorted(root.rglob("*.jsonl"))
return
current = since
while current <= until:
day_dir = root / f"{current.year:04d}" / f"{current.month:02d}" / f"{current.day:02d}"
if day_dir.is_dir():
yield from sorted(day_dir.glob("*.jsonl"))
current += timedelta(days=1)
def day_from_filename(filename: str) -> date | None:
match = FILENAME_DAY_RE.search(filename)
if not match:
return None
try:
return date.fromisoformat(match.group(1))
except ValueError:
return None
def load_session_index(root: Path) -> dict[str, dict]:
session_index = root / "session_index.jsonl"
mapping: dict[str, dict] = {}
if not session_index.is_file():
return mapping
with session_index.open() as handle:
for line in handle:
try:
item = json.loads(line)
except json.JSONDecodeError:
continue
session_id = item.get("id")
if session_id:
mapping[session_id] = item
return mapping
def load_limit_snapshot(root: Path) -> LimitSnapshot | None:
db_path = root / "logs_1.sqlite"
if not db_path.is_file():
return None
query = """
SELECT ts, feedback_log_body
FROM logs
WHERE target = 'codex_api::endpoint::responses_websocket'
AND feedback_log_body LIKE '%websocket event: {"type":"codex.rate_limits"%'
ORDER BY ts DESC, ts_nanos DESC, id DESC
LIMIT 25
"""
prefix = "websocket event: "
try:
connection = sqlite3.connect(str(db_path))
try:
rows = connection.execute(query).fetchall()
finally:
connection.close()
except sqlite3.Error:
return None
for ts, body in rows:
if not body or prefix not in body:
continue
raw_payload = body.split(prefix, 1)[1].strip()
try:
payload = json.loads(raw_payload)
except json.JSONDecodeError:
continue
if payload.get("type") != "codex.rate_limits":
continue
credits = payload.get("credits") if isinstance(payload.get("credits"), dict) else {}
additional_payload = (
payload.get("additional_rate_limits")
if isinstance(payload.get("additional_rate_limits"), dict)
else {}
)
additional: dict[str, LimitBucket] = {}
for name, item in additional_payload.items():
bucket = parse_limit_bucket(item)
if bucket is not None:
additional[name] = bucket
snapshot = LimitSnapshot(
captured_at=epoch_to_local_timestamp(ts),
plan_type=payload.get("plan_type") if isinstance(payload.get("plan_type"), str) else None,
credits_has_credits=as_bool(credits.get("has_credits")),
credits_unlimited=as_bool(credits.get("unlimited")),
credits_balance=as_float(credits.get("balance")),
standard=parse_limit_bucket(payload.get("rate_limits")),
code_review=parse_limit_bucket(payload.get("code_review_rate_limits")),
additional=additional,
)
if has_limit_snapshot_data(snapshot):
return snapshot
return None
def has_limit_snapshot_data(snapshot: LimitSnapshot) -> bool:
return any(
[
snapshot.plan_type,
snapshot.standard,
snapshot.code_review,
snapshot.additional,
snapshot.credits_has_credits is not None,
snapshot.credits_unlimited is not None,
snapshot.credits_balance is not None,
]
)
def parse_limit_bucket(payload: object) -> LimitBucket | None:
if not isinstance(payload, dict):
return None
bucket = LimitBucket(
allowed=as_bool(payload.get("allowed")),
limit_reached=as_bool(payload.get("limit_reached")),
primary=parse_limit_window(payload.get("primary")),
secondary=parse_limit_window(payload.get("secondary")),
)
if any([bucket.allowed is not None, bucket.limit_reached is not None, bucket.primary, bucket.secondary]):
return bucket
return None
def parse_limit_window(payload: object) -> LimitWindow | None:
if not isinstance(payload, dict):
return None
window = LimitWindow(
used_percent=as_float(payload.get("used_percent")),
window_minutes=as_int(payload.get("window_minutes")) or None,
reset_after_seconds=as_int(payload.get("reset_after_seconds")) or None,
reset_at=epoch_to_local_timestamp(payload.get("reset_at")),
)
if any(
[
window.used_percent is not None,
window.window_minutes is not None,
window.reset_after_seconds is not None,
window.reset_at is not None,
]
):
return window
return None
def strip_model_suffixes(model: str) -> str:
stripped = model
while True:
updated = MODEL_DATE_SUFFIX.sub("", stripped)
updated = MODEL_REASONING_SUFFIX.sub("", updated)
updated = MODEL_TRAILING_NOISE_SUFFIX.sub("", updated)
if updated == stripped:
return updated
stripped = updated
def pricing_variant(model: str) -> str:
match = GPT_VERSION_RE.match(model)