-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude_code_usage.py
More file actions
2216 lines (1987 loc) · 88.4 KB
/
claude_code_usage.py
File metadata and controls
2216 lines (1987 loc) · 88.4 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
"""
Claude Code usage — personalized dashboard with pacing, 99%-by-Friday
targeting, active-hour rate conversion, ASCII charts, search, and
Anthropic Max-plan drift validation.
Data sources:
1. Live API: GET https://api.anthropic.com/api/oauth/usage — Anthropic's
authoritative weekly/session quota (% utilization + reset timestamps)
2. Local SQLite at _infrastructure/cc_usage/data/claude_usage.db — backfilled
per-turn token counts parsed from ~/.claude/projects/*/*.jsonl
Each CLI invocation records a fresh snapshot to the `snapshots` table, so
historical pacing (recent burn rate, projection to landing) is always
available from the rolling log.
## Auth
Reads the Claude Code OAuth access token from the macOS keychain. Pure read,
never writes, never refreshes — refreshing rotates the token and kicks the
live CLI back to /login, so the script deliberately avoids that path.
The `anthropic-beta: oauth-2025-04-20` header is required to unlock OAuth on
`/api/oauth/*` — without it the server returns "OAuth authentication is
currently not supported".
## CLI
cc-usage # panel + pacing (records snapshot)
cc-usage --report # + tokens by model/project + session list
cc-usage --charts # + hourly & daily burn ASCII charts
cc-usage --search my-repo # filter everything by project substring
cc-usage --validate # Max plan drift check (snapshot Δ% vs token burn)
cc-usage --json # raw API JSON
cc-usage --plain # panel without writing snapshot
cc-usage --target 95 # custom weekly target %
Aliased to `cc-usage` in ~/.zshrc.
"""
import argparse
import getpass
import json
import os
import subprocess
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
import requests
# Sibling import — claude_usage_db.py lives next to this file in
# _infrastructure/cc_usage/. Add our own directory to sys.path so the import
# works no matter where the interpreter is invoked from (launchd, zshrc alias,
# cron, or a `cd elsewhere && python3 /path/to/claude_code_usage.py`).
sys.path.insert(0, str(Path(__file__).resolve().parent))
import claude_usage_db as dbmod # noqa: E402
USAGE_URL = "https://api.anthropic.com/api/oauth/usage"
USER_AGENT = "claude-cli/2.1.101 (external, cli)"
# Required to unlock OAuth on /api/oauth/* endpoints. Without this header
# the server returns 401 "OAuth authentication is currently not supported".
# Extracted from the Claude Code CLI binary (constant `GP`).
ANTHROPIC_BETA = "oauth-2025-04-20"
KEYCHAIN_SERVICE = "Claude Code-credentials"
# Multi-account registry. Each key maps to the keychain service name and a
# human-readable label. The overflow account absorbs usage after the primary
# hits its weekly cap — see MULTI_ACCOUNT_PLAN.md for the full rationale.
ACCOUNTS = {
"primary": {"keychain": "Claude Code-credentials", "label": "Max 20x", "tier": "max_20x"},
"overflow": {"keychain": "Claude Code-credentials-bae1e975", "label": "Max 20x", "tier": "max_20x"},
}
# Local wall-clock timezone for human-friendly displays ("4:28pm", "Sat Apr 11").
# Override with the CC_USAGE_TZ env var (any IANA zone name, e.g. "Europe/Berlin").
# Defaults to America/Los_Angeles to match the Anthropic quota reset convention.
PT = ZoneInfo(os.environ.get("CC_USAGE_TZ", "America/Los_Angeles"))
DEFAULT_TARGET = 99.0
# ---------- auth + fetch ----------
def _load_access_token(keychain_service=KEYCHAIN_SERVICE):
result = subprocess.run(
[
"security", "find-generic-password",
"-s", keychain_service,
"-a", getpass.getuser(),
"-w",
],
capture_output=True, text=True, check=False,
)
if result.returncode != 0:
raise RuntimeError(
f"Claude Code keychain entry not found ({keychain_service}): "
f"{result.stderr.strip() or 'unknown error'}"
)
return json.loads(result.stdout)["claudeAiOauth"]["accessToken"]
def get_usage(keychain_service=KEYCHAIN_SERVICE):
resp = requests.get(
USAGE_URL,
headers={
"Authorization": f"Bearer {_load_access_token(keychain_service)}",
"anthropic-beta": ANTHROPIC_BETA,
"User-Agent": USER_AGENT,
},
timeout=30,
)
resp.raise_for_status()
return resp.json()
# ---------- time helpers ----------
def _parse_iso(ts):
if not ts:
return None
return datetime.fromisoformat(ts.replace("Z", "+00:00"))
def _fmt_reset(iso_ts):
dt = _parse_iso(iso_ts)
if not dt:
return ""
return dt.astimezone(PT).strftime("%a %b %-d, %-I:%M%p").replace(":00", "")
def _hours_until(iso_ts):
dt = _parse_iso(iso_ts)
if not dt:
return 0.0
return max(0.0, (dt - datetime.now(timezone.utc)).total_seconds() / 3600)
def _hours_since(iso_ts):
dt = _parse_iso(iso_ts)
if not dt:
return 0.0
return max(0.0, (datetime.now(timezone.utc) - dt).total_seconds() / 3600)
def _fmt_duration(hours):
if hours < 1 / 60:
return "<1m"
if hours < 1:
return f"{int(round(hours * 60))}m"
if hours < 24:
h = int(hours)
m = int(round((hours - h) * 60))
return f"{h}h {m}m" if m else f"{h}h"
days = hours / 24
if days < 10:
return f"{days:.1f}d"
return f"{int(round(days))}d"
def _bar(pct, width=50):
pct = max(0, min(100, pct))
filled = int(round((pct / 100) * width))
return "█" * filled + "░" * (width - filled)
def _fmt_tokens(n):
if n is None:
return "—"
if n >= 1_000_000_000:
return f"{n/1_000_000_000:.1f}B"
if n >= 1_000_000:
return f"{n/1_000_000:.1f}M"
if n >= 1_000:
return f"{n/1_000:.1f}k"
return str(n)
def _short_proj(path):
"""
Shorten a project cwd path for CLI display. Replaces the user's home
directory with `~` so wide project paths like
`/Users/alice/code/big-repo-name` collapse to `~/code/big-repo-name`.
Then truncates to 40 chars to keep table columns aligned.
"""
if not path:
return "—"
home = str(Path.home())
if path.startswith(home):
path = "~" + path[len(home):]
return path[:40]
def _week_start_iso(reset_iso):
"""Weekly window = 168h before reset."""
dt = _parse_iso(reset_iso)
if not dt:
return None
return (dt - timedelta(hours=168)).isoformat()
def _session_start_iso(reset_iso):
"""Current session window = 5h before reset."""
dt = _parse_iso(reset_iso)
if not dt:
return None
return (dt - timedelta(hours=5)).isoformat()
# ---------- pace from snapshots ----------
def _recent_pace(conn, bucket_col, bucket_reset_col, current_reset_iso, current_pct):
"""
Return (pct_per_day, hours_ago) from the oldest snapshot in the SAME
window (same reset timestamp) that has a usable value. Returns None if
we don't have enough history yet.
"""
if not current_reset_iso:
return None
row = conn.execute(
f"SELECT ts, {bucket_col} FROM snapshots "
f"WHERE {bucket_reset_col} = ? AND {bucket_col} IS NOT NULL "
f"ORDER BY ts ASC LIMIT 1",
(current_reset_iso,),
).fetchone()
if not row or row[bucket_col] is None:
return None
prev_ts = _parse_iso(row["ts"])
if not prev_ts:
return None
hours = (datetime.now(timezone.utc) - prev_ts).total_seconds() / 3600
if hours < 0.05: # under 3 min — too noisy
return None
delta = current_pct - row[bucket_col]
if delta < 0:
return None
return ((delta / hours) * 24, hours)
def _recent_dollar_pace(conn, extra_reset_iso, current_used_cents):
if not extra_reset_iso:
return None
row = conn.execute(
"SELECT ts, extra_used_cents FROM snapshots "
"WHERE extra_reset = ? AND extra_used_cents IS NOT NULL "
"ORDER BY ts ASC LIMIT 1",
(extra_reset_iso,),
).fetchone()
if not row or row["extra_used_cents"] is None:
return None
prev_ts = _parse_iso(row["ts"])
if not prev_ts:
return None
hours = (datetime.now(timezone.utc) - prev_ts).total_seconds() / 3600
if hours < 0.05:
return None
delta_dollars = (current_used_cents - row["extra_used_cents"]) / 100.0
if delta_dollars < 0:
return None
return ((delta_dollars / hours) * 24, hours)
def _dollar_pace_since_last_reset(conn, current_used_cents, max_lookback_hours=24 * 40):
"""Compute $/day pace across the current monthly cycle, inferring the
cycle boundary from snapshot history (no `extra_reset_iso` required).
Walks snapshots oldest→newest within the lookback window. A monthly
reset shows up as `extra_used_cents` decreasing between two adjacent
snapshots (the counter drops back to 0). The most recent such drop
is treated as the start of the current cycle. If no drops are
observed, the oldest snapshot in the window is treated as the start.
Returns `(dollars_per_day, lookback_hours, delta_dollars)` or None if
there's insufficient data or zero movement. Callers should interpret
`delta_dollars == 0` + `lookback_hours small` as "counter hasn't
moved yet, wait longer" vs `lookback_hours large` as "you're genuinely
not burning extra right now."
"""
cutoff_iso = (
datetime.now(timezone.utc) - timedelta(hours=max_lookback_hours)
).isoformat()
rows = conn.execute(
"SELECT ts, extra_used_cents FROM snapshots "
"WHERE ts >= ? AND extra_used_cents IS NOT NULL "
"ORDER BY ts ASC",
(cutoff_iso,),
).fetchall()
if not rows:
return None
# Find the most recent reset (drop). Anchor is the snapshot immediately
# after that drop. If no drops, anchor = oldest row in the window.
anchor = rows[0]
for i in range(len(rows) - 1):
if rows[i]["extra_used_cents"] > rows[i + 1]["extra_used_cents"]:
anchor = rows[i + 1]
anchor_ts = _parse_iso(anchor["ts"])
if not anchor_ts:
return None
hours = (datetime.now(timezone.utc) - anchor_ts).total_seconds() / 3600
if hours < 1.0:
return None # not enough elapsed time to compute anything meaningful
delta_dollars = (current_used_cents - anchor["extra_used_cents"]) / 100.0
if delta_dollars < 0:
delta_dollars = 0.0 # defensive; shouldn't happen given anchor logic
per_day = (delta_dollars / hours) * 24 if hours > 0 else 0
return (per_day, hours, delta_dollars)
def _status(recent, safe):
"""Coach voice: 'pull back' not 'slow down'."""
if safe <= 0:
return "OVER CAP"
if recent is None:
return "—"
ratio = recent / safe
if ratio >= 1.5:
return "PULL BACK HARD"
if ratio >= 1.15:
return "pull back"
if ratio >= 0.85:
return "on pace"
return "plenty of headroom"
# ---------- active-hour rate (the "real work" unit) ----------
def _active_hour_stats(conn, since_iso, project_filter=None, account=None):
"""
An 'active hour' = a distinct calendar hour (UTC bucket — consistent,
not drifting with DST) where at least one non-sidechain assistant turn
was produced. Translating %-quota → hours uses this as the base unit,
so 'tomorrow you can work 1.28 active hours' is an honest number: it
already excludes background/idle time.
"""
where = "ts >= ? AND is_sidechain = 0"
params = [since_iso]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
if account:
where += " AND COALESCE(account, 'primary') = ?"
params.append(account)
row = conn.execute(
f"""
SELECT
COUNT(DISTINCT strftime('%Y-%m-%d %H', ts)) AS active_hours,
COUNT(*) AS turns,
SUM(input_tokens + output_tokens + cache_creation_input_tokens) AS tokens
FROM turns
WHERE {where}
""",
params,
).fetchone()
return {
"active_hours": row["active_hours"] or 0,
"turns": row["turns"] or 0,
"tokens": row["tokens"] or 0,
}
def _pull_back_plan(current_pct, target_pct, hours_left, active_hours_so_far):
"""
Given where we are in the week and how many active hours have produced
the current %, compute:
- pct_per_active_hour (observed rate this week)
- daily_budget_pct (linear-to-target %/day)
- active_hours_per_day_budget (how many active hours per day to land on target)
- tomorrow_budget_hours (same thing, for tomorrow specifically)
"""
if hours_left <= 0 or active_hours_so_far <= 0:
return None
rate = current_pct / active_hours_so_far
if rate <= 0:
return None
days_left = hours_left / 24
remaining_pct = max(0.0, target_pct - current_pct)
daily_budget_pct = remaining_pct / days_left
daily_hours = daily_budget_pct / rate
return {
"rate_pct_per_hour": rate,
"daily_budget_pct": daily_budget_pct,
"daily_hours": daily_hours,
"tomorrow_hours": daily_hours, # today is today; "tomorrow's allowance" = 1 day's budget
"days_left": days_left,
}
# ---------- panel ----------
def _print_bucket_row(label, block, bucket_col, reset_col, conn, target_pct, is_session=False):
if not block:
return None
used = block.get("utilization", 0) or 0
remaining = 100 - used
reset_iso = block.get("resets_at")
hours_left = _hours_until(reset_iso)
hours_elapsed = 168 - hours_left if reset_iso and not is_session else 0
print(f"\n {label}")
print(f" {_bar(used)}")
print(
f" {used:5.1f}% used · {remaining:5.1f}% left · "
f"{_fmt_duration(hours_left)} to reset ({_fmt_reset(reset_iso)})"
)
if hours_left <= 0:
return None
pace = _recent_pace(conn, bucket_col, reset_col, reset_iso, used)
if is_session:
safe_h = remaining / hours_left if hours_left > 0 else 0
line = f" safe: {safe_h:5.2f}%/h"
if pace:
recent_per_day, lookback_h = pace
recent_h = recent_per_day / 24
line += (
f" · recent: {recent_h:5.2f}%/h "
f"over {_fmt_duration(lookback_h)} → {_status(recent_h, safe_h)}"
)
print(line)
if pace and pace[0] > 0:
recent_h = pace[0] / 24
if recent_h > 0:
burnout_h = remaining / recent_h
if burnout_h < hours_left:
print(
f" at current pace you hit 100% in {_fmt_duration(burnout_h)} "
f"({_fmt_duration(hours_left - burnout_h)} before reset)"
)
# active-hour rate within this 5h window
session_start = _session_start_iso(reset_iso)
if session_start:
sstats = _active_hour_stats(conn, session_start)
if sstats["active_hours"] >= 1 and used > 0:
rate = used / sstats["active_hours"]
headroom_hours = remaining / rate if rate > 0 else 0
print(
f" session rate: {rate:5.2f}%/active-hour "
f"({sstats['active_hours']}h · {sstats['turns']} turns) "
f"→ {headroom_hours:4.2f}h of work fits in the {remaining:.0f}% remaining"
)
return None
# weekly bucket — add 99%-by-Friday math
days_left = hours_left / 24
safe_to_target = max(0.0, (target_pct - used) / days_left) if days_left > 0 else 0
ideal_now = (hours_elapsed / 168) * target_pct
vs_ideal = used - ideal_now
# "on-pace-for-target" line
direction = "AHEAD" if vs_ideal > 0 else ("behind" if vs_ideal < -0.5 else "on track")
print(
f" on-pace-for-{int(target_pct)}% baseline: {ideal_now:5.2f}% "
f"(you're {'+' if vs_ideal >= 0 else ''}{vs_ideal:5.2f}% {direction})"
)
# safe burn for hitting target
print(
f" to land at {int(target_pct)}% by {_fmt_reset(reset_iso)}: "
f"{safe_to_target:5.2f}%/day budget for {_fmt_duration(hours_left)}"
)
if pace:
recent_per_day, lookback_h = pace
projected = used + (recent_per_day * days_left)
status = _status(recent_per_day, safe_to_target)
print(
f" recent burn: {recent_per_day:5.2f}%/day over last "
f"{_fmt_duration(lookback_h)} → projected landing "
f"{projected:5.1f}% ({status})"
)
return (label, safe_to_target, used, reset_iso)
# ---------- reports ----------
def _today_session_report(conn, reset_iso_utc, project_filter=None):
where = "ts >= ?"
params = [reset_iso_utc]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
rows = conn.execute(
f"""
SELECT
session_id,
project_cwd,
COUNT(*) AS turns,
MIN(ts) AS first_ts,
MAX(ts) AS last_ts,
SUM(input_tokens) AS in_tok,
SUM(output_tokens) AS out_tok,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(cache_read_input_tokens) AS cache_read,
SUM(CASE WHEN is_sidechain = 1 THEN 1 ELSE 0 END) AS sidechain_turns,
(SELECT model FROM turns t2 WHERE t2.session_id = t.session_id
GROUP BY model ORDER BY COUNT(*) DESC LIMIT 1) AS top_model
FROM turns t
WHERE {where}
GROUP BY session_id
ORDER BY SUM(input_tokens + output_tokens + cache_creation_input_tokens) DESC
""",
params,
).fetchall()
return rows
def _model_breakdown(conn, reset_iso_utc, project_filter=None):
where = "ts >= ?"
params = [reset_iso_utc]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
return conn.execute(
f"""
SELECT
model,
COUNT(*) AS turns,
COUNT(DISTINCT session_id) AS sessions,
SUM(input_tokens) AS in_tok,
SUM(output_tokens) AS out_tok,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(cache_read_input_tokens) AS cache_read
FROM turns
WHERE {where}
GROUP BY model
ORDER BY SUM(input_tokens + output_tokens + cache_creation_input_tokens) DESC
""",
params,
).fetchall()
def _project_breakdown(conn, reset_iso_utc, limit=10, project_filter=None):
where = "ts >= ? AND project_cwd IS NOT NULL"
params = [reset_iso_utc]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
params.append(limit)
return conn.execute(
f"""
SELECT
project_cwd,
COUNT(*) AS turns,
COUNT(DISTINCT session_id) AS sessions,
SUM(input_tokens) AS in_tok,
SUM(output_tokens) AS out_tok,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(cache_read_input_tokens) AS cache_read
FROM turns
WHERE {where}
GROUP BY project_cwd
ORDER BY SUM(input_tokens + output_tokens + cache_creation_input_tokens) DESC
LIMIT ?
""",
params,
).fetchall()
def _print_report(conn, reset_iso_utc, project_filter=None):
suffix = f" (filter: project ~ '{project_filter}')" if project_filter else ""
print(f"\n ─ Since the weekly reset ─{suffix}")
print(f" window start: {_fmt_reset(reset_iso_utc)} PT")
models = _model_breakdown(conn, reset_iso_utc, project_filter)
if models:
print("\n tokens by model:")
print(f" {'model':<28} {'turns':>6} {'sess':>5} {'input':>10} {'output':>10} {'cache-new':>10} {'cache-rd':>10}")
for r in models:
print(
f" {(r['model'] or '—'):<28} {r['turns']:>6} {r['sessions']:>5} "
f"{_fmt_tokens(r['in_tok']):>10} {_fmt_tokens(r['out_tok']):>10} "
f"{_fmt_tokens(r['cache_new']):>10} {_fmt_tokens(r['cache_read']):>10}"
)
projects = _project_breakdown(conn, reset_iso_utc, project_filter=project_filter)
if projects:
print("\n tokens by project (top 10):")
print(f" {'project':<42} {'turns':>6} {'sess':>5} {'input':>10} {'output':>10} {'cache-new':>10}")
for r in projects:
print(
f" {_short_proj(r['project_cwd']):<42} {r['turns']:>6} "
f"{r['sessions']:>5} {_fmt_tokens(r['in_tok']):>10} "
f"{_fmt_tokens(r['out_tok']):>10} {_fmt_tokens(r['cache_new']):>10}"
)
sessions = _today_session_report(conn, reset_iso_utc, project_filter)
if sessions:
print(f"\n sessions this week ({len(sessions)}):")
print(f" {'started':<16} {'proj':<28} {'turns':>6} {'in+out':>10} {'cache-new':>10} {'model':<24}")
for r in sessions:
started_pt = _parse_iso(r["first_ts"]).astimezone(PT).strftime("%a %-I:%M%p")
combined = (r["in_tok"] or 0) + (r["out_tok"] or 0)
print(
f" {started_pt:<16} "
f"{_short_proj(r['project_cwd'])[:28]:<28} "
f"{r['turns']:>6} {_fmt_tokens(combined):>10} "
f"{_fmt_tokens(r['cache_new']):>10} "
f"{(r['top_model'] or '—'):<24}"
)
# ---------- charts ----------
def _hourly_chart(conn, since_iso, project_filter=None, width=40, title=None):
"""Hourly bars since `since_iso` — one row per active UTC hour."""
where = "ts >= ?"
params = [since_iso]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
rows = conn.execute(
f"""
SELECT
strftime('%Y-%m-%d %H', ts) AS hour_utc,
COUNT(*) AS turns,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(input_tokens + output_tokens + cache_creation_input_tokens) AS total_new
FROM turns
WHERE {where}
GROUP BY hour_utc
ORDER BY hour_utc
""",
params,
).fetchall()
if not rows:
print("\n (no hourly data yet)")
return
max_val = max((r["total_new"] or 0) for r in rows) or 1
print(f"\n {title or 'hourly burn'}")
print(f" ({len(rows)} active hours · scale = input+output+cache-new)")
for r in rows:
dt = datetime.strptime(r["hour_utc"] + ":00:00+00:00", "%Y-%m-%d %H:%M:%S%z")
pt_dt = dt.astimezone(PT)
val = r["total_new"] or 0
bar_len = int(round((val / max_val) * width))
bar_len = max(1, bar_len) if val else 0
label = pt_dt.strftime("%a %-I%p")
bar = "█" * bar_len + "·" * (width - bar_len)
print(f" {label:<8} {bar} {r['turns']:>4}t · {_fmt_tokens(val):>7}")
def _daily_chart(conn, days=14, project_filter=None, width=40):
"""
One bar per PT calendar day over the last N days. Buckets in Python on
PT (not SQLite UTC) so 'today' matches the hourly chart.
"""
since = (datetime.now(timezone.utc) - timedelta(days=days + 1)).isoformat()
where = "ts >= ?"
params = [since]
if project_filter:
where += " AND project_cwd LIKE ?"
params.append(f"%{project_filter}%")
rows = conn.execute(
f"""
SELECT ts, session_id, input_tokens, output_tokens,
cache_creation_input_tokens
FROM turns
WHERE {where}
ORDER BY ts
""",
params,
).fetchall()
if not rows:
print("\n (no daily data yet)")
return
# Bucket in PT
today_pt = datetime.now(PT).date()
cutoff = today_pt - timedelta(days=days - 1)
buckets = defaultdict(lambda: {
"turns": 0, "sessions": set(), "hours": set(), "tokens": 0,
})
for r in rows:
dt = _parse_iso(r["ts"])
if not dt:
continue
pt_dt = dt.astimezone(PT)
day = pt_dt.date()
if day < cutoff:
continue
b = buckets[day]
b["turns"] += 1
b["sessions"].add(r["session_id"])
b["hours"].add(pt_dt.strftime("%Y-%m-%d %H"))
b["tokens"] += (
(r["input_tokens"] or 0)
+ (r["output_tokens"] or 0)
+ (r["cache_creation_input_tokens"] or 0)
)
if not buckets:
print("\n (no daily data in window)")
return
max_val = max(b["tokens"] for b in buckets.values()) or 1
print(f"\n daily burn — last {days} days (PT calendar)")
print(" (scale = input+output+cache-new tokens)")
for day in sorted(buckets.keys()):
b = buckets[day]
val = b["tokens"]
bar_len = int(round((val / max_val) * width))
bar_len = max(1, bar_len) if val else 0
label = day.strftime("%a %b %-d")
bar = "█" * bar_len + "·" * (width - bar_len)
print(
f" {label:<11} {bar} {len(b['hours']):>2}h · "
f"{len(b['sessions']):>2}s · {b['turns']:>5}t · {_fmt_tokens(val):>7}"
)
# ---------- search ----------
def _print_search(conn, substring, limit=20):
print(f"\n Search: project_cwd LIKE '%{substring}%'")
rows = conn.execute(
"""
SELECT
project_cwd,
COUNT(*) AS turns,
COUNT(DISTINCT session_id) AS sessions,
MIN(ts) AS first_ts,
MAX(ts) AS last_ts,
SUM(input_tokens) AS in_tok,
SUM(output_tokens) AS out_tok,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(cache_read_input_tokens) AS cache_read
FROM turns
WHERE project_cwd LIKE ?
GROUP BY project_cwd
ORDER BY SUM(input_tokens + output_tokens + cache_creation_input_tokens) DESC
LIMIT ?
""",
(f"%{substring}%", limit),
).fetchall()
if not rows:
print(" (no matches)")
return
print(f" {'project':<44} {'sess':>4} {'turns':>6} {'first':<14} {'last':<14} {'cache-new':>10}")
for r in rows:
first = _parse_iso(r["first_ts"]).astimezone(PT).strftime("%b %-d %-I%p")
last = _parse_iso(r["last_ts"]).astimezone(PT).strftime("%b %-d %-I%p")
print(
f" {_short_proj(r['project_cwd']):<44} "
f"{r['sessions']:>4} {r['turns']:>6} "
f"{first:<14} {last:<14} "
f"{_fmt_tokens(r['cache_new']):>10}"
)
# ---------- Max plan validation (snapshot Δ% vs token burn) ----------
def _validate_anthropic(conn):
"""
Between every pair of adjacent snapshots in the CURRENT weekly window,
compare API-reported Δ quota% against token burn in the same interval.
If the %/Mtok ratio drifts over time, that's evidence Anthropic is
metering the Max plan differently than on day 1 — either cheaper
(headroom) or more expensive (cap is timing out sooner).
"""
snaps = conn.execute("""
SELECT ts, seven_day_pct, seven_day_reset
FROM snapshots
WHERE seven_day_pct IS NOT NULL
ORDER BY ts
""").fetchall()
if len(snaps) < 2:
print("\n Max plan validation")
print(" (need ≥2 snapshots in the same weekly window — run cc-usage a few more times)")
return
windows = defaultdict(list)
for s in snaps:
windows[s["seven_day_reset"]].append(s)
print("\n Max plan validation — snapshot Δ% vs token burn")
print(" ─ compares API's metered weekly% against local turn-token counts ─")
print(f" {'window':<10} {'interval':<25} {'Δ %':>7} {'Δ tokens':>12} {'%/Mtok':>9} {'notes'}")
ratios = []
for reset, rows in windows.items():
if len(rows) < 2:
continue
reset_short = _parse_iso(reset).astimezone(PT).strftime("%b %-d") if reset else "—"
for i in range(1, len(rows)):
a, b = rows[i - 1], rows[i]
delta_pct = (b["seven_day_pct"] or 0) - (a["seven_day_pct"] or 0)
if delta_pct <= 0.01:
continue
sums = conn.execute(
"""
SELECT
SUM(input_tokens) AS in_tok,
SUM(output_tokens) AS out_tok,
SUM(cache_creation_input_tokens) AS cache_new,
SUM(cache_read_input_tokens) AS cache_read
FROM turns
WHERE ts > ? AND ts <= ?
""",
(a["ts"], b["ts"]),
).fetchone()
cache_new = sums["cache_new"] or 0
inout = (sums["in_tok"] or 0) + (sums["out_tok"] or 0)
total = cache_new + inout
if total <= 0:
continue
ratio = delta_pct / (total / 1_000_000)
ratios.append(ratio)
a_pt = _parse_iso(a["ts"]).astimezone(PT).strftime("%a %-I:%M%p")
b_pt = _parse_iso(b["ts"]).astimezone(PT).strftime("%-I:%M%p")
print(
f" {reset_short:<10} {a_pt}→{b_pt:<12} "
f"{delta_pct:>7.2f} {_fmt_tokens(total):>12} {ratio:>9.4f}"
)
if len(ratios) >= 3:
avg = sum(ratios) / len(ratios)
lo, hi = min(ratios), max(ratios)
print()
print(f" avg : {avg:.4f} %/Mtok")
print(f" range: {lo:.4f} → {hi:.4f} (drift = {((hi-lo)/avg*100):.1f}%)")
# interpretation
if hi - lo > avg * 0.5:
print(" ⚠ >50% drift — Anthropic's metering is NOT stable over the week.")
elif hi - lo > avg * 0.2:
print(" ~ 20-50% drift — within reasonable noise, no obvious anomaly.")
else:
print(" ✓ <20% drift — metering appears consistent.")
else:
print("\n (not enough valid intervals yet — keep running cc-usage periodically)")
# ---------- main panel ----------
def print_panel(
data=None,
conn=None,
record=True,
report=False,
charts=False,
target=DEFAULT_TARGET,
project_filter=None,
):
if conn is None:
conn = dbmod.connect()
# Resolve `data`: prefer a live fetch, fall back to the most recent DB
# snapshot on any error (429, network, token refresh, etc.). Matches the
# widget's fallback policy — transient API issues should never crash the
# panel, and a slightly stale snapshot is always better than a traceback.
# When we do fall back, we also run the same live-extrapolation the
# widget uses so the CLI and widget stay numerically consistent — no
# "widget says 45%, cc-usage says 39%" skew just because the API is
# refusing us right now.
live_fetched = False
if data is None:
try:
data = get_usage()
live_fetched = True
except Exception as e:
row = dbmod.latest_snapshot(conn)
if row and row["raw_json"]:
try:
data = json.loads(row["raw_json"])
age_min = max(
0,
(
datetime.now(timezone.utc) - _parse_iso(row["ts"])
).total_seconds() / 60,
) if row["ts"] else None
age_str = (
f"{int(age_min)}m old" if age_min is not None else "stale"
)
_extrapolate_live(conn, data, row["ts"])
extra_info = data.get("_extrapolated") or {}
week_info = extra_info.get("week") or {}
session_info = extra_info.get("session") or {}
if week_info.get("applied") or session_info.get("applied"):
bits = []
if session_info.get("applied"):
bits.append(
f"session +{session_info.get('delta_pct', 0):.1f}%"
)
if week_info.get("applied"):
bits.append(
f"week +{week_info.get('delta_pct', 0):.1f}%"
)
detail = " · ".join(bits)
print(
f" ⚠ live fetch failed ({type(e).__name__}); "
f"anchor {age_str}, extrapolated from turns ({detail})"
)
else:
print(
f" ⚠ live fetch failed ({type(e).__name__}); "
f"showing last DB snapshot ({age_str})"
)
except Exception:
raise e
else:
raise
# Only record a new snapshot if `data` came from a fresh API call.
# Replaying a stale snapshot row would double-count it.
if record and live_fetched:
dbmod.insert_snapshot(
conn,
ts=datetime.now(timezone.utc).isoformat(),
source="cli",
data=data,
)
now_pt = datetime.now(timezone.utc).astimezone(PT)
print()
title = f" Claude Code usage · {now_pt.strftime('%a %b %-d, %-I:%M%p %Z')} · target {int(target)}%"
if project_filter:
title += f" · filter: {project_filter}"
print(title)
print(" " + "─" * 72)
constraint = None
_print_bucket_row(
"Current session (5h window)",
data.get("five_hour"),
"five_hour_pct", "five_hour_reset",
conn, target, is_session=True,
)
for label, key, col, reset_col in [
("Weekly — all models", "seven_day", "seven_day_pct", "seven_day_reset"),
("Weekly — Sonnet only", "seven_day_sonnet", "seven_day_sonnet_pct", "seven_day_sonnet_reset"),
("Weekly — Opus only", "seven_day_opus", "seven_day_opus_pct", "seven_day_opus_reset"),
]:
result = _print_bucket_row(label, data.get(key), col, reset_col, conn, target)
if result:
lbl, safe, used, reset_iso = result
if constraint is None or safe < constraint[1]:
constraint = (lbl, safe, used, reset_iso)
# extra usage
extra = data.get("extra_usage") or {}
if extra.get("is_enabled"):
used_pct = extra.get("utilization", 0) or 0
spent = (extra.get("used_credits") or 0) / 100
cap = (extra.get("monthly_limit") or 0) / 100
remaining = cap - spent
reset_iso = extra.get("resets_at")
hours_left = _hours_until(reset_iso) if reset_iso else None
print("\n Extra usage ($ cap)")
print(f" {_bar(used_pct)}")
if hours_left is not None:
days_left = hours_left / 24
print(
f" ${spent:7.2f} / ${cap:7.2f} spent · ${remaining:7.2f} left · "
f"{_fmt_duration(hours_left)} to reset ({_fmt_reset(reset_iso)})"
)
safe_per_day = remaining / days_left if days_left > 0 else 0
line = f" safe pace: ${safe_per_day:5.2f}/day"
pace = _recent_dollar_pace(conn, reset_iso, extra.get("used_credits") or 0)
if pace:
recent_per_day, lookback_h = pace
status = _status(recent_per_day, safe_per_day)
line += (
f" · recent: ${recent_per_day:5.2f}/day over "
f"{_fmt_duration(lookback_h)} → {status}"
)
print(line)
# constraint summary + TOMORROW'S BUDGET in active hours
if constraint:
lbl, safe, used, reset_iso = constraint
week_start_iso = _week_start_iso(reset_iso)
print()
print(" " + "─" * 72)
print(
f" Constraint: {lbl} — keep burn under "
f"{safe:5.2f}%/day to land at {int(target)}%."
)
stats = _active_hour_stats(conn, week_start_iso, project_filter) if week_start_iso else None
if stats and stats["active_hours"] >= 2:
plan = _pull_back_plan(
current_pct=used,
target_pct=target,
hours_left=_hours_until(reset_iso),
active_hours_so_far=stats["active_hours"],
)
if plan:
rate = plan["rate_pct_per_hour"]
print()
print(
f" Observed rate this week : {rate:5.2f}%/active-hour "
f"(over {stats['active_hours']} active hours · {stats['turns']} turns)"
)
status = "PULL BACK" if plan["daily_hours"] < 4 else "steady"
print(
f" Tomorrow's budget : {plan['daily_hours']:5.2f} active hours "