-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcodex_usage.py
More file actions
executable file
·3166 lines (2858 loc) · 110 KB
/
Copy pathcodex_usage.py
File metadata and controls
executable file
·3166 lines (2858 loc) · 110 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
"""
Codex Usage
===========
Repository: https://github.com/MacSteini/Codex-Usage
Author: MacSteini
Licence: MIT
A single-file command-line tool for Codex users. It shows reset credits,
rate-limit windows, local usage metadata, read-only online usage/profile data,
and report exports beside the script.
It uses the existing Codex login at auth.json inside the Codex home directory.
It does not require an OpenAI API key. It does not print auth tokens, account
IDs, email addresses, prompts, assistant replies, commands, diffs, transcripts,
or secrets.
"""
from __future__ import annotations
import argparse
import contextlib
import csv
import io
import json
import math
import os
import re
import shutil
import sqlite3
import sys
import textwrap
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
def resolve_codex_home() -> Path:
codex_home = os.environ.get("CODEX_HOME")
if codex_home:
return Path(codex_home).expanduser()
return Path.home() / ".codex"
CODEX_HOME = resolve_codex_home()
AUTH_PATH = CODEX_HOME / "auth.json"
SCRIPT_DIR = Path(__file__).resolve().parent
EXPORT_DIR = SCRIPT_DIR
API_BASE = "https://chatgpt.com/backend-api"
ADMIN_API_BASE = "https://api.openai.com/v1"
ORIGINATOR = "Codex Desktop"
USER_AGENT = "codex-usage-local-script/3.0"
ADMIN_KEY_ENV = "OPENAI_ADMIN_KEY"
ADMIN_MAX_PAGES = 10
USAGE_FIELDS = [
"input_tokens",
"cached_input_tokens",
"output_tokens",
"reasoning_output_tokens",
"total_tokens",
]
ONLINE_ENDPOINTS = {
"rate_limit_status": "/wham/usage",
"daily_token_usage_breakdown": "/wham/usage/daily-token-usage-breakdown",
"credit_usage_events": "/wham/usage/credit-usage-events",
"profile": "/wham/profiles/me",
}
SENSITIVE_KEY_RE = re.compile(
r"(access[_-]?token|refresh[_-]?token|id[_-]?token|authorization|secret|password|cookie|session|account[_-]?id|email|phone)",
re.I,
)
INTERESTING_ONLINE_KEY_RE = re.compile(
r"(usage|token|credit|limit|remaining|reset|plan|tier|quota|rate|bucket|daily|lifetime|status|used|expires|renew|model|source)",
re.I,
)
ADMIN_USAGE_GROUP_FIELDS = {
"project_id",
"user_id",
"api_key_id",
"model",
"batch",
"service_tier",
}
ADMIN_COST_GROUP_FIELDS = {"project_id", "line_item", "api_key_id"}
ADMIN_IDENTIFIER_KEYS = {"api_key_id", "organization_id", "project_id", "user_id"}
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
ANSI = {
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"bold": "\033[1m",
"dim": "\033[2m",
"reset": "\033[0m",
}
COLOR_ENABLED = sys.stdout.isatty() and os.environ.get("NO_COLOR") is None
def die(message: str, exit_code: int = 1) -> None:
print(f"❌ {message}", file=sys.stderr)
raise SystemExit(exit_code)
def set_colour_mode(mode: str | None) -> None:
global COLOR_ENABLED
if mode == "always":
COLOR_ENABLED = True
elif mode == "never":
COLOR_ENABLED = False
else:
COLOR_ENABLED = sys.stdout.isatty() and os.environ.get("NO_COLOR") is None
def colour(text: str, name: str) -> str:
if not COLOR_ENABLED:
return text
return f"{ANSI.get(name, '')}{text}{ANSI['reset']}"
def local_now_text() -> str:
return datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z %z")
def fmt_int(value: int | float | None) -> str:
if value is None:
return "—"
return f"{int(value):,}"
def fmt_number(value: Any, decimals: int = 2) -> str:
if value is None:
return "—"
if isinstance(value, bool):
return str(value)
if isinstance(value, int):
return fmt_int(value)
if isinstance(value, float):
if value.is_integer():
return fmt_int(value)
return f"{value:,.{decimals}f}"
return str(value)
def numeric_sort_value(value: Any) -> float:
if isinstance(value, bool):
return 0.0
if isinstance(value, (int, float)):
number = float(value)
return number if math.isfinite(number) else 0.0
if isinstance(value, str):
try:
number = float(value.strip())
except ValueError:
return 0.0
return number if math.isfinite(number) else 0.0
return 0.0
def fmt_percent(value: float | None) -> str:
if value is None:
return "—"
return f"{value:.1f}%"
def print_kv(label: str, value: Any, width: int = 28) -> None:
print(f"{label + ':':<{width}} {value}")
def print_json(data: Any) -> None:
print(json.dumps(data, indent=2, ensure_ascii=False))
def fmt_local_timestamp(value: Any) -> str:
if value is None or value == "":
return "—"
if isinstance(value, (int, float)) or (isinstance(value, str) and value.isdigit()):
number = float(value)
if number > 10_000_000_000:
number /= 1000
try:
return (
datetime.fromtimestamp(number)
.astimezone()
.strftime("%Y-%m-%d %H:%M:%S %Z %z")
)
except (OSError, OverflowError, ValueError):
return str(value)
if isinstance(value, str):
try:
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
return dt.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z %z")
except ValueError:
return value
return str(value)
def parse_dt(value: str | None) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def fmt_dt(value: str | None) -> tuple[str, str, str, float | None]:
dt = parse_dt(value)
if dt is None:
return (value or "—", "—", "—", None)
utc_dt = dt.astimezone(timezone.utc)
local_dt = dt.astimezone()
now = datetime.now(timezone.utc)
delta = utc_dt - now
days_remaining = delta.total_seconds() / 86400
if delta.total_seconds() < 0:
remaining = "expired"
else:
remaining = "in " + fmt_duration_seconds(delta.total_seconds())
utc_text = utc_dt.strftime("%Y-%m-%d %H:%M:%S UTC")
local_text = local_dt.strftime("%Y-%m-%d %H:%M:%S %Z %z")
return local_text, utc_text, remaining, days_remaining
def fmt_duration_seconds(value: Any) -> str:
try:
seconds = int(float(value))
except (TypeError, ValueError):
return "—"
if seconds < 0:
return "expired"
days, rem = divmod(seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, seconds = divmod(rem, 60)
parts: list[str] = []
if days:
parts.append(f"{days} day{'s' if days != 1 else ''}")
if hours:
parts.append(f"{hours} hr{'s' if hours != 1 else ''}")
if minutes and len(parts) < 2:
parts.append(f"{minutes} min{'s' if minutes != 1 else ''}")
if not parts:
parts.append(f"{seconds} sec{'s' if seconds != 1 else ''}")
return ", ".join(parts[:2])
def fmt_epoch_local(value: Any) -> str:
return fmt_local_timestamp(value)
def display_width(value: str) -> int:
width = 0
for char in strip_ansi(value):
category = unicodedata.category(char)
if category in {"Mn", "Me", "Cf"}:
continue
width += 2 if unicodedata.east_asian_width(char) in {"F", "W"} else 1
return width
def strip_ansi(value: str) -> str:
return re.sub(r"\x1b\[[0-9;]*m", "", value)
def pad_display(value: str, width: int) -> str:
return value + " " * max(0, width - display_width(value))
def truncate_display(value: str, width: int) -> str:
if display_width(value) <= width:
return value
if width <= 1:
return "…"[:width]
out = ""
used = 0
for char in value:
if unicodedata.category(char) in {"Mn", "Me", "Cf"}:
out += char
continue
char_width = 2 if unicodedata.east_asian_width(char) in {"F", "W"} else 1
if used + char_width > width - 1:
break
out += char
used += char_width
return out + "…"
def terminal_width() -> int:
return shutil.get_terminal_size((140, 24)).columns
def make_table(
headers: list[str], rows: list[list[str]], max_width: int | None = None
) -> str:
max_width = max_width or min(max(80, terminal_width()), 180)
clean_rows = [[str(cell) for cell in row] for row in rows]
widths = [display_width(h) for h in headers]
for row in clean_rows:
for i, cell in enumerate(row):
widths[i] = max(widths[i], display_width(cell))
min_widths = [
min(max(display_width(headers[i]), 8), widths[i]) for i in range(len(widths))
]
def total_table_width() -> int:
return sum(widths) + (3 * len(widths)) + 1
while widths and total_table_width() > max_width:
candidates = [i for i, w in enumerate(widths) if w > min_widths[i]]
if not candidates:
break
i = max(candidates, key=lambda idx: widths[idx])
widths[i] -= 1
def line(left: str, sep: str, right: str, fill: str = "─") -> str:
return left + sep.join(fill * (w + 2) for w in widths) + right
def row(cells: list[str]) -> str:
truncated = [truncate_display(cells[i], widths[i]) for i in range(len(widths))]
return (
"│ "
+ " │ ".join(
pad_display(truncated[i], widths[i]) for i in range(len(widths))
)
+ " │"
)
out = [line("┌", "┬", "┐"), row(headers), line("├", "┼", "┤")]
out.extend(row(r) for r in clean_rows)
out.append(line("└", "┴", "┘"))
return "\n".join(out)
def print_counter_table(title: str, headers: list[str], rows: list[list[str]]) -> None:
print(colour(title, "bold"))
print("-" * len(title))
if rows:
print(make_table(headers, rows))
else:
print("No data found.")
print()
def short_path(path_value: str | None, max_chars: int = 48) -> str:
if not path_value:
return "—"
home = str(Path.home())
text = str(path_value).replace(home, "~")
if len(text) <= max_chars:
return text
parts = Path(text).parts
if len(parts) >= 3:
text = f"{parts[0]}/…/{parts[-1]}"
if len(text) > max_chars:
text = text[: max_chars - 1] + "…"
return text
def section(title: str) -> None:
print(colour(title, "bold"))
print("=" * display_width(title))
def explain(text: str) -> None:
width = min(max(72, terminal_width() - 4), 110)
for paragraph in text.split("\n"):
paragraph = paragraph.strip()
if paragraph:
print(textwrap.fill(paragraph, width=width))
else:
print()
print()
def load_auth() -> tuple[str, str]:
if not AUTH_PATH.exists():
die(f"Codex auth file not found: {AUTH_PATH}")
try:
auth = json.loads(AUTH_PATH.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
die(f"Could not parse {AUTH_PATH} as JSON: {exc}")
except OSError as exc:
die(f"Could not read {AUTH_PATH}: {exc}")
tokens = auth.get("tokens")
if not isinstance(tokens, dict):
die(f"Unexpected format in {AUTH_PATH}: field 'tokens' is missing.")
access_token = tokens.get("access_token")
account_id = tokens.get("account_id")
if not access_token or not account_id:
die(
"Unexpected format in auth.json: 'tokens.access_token' or "
"'tokens.account_id' is missing. Are you signed in to Codex CLI/Desktop?"
)
return access_token, account_id
def build_url(path_or_url: str) -> str:
if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
return path_or_url
return API_BASE.rstrip("/") + "/" + path_or_url.lstrip("/")
def fetch_json(
path_or_url: str, access_token: str, account_id: str, timeout: int = 25
) -> dict[str, Any]:
req = urllib.request.Request(
build_url(path_or_url),
headers={
"Authorization": f"Bearer {access_token}",
"ChatGPT-Account-ID": account_id,
"originator": ORIGINATOR,
"User-Agent": USER_AGENT,
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
raw = response.read().decode("utf-8", "replace")
status = response.status
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", "replace")[:1000]
return {
"ok": False,
"status": exc.code,
"reason": exc.reason,
"body_excerpt": redact(body),
}
except urllib.error.URLError as exc:
return {"ok": False, "error": f"Network error: {exc}"}
except TimeoutError:
return {"ok": False, "error": "Timed out whilst fetching data."}
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
return {
"ok": False,
"status": status,
"error": f"Response was not valid JSON: {exc}",
"body_excerpt": redact(raw[:1000]),
}
return {"ok": True, "status": status, "data": data}
def admin_api_key() -> str | None:
value = os.environ.get(ADMIN_KEY_ENV)
return value.strip() if value and value.strip() else None
def build_admin_url(path: str, params: dict[str, Any]) -> str:
clean_params = {k: v for k, v in params.items() if v not in (None, "", [])}
query = urllib.parse.urlencode(clean_params, doseq=True)
url = ADMIN_API_BASE.rstrip("/") + "/" + path.lstrip("/")
return f"{url}?{query}" if query else url
def fetch_admin_json(
path: str, params: dict[str, Any], admin_key: str, timeout: int = 25
) -> dict[str, Any]:
req = urllib.request.Request(
build_admin_url(path, params),
headers={
"Authorization": f"Bearer {admin_key}",
"Content-Type": "application/json",
"User-Agent": USER_AGENT,
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
raw = response.read().decode("utf-8", "replace")
status = response.status
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", "replace")[:1000]
return {
"ok": False,
"status": exc.code,
"reason": exc.reason,
"body_excerpt": redact_admin(body),
}
except urllib.error.URLError as exc:
return {"ok": False, "error": f"Network error: {exc}"}
except TimeoutError:
return {"ok": False, "error": "Timed out whilst fetching Admin API data."}
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
return {
"ok": False,
"status": status,
"error": f"Response was not valid JSON: {exc}",
"body_excerpt": redact_admin(raw[:1000]),
}
return {"ok": True, "status": status, "data": data}
def redact(value: Any, key: str | None = None) -> Any:
if key and SENSITIVE_KEY_RE.search(key):
return "[REDACTED]"
if isinstance(value, dict):
return {k: redact(v, str(k)) for k, v in value.items()}
if isinstance(value, list):
return [redact(v, key) for v in value]
if isinstance(value, str):
text = EMAIL_RE.sub("[REDACTED_EMAIL]", value)
if len(text) > 300:
return text[:297] + "…"
return text
return value
def shorten_identifier(value: str, visible: int = 6) -> str:
if len(value) <= visible * 2 + 1:
return "[REDACTED_ID]"
return f"{value[:visible]}…{value[-visible:]}"
def redact_admin(value: Any, key: str | None = None) -> Any:
key_text = str(key or "")
if key_text in ADMIN_IDENTIFIER_KEYS:
if value in (None, ""):
return value
return shorten_identifier(str(value))
if key and SENSITIVE_KEY_RE.search(key):
return "[REDACTED]"
if isinstance(value, dict):
return {k: redact_admin(v, str(k)) for k, v in value.items()}
if isinstance(value, list):
return [redact_admin(v, key) for v in value]
if isinstance(value, str):
text = EMAIL_RE.sub("[REDACTED_EMAIL]", value)
if len(text) > 300:
return text[:297] + "…"
return text
return value
def collect_resets() -> dict[str, Any]:
access_token, account_id = load_auth()
response = fetch_json("/wham/rate-limit-reset-credits", access_token, account_id)
if not response.get("ok"):
return {"retrieved_at_local": local_now_text(), "ok": False, "error": response}
data = response.get("data") if isinstance(response.get("data"), dict) else {}
credits_raw = data.get("credits", []) if isinstance(data, dict) else []
credits = credits_raw if isinstance(credits_raw, list) else []
normalised = [normalise_credit_for_json(c) for c in credits if isinstance(c, dict)]
return {
"retrieved_at_local": local_now_text(),
"ok": True,
"available_count": data.get("available_count"),
"credits_returned": len(normalised),
"total_earned_count": data.get("total_earned_count"),
"credits": normalised,
"note": "Endpoint is undocumented and may change. Token is not printed.",
}
def normalise_credit_for_json(credit: dict[str, Any]) -> dict[str, Any]:
local_expiry, utc_expiry, remaining, days_remaining = fmt_dt(
credit.get("expires_at")
)
local_granted, utc_granted, _, _ = fmt_dt(credit.get("granted_at"))
return {
"reset_type": credit.get("reset_type"),
"status": credit.get("status"),
"granted_at": credit.get("granted_at"),
"granted_at_local": local_granted,
"granted_at_utc": utc_granted,
"expires_at": credit.get("expires_at"),
"expires_at_local": local_expiry,
"expires_at_utc": utc_expiry,
"time_remaining": remaining,
"days_remaining": days_remaining,
"redeem_started_at": credit.get("redeem_started_at"),
"redeemed_at": credit.get("redeemed_at"),
}
def reset_warnings(reset_data: dict[str, Any], warn_days: int) -> list[str]:
warnings: list[str] = []
if not reset_data.get("ok", True):
warnings.append("Could not fetch reset credits.")
return warnings
for i, credit in enumerate(reset_data.get("credits", []), start=1):
status = str(credit.get("status") or "unknown")
days = credit.get("days_remaining")
if status == "available" and isinstance(days, (int, float)):
if days < 0:
warnings.append(f"Reset #{i} has expired.")
elif days <= warn_days:
warnings.append(
f"Reset #{i} expires soon: {credit.get('time_remaining')} ({credit.get('expires_at_local')})."
)
return warnings
def print_resets(reset_data: dict[str, Any], warn_days: int = 7) -> None:
section("Codex Rate-Limit Reset Credits")
explain(
"Reset credits are spare one-use allowances for Codex rate limits. This report shows how many are available and when each one expires in your local timezone."
)
if not reset_data.get("ok", True):
print_counter_table(
"Reset credit overview",
["Metric", "Value"],
[
["Retrieved", reset_data.get("retrieved_at_local", local_now_text())],
["Status", colour("error", "red")],
],
)
print(json.dumps(reset_data.get("error"), indent=2, ensure_ascii=False))
return
overview_rows = [
["Retrieved", reset_data.get("retrieved_at_local", local_now_text())],
["Available resets", reset_data.get("available_count", "—")],
["Credits returned", reset_data.get("credits_returned", "—")],
["Total earned count", reset_data.get("total_earned_count", "—")],
["Expiry warning window", f"{warn_days} day{'s' if warn_days != 1 else ''}"],
]
print_counter_table("Reset credit overview", ["Metric", "Value"], overview_rows)
warnings = reset_warnings(reset_data, warn_days)
if warnings:
print(colour("Warnings", "yellow"))
for item in warnings:
print(f" ⚠️ {item}")
print()
credits = reset_data.get("credits", [])
if not credits:
print("No reset credits were found in the server response.")
return
rows: list[list[str]] = []
for index, credit in enumerate(credits, start=1):
status = str(credit.get("status", "unknown"))
status_text = status
if status == "available":
status_text = colour(status_text, "green")
rows.append(
[
str(index),
status_text,
str(credit.get("expires_at_local") or "—"),
str(credit.get("time_remaining") or "—"),
str(credit.get("granted_at_local") or "—"),
]
)
print_counter_table(
"Reset credits",
["#", "Status", "Expires locally", "Time remaining", "Granted locally"],
rows,
)
print(colour("Technical details", "bold"))
print("-" * 17)
explain(
"These details explain where the values came from. They are shown for transparency and are not needed for normal reading of the report."
)
print_counter_table(
"Reset endpoint details",
["Metric", "Value"],
[
["Endpoint", "/backend-api/wham/rate-limit-reset-credits"],
["Method", "GET"],
["Auth file", f"{AUTH_PATH} (token is not printed)"],
["Endpoint status", "undocumented; may change"],
],
)
def cmd_resets(args: argparse.Namespace) -> None:
set_colour_mode(getattr(args, "colour", None))
data = collect_resets()
if args.json:
print_json(data)
else:
print_resets(data, warn_days=args.warn_days)
def connect_sqlite_readonly(path: Path) -> sqlite3.Connection:
return sqlite3.connect(f"file:{path}?mode=ro", uri=True)
def sqlite_threads_summary(codex_home: Path, top_n: int) -> dict[str, Any]:
candidates = [
codex_home / "state_5.sqlite",
codex_home / "sqlite" / "state_5.sqlite",
]
summaries: list[dict[str, Any]] = []
for db_path in candidates:
if not db_path.exists():
continue
try:
con = connect_sqlite_readonly(db_path)
cur = con.cursor()
tables = {
row[0]
for row in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table'"
)
}
if "threads" not in tables:
con.close()
continue
cols = [row[1] for row in cur.execute("PRAGMA table_info(threads)")]
has_tokens = "tokens_used" in cols
has_model = "model" in cols
has_created = "created_at" in cols
has_updated = "updated_at" in cols
basic: dict[str, Any] = {
"database": str(db_path),
"rows": 0,
"tokens_used_sum": 0,
"tokens_used_max": 0,
"created_at_min": None,
"updated_at_max": None,
"by_model": [],
}
if has_tokens:
row = cur.execute(
"SELECT COUNT(*), SUM(COALESCE(tokens_used, 0)), MAX(COALESCE(tokens_used, 0)) FROM threads"
).fetchone()
basic["rows"] = int(row[0] or 0)
basic["tokens_used_sum"] = int(row[1] or 0)
basic["tokens_used_max"] = int(row[2] or 0)
else:
basic["rows"] = int(
cur.execute("SELECT COUNT(*) FROM threads").fetchone()[0] or 0
)
if has_created:
basic["created_at_min"] = cur.execute(
"SELECT MIN(created_at) FROM threads"
).fetchone()[0]
if has_updated:
basic["updated_at_max"] = cur.execute(
"SELECT MAX(updated_at) FROM threads"
).fetchone()[0]
if has_model and has_tokens:
for model, rows, tokens in cur.execute(
"""
SELECT COALESCE(NULLIF(model, ''), '(blank)') AS model_name,
COUNT(*) AS rows,
SUM(COALESCE(tokens_used, 0)) AS tokens
FROM threads
GROUP BY COALESCE(NULLIF(model, ''), '(blank)')
ORDER BY tokens DESC
LIMIT ?
""",
(top_n,),
):
basic["by_model"].append(
{
"model": model,
"threads": int(rows or 0),
"tokens_used": int(tokens or 0),
}
)
con.close()
summaries.append(basic)
except sqlite3.Error as exc:
summaries.append(
{"database": str(db_path), "error": f"{type(exc).__name__}: {exc}"}
)
selected = next(
(
s
for s in summaries
if s.get("database", "").endswith("state_5.sqlite")
and "/sqlite/" not in s.get("database", "")
),
None,
)
if selected is None and summaries:
selected = summaries[0]
return {"selected": selected, "all": summaries}
def session_date_from_path(path: Path) -> str | None:
parts = path.parts
try:
idx = parts.index("sessions")
year, month, day = parts[idx + 1], parts[idx + 2], parts[idx + 3]
if len(year) == 4 and len(month) == 2 and len(day) == 2:
return f"{year}-{month}-{day}"
except (ValueError, IndexError):
return None
return None
def scan_sessions_metadata(codex_home: Path, top_n: int = 10) -> dict[str, Any]:
session_dir = codex_home / "sessions"
files = sorted(session_dir.rglob("*.jsonl")) if session_dir.exists() else []
daily_sessions: Counter[str] = Counter()
daily_usage: dict[str, Counter[str]] = defaultdict(Counter)
model_sessions: Counter[str] = Counter()
model_usage: dict[str, Counter[str]] = defaultdict(Counter)
provider_sessions: Counter[str] = Counter()
context_windows: Counter[str] = Counter()
final_totals: list[dict[str, Any]] = []
final_sum: Counter[str] = Counter()
parse_errors = 0
lines_seen = 0
files_with_usage = 0
mtime_values: list[datetime] = []
for file_path in files:
date_key = session_date_from_path(file_path) or "unknown"
daily_sessions[date_key] += 1
try:
mtime_values.append(
datetime.fromtimestamp(file_path.stat().st_mtime).astimezone()
)
except OSError:
pass
final_usage: dict[str, int] | None = None
model: str | None = None
provider: str | None = None
context_window: int | None = None
project: str | None = None
try:
with file_path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
lines_seen += 1
try:
obj = json.loads(line)
except json.JSONDecodeError:
parse_errors += 1
continue
if not isinstance(obj, dict):
continue
payload = (
obj.get("payload")
if isinstance(obj.get("payload"), dict)
else obj
)
if not isinstance(payload, dict):
continue
if isinstance(payload.get("model"), str):
model = payload["model"]
if isinstance(payload.get("model_provider"), str):
provider = payload["model_provider"]
if isinstance(payload.get("cwd"), str):
project = payload["cwd"]
info = payload.get("info")
if isinstance(info, dict):
total_usage = info.get("total_token_usage")
if isinstance(total_usage, dict):
final_usage = {
key: int(total_usage.get(key) or 0)
for key in USAGE_FIELDS
if isinstance(total_usage.get(key), (int, float))
}
if isinstance(info.get("model_context_window"), int):
context_window = int(info["model_context_window"])
except OSError:
parse_errors += 1
continue
if model:
model_sessions[model] += 1
if provider:
provider_sessions[provider] += 1
if context_window is not None:
context_windows[str(context_window)] += 1
if final_usage:
files_with_usage += 1
for key, value in final_usage.items():
final_sum[key] += value
daily_usage[date_key][key] += value
if model:
model_usage[model][key] += value
final_totals.append(
{
"session_file": str(file_path.relative_to(codex_home)),
"date": date_key,
"model": model or "—",
"project": short_path(project),
"usage": final_usage,
}
)
final_totals.sort(
key=lambda item: item["usage"].get("total_tokens", 0), reverse=True
)
daily_usage_rows = []
for day in sorted(daily_sessions):
row = {"date": day, "sessions": daily_sessions[day]}
row.update(
{field: int(daily_usage[day].get(field, 0)) for field in USAGE_FIELDS}
)
daily_usage_rows.append(row)
return {
"session_files": len(files),
"jsonl_lines_scanned": lines_seen,
"parse_or_read_errors": parse_errors,
"files_with_final_token_totals": files_with_usage,
"file_mtime_start_local": min(mtime_values).strftime("%Y-%m-%d %H:%M:%S %Z %z")
if mtime_values
else None,
"file_mtime_end_local": max(mtime_values).strftime("%Y-%m-%d %H:%M:%S %Z %z")
if mtime_values
else None,
"final_token_totals_sum": dict(final_sum),
"models_by_session": model_sessions.most_common(top_n),
"model_token_totals": {
model: dict(counter) for model, counter in model_usage.items()
},
"providers_by_session": provider_sessions.most_common(20),
"context_windows_by_session": context_windows.most_common(20),
"daily_usage": daily_usage_rows,
"top_sessions_by_total_tokens": final_totals[:top_n],
}
def collect_local_usage(codex_home: Path, top_n: int) -> dict[str, Any]:
if not codex_home.exists():
die(f"Codex home not found: {codex_home}")
return {
"retrieved_at_local": local_now_text(),
"codex_home": str(codex_home),
"network_calls_made": 0,
"privacy_note": "Local metadata only; prompt/assistant/transcript contents are not printed.",
"sqlite_threads": sqlite_threads_summary(codex_home, top_n=top_n),
"sessions": scan_sessions_metadata(codex_home, top_n=top_n),
}
def local_hints(
local_data: dict[str, Any], high_session_threshold: int = 500_000_000
) -> list[str]:
hints: list[str] = []
sessions = local_data.get("sessions", {})
totals = (
sessions.get("final_token_totals_sum", {}) if isinstance(sessions, dict) else {}
)
total_tokens = int(totals.get("total_tokens") or 0)
input_tokens = int(totals.get("input_tokens") or 0)
cached = int(totals.get("cached_input_tokens") or 0)
if input_tokens:
cached_ratio = cached / input_tokens * 100
if cached_ratio >= 80:
hints.append(
f"Cached input is high: {cached_ratio:.1f}% of input tokens were cached locally."
)
top_sessions = (
sessions.get("top_sessions_by_total_tokens", [])
if isinstance(sessions, dict)
else []
)
high_sessions = [
s
for s in top_sessions
if s.get("usage", {}).get("total_tokens", 0) >= high_session_threshold
]
if high_sessions:
hints.append(
f"{len(high_sessions)} top session(s) are above {fmt_int(high_session_threshold)} total tokens."
)
selected = (
local_data.get("sqlite_threads", {}).get("selected")
if isinstance(local_data.get("sqlite_threads"), dict)
else None
)
if selected and isinstance(selected.get("by_model"), list) and total_tokens:
top = selected["by_model"][0] if selected["by_model"] else None
if top:
share = (
int(top.get("tokens_used") or 0)
/ max(1, int(selected.get("tokens_used_sum") or 1))
* 100
)
if share >= 90:
hints.append(
f"Model {top.get('model')} dominates local usage at {share:.1f}% of SQLite tokens_used."
)
errors = (
int(sessions.get("parse_or_read_errors") or 0)
if isinstance(sessions, dict)
else 0
)
if errors: