-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatusline.sh
More file actions
executable file
·1723 lines (1517 loc) · 58.2 KB
/
statusline.sh
File metadata and controls
executable file
·1723 lines (1517 loc) · 58.2 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
#!/bin/bash
# Claude Code statusline
# Usage: statusline.sh [--style STYLE] [--order ORDER] [--theme THEME] [--path-display TYPE] [--alignment TYPE] [--extra MODE] [--test JSON] [--debug]
# Themes: minimal, compact, detailed, developer, manager
# Styles: single-block, unicode-blocks, bracketed-bars, filled-dots, square-blocks, line-segments, ascii-bars, percent-only, fraction-display
# Extra modes: auto (default, shows when quota runs out or extra >= 50%), always, on-limit, off
progress_bar_style="unicode-blocks"
stat_order="activity,time,cost,model,user,quota,extra"
path_display="project" # project, cwd, full, relative
alignment="left-right" # left-right, right-left, center
theme=""
# Context limit: auto-detected from model.id ([1m] suffix = 1M, default = 200k)
# CLAUDE_CONTEXT_LIMIT env override still honored for manual tuning
context_limit_override="${CLAUDE_CONTEXT_LIMIT:-}"
extra_display_mode="auto" # auto, always, on-limit, off
test_mode=false
test_data=""
debug_mode=false
# Auto-display thresholds: two signal types gate countdown and extra visibility
# Signal 1 — percentage: how much quota is consumed
# Signal 2 — time proximity: how close is the next reset window
FIVE_HOUR_COUNTDOWN_SECS=7200 # show countdown when reset <= 2h
FIVE_HOUR_RECOVERY_SECS=1800 # recovery color when reset <= 30min
SEVEN_DAY_COUNTDOWN_SECS=259200 # show countdown when reset <= 3d
SEVEN_DAY_RECOVERY_SECS=43200 # recovery color when reset <= 12h
EXTRA_AUTO_UTIL_PCT=50 # show extra when its own utilization >= 50%
CACHE_BREAK_MIN_TOKENS=2000 # ignore cache drops below this (noise)
CACHE_BREAK_DROP_PCT=5 # cache read must drop >5% to count as break
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Resolve claude home — OrbStack sets $HOME to macOS host path,
# but credentials/settings live in the Linux user's actual home.
CLAUDE_HOME="$HOME"
if [ ! -d "$CLAUDE_HOME/.claude" ]; then
_real_home=$(getent passwd "$(whoami)" 2>/dev/null | cut -d: -f6)
[ -n "$_real_home" ] && [ -d "$_real_home/.claude" ] && CLAUDE_HOME="$_real_home"
fi
CLAUDE_DATA_DIR="${CLAUDE_DATA_DIR:-$SCRIPT_DIR}"
CLAUDE_CACHE_DIR="${CLAUDE_CACHE_DIR:-$SCRIPT_DIR/sessions}"
# Debug helper
DEBUG_LOG="${DEBUG_LOG:-/tmp/claude-code-statusline.log}"
debug_log() {
if [ "$debug_mode" = true ]; then
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] DEBUG: $*"
echo "$msg" >&2
echo "$msg" >> "$DEBUG_LOG" 2>/dev/null
fi
}
while [[ $# -gt 0 ]]; do
case $1 in
--style)
progress_bar_style="$2"
shift 2
;;
--order)
stat_order="$2"
shift 2
;;
--theme)
theme="$2"
shift 2
;;
--path-display)
path_display="$2"
shift 2
;;
--alignment)
alignment="$2"
shift 2
;;
--extra)
extra_display_mode="$2"
shift 2
;;
--test)
test_mode=true
if [ -n "$2" ] && [[ "$2" != --* ]]; then
test_data="$2"
shift 2
else
shift
fi
;;
--debug)
debug_mode=true
shift
;;
*)
shift
;;
esac
done
debug_log "Script started with: style=$progress_bar_style order=$stat_order theme=$theme"
debug_log "SCRIPT_DIR=$SCRIPT_DIR CLAUDE_DATA_DIR=$CLAUDE_DATA_DIR CLAUDE_CACHE_DIR=$CLAUDE_CACHE_DIR"
command -v jq >/dev/null 2>&1 || { echo "statusline: jq required" >&2; exit 1; }
apply_theme() {
case "$theme" in
"minimal")
progress_bar_style="single-block"
stat_order="model,user"
path_display="project"
alignment="left-right"
extra_display_mode="off"
;;
"compact")
progress_bar_style="unicode-blocks"
stat_order="activity,time,cost,model,user,quota,extra"
path_display="project"
alignment="left-right"
;;
"detailed")
progress_bar_style="bracketed-bars"
stat_order="model,activity,time,cost,user,quota,extra"
path_display="cwd"
alignment="left-right"
;;
"developer")
progress_bar_style="filled-dots"
stat_order="activity,time,cost,model,user,quota,extra"
path_display="full"
alignment="right-left"
extra_display_mode="on-limit"
;;
"manager")
progress_bar_style="percent-only"
stat_order="cost,time,activity,model,user"
path_display="project"
alignment="center"
;;
esac
}
if [ -n "$theme" ]; then
apply_theme
fi
if [ "$test_mode" = true ]; then
if [ -n "$test_data" ]; then
input="$test_data"
else
input=$(cat)
fi
debug_log "TEST MODE ENABLED: input data: ${input:0:200}..."
mock_context='{
"type": "assistant",
"message": {
"usage": {
"cache_read_input_tokens": 130000,
"input_tokens": 26000
}
}
}'
temp_transcript="/tmp/statusline-test-$(date +%s).jsonl"
echo "$mock_context" >"$temp_transcript"
input=$(echo "$input" | jq --arg transcript "$temp_transcript" '{
session_id: "test-session-id",
transcript_path: $transcript,
cwd: .cwd,
model: .model,
workspace: .workspace,
version: .version,
output_style: .output_style,
cost: .cost,
exceeds_200k_tokens: .exceeds_200k_tokens,
context_window: (.context_window // {used_percentage: 15, context_window_size: 1000000}),
effort: .effort,
fast_mode: .fast_mode,
rate_limits: .rate_limits
}' 2>/dev/null)
debug_log "TEST MODE: transformed input: ${input:0:300}..."
else
input=$(cat)
debug_log "RAW STDIN: $input"
fi
# Parse all fields in a single jq call for speed
eval "$(echo "$input" | jq -r '
@sh "model_display=\(.model.display_name // "Unknown")",
@sh "model_id=\(.model.id // "")",
@sh "current_dir=\(.workspace.current_dir // .cwd // "/")",
@sh "project_dir=\(.workspace.project_dir // "")",
@sh "cwd=\(.cwd // "")",
@sh "cost_usd=\(.cost.total_cost_usd // 0)",
@sh "lines_added=\(.cost.total_lines_added // 0)",
@sh "lines_removed=\(.cost.total_lines_removed // 0)",
@sh "api_duration_ms=\(.cost.total_api_duration_ms // 0)",
@sh "duration_ms=\(.cost.total_duration_ms // 0)",
@sh "transcript_path=\(.transcript_path // "")",
@sh "cli_version=\(.version // "")",
@sh "exceeds_200k=\(.exceeds_200k_tokens // false)",
@sh "ctx_pct=\(.context_window.used_percentage // "")",
@sh "ctx_size=\(.context_window.context_window_size // "")",
@sh "effort_level=\(.effort.level // "")",
@sh "fast_mode=\(.fast_mode // false)",
@sh "rl_five_pct=\(.rate_limits.five_hour.used_percentage // "")",
@sh "rl_five_reset=\(.rate_limits.five_hour.resets_at // "")",
@sh "rl_seven_pct=\(.rate_limits.seven_day.used_percentage // "")",
@sh "rl_seven_reset=\(.rate_limits.seven_day.resets_at // "")",
@sh "cache_read_tokens=\(.context_window.current_usage.cache_read_input_tokens // "")",
@sh "cache_creation_tokens=\(.context_window.current_usage.cache_creation_input_tokens // "")",
@sh "uncached_input_tokens=\(.context_window.current_usage.input_tokens // "")",
@sh "stdin_session_id=\(.session_id // "")"
' 2>/dev/null)"
# Detect context window from model ID:
# CLI function NO(A): if A.includes("[1m]") return 1e6; else return 200000;
get_context_limit() {
local mid="$1"
if [[ "$mid" == *"[1m]"* ]]; then
echo 1000000
else
echo 200000
fi
}
debug_log "PARSED INPUT: model=$model_display (id=$model_id) cwd=$current_dir cost=$cost_usd ctx_pct=$ctx_pct exceeds_200k=$exceeds_200k api_duration_ms=$api_duration_ms"
term_width=$(tput cols 2>/dev/null || echo 80)
YELLOW='\033[0;33m'
GREEN='\033[0;32m'
RED='\033[0;31m'
DIM='\033[2m'
DIM_GREEN='\033[2;32m'
DIM_RED='\033[2;31m'
DIM_YELLOW='\033[2;33m'
CYAN='\033[0;36m'
DIM_CYAN='\033[2;36m'
RESET='\033[0m'
# Usage quota tracking
oauth_token_expired() {
local expires_at="${1:-}"
if [ -z "$expires_at" ] || [ "$expires_at" = "null" ]; then
return 1
fi
local expiry
expiry=$(printf '%.0f' "$expires_at" 2>/dev/null) || return 1
# Claude Code stores expiresAt in milliseconds. Accept seconds for older
# notes/tools that used second precision.
if [ "$expiry" -lt 100000000000 ] 2>/dev/null; then
expiry=$((expiry * 1000))
fi
local now_ms="${STATUSLINE_TEST_NOW_MS:-$(($(date +%s) * 1000))}"
[ $((now_ms + 300000)) -ge "$expiry" ]
}
refresh_oauth_credentials_file() {
local cred_file="$1"
local refresh_token scope scope_string payload response http_code body
[ -f "$cred_file" ] || return 1
refresh_token=$(jq -r '.claudeAiOauth.refreshToken // empty' "$cred_file" 2>/dev/null)
[ -n "$refresh_token" ] || return 1
mkdir -p "$CLAUDE_CACHE_DIR"
local lock_file="$CLAUDE_CACHE_DIR/oauth_refresh.lock"
if [ -f "$lock_file" ]; then
local lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || stat -f %m "$lock_file" 2>/dev/null || echo 0)))
[ "$lock_age" -lt 30 ] && return 1
rm -f "$lock_file"
fi
touch "$lock_file"
scope_string=$(jq -r '.claudeAiOauth.scopes // [] | join(" ")' "$cred_file" 2>/dev/null)
if [ -z "$scope_string" ]; then
scope_string="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload"
fi
payload=$(jq -n \
--arg refresh "$refresh_token" \
--arg scope "$scope_string" \
'{
grant_type:"refresh_token",
refresh_token:$refresh,
client_id:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",
scope:$scope
}')
response=$(curl -sS -w "\n%{http_code}" -X POST \
"https://platform.claude.com/v1/oauth/token" \
-H "Content-Type: application/json" \
--data "$payload" \
--max-time 15)
http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | sed '$d')
rm -f "$lock_file"
if [ "$http_code" != "200" ]; then
debug_log "refresh_oauth_credentials_file: refresh failed (code: $http_code)"
return 1
fi
local access_token new_refresh_token expires_in now_ms expires_at scopes_json tmp_file
access_token=$(echo "$body" | jq -r '.access_token // empty' 2>/dev/null)
new_refresh_token=$(echo "$body" | jq -r '.refresh_token // empty' 2>/dev/null)
expires_in=$(echo "$body" | jq -r '.expires_in // empty' 2>/dev/null)
scope=$(echo "$body" | jq -r '.scope // empty' 2>/dev/null)
[ -n "$access_token" ] || return 1
[ -n "$new_refresh_token" ] || new_refresh_token="$refresh_token"
[ -n "$expires_in" ] || expires_in=3600
[ -n "$scope" ] || scope="$scope_string"
now_ms="${STATUSLINE_TEST_NOW_MS:-$(($(date +%s) * 1000))}"
expires_at=$((now_ms + expires_in * 1000))
scopes_json=$(printf '%s' "$scope" | jq -R 'split(" ") | map(select(length > 0))')
tmp_file="${cred_file}.tmp.$$"
jq \
--arg access "$access_token" \
--arg refresh "$new_refresh_token" \
--argjson expires "$expires_at" \
--argjson scopes "$scopes_json" \
'.claudeAiOauth.accessToken = $access
| .claudeAiOauth.refreshToken = $refresh
| .claudeAiOauth.expiresAt = $expires
| .claudeAiOauth.scopes = $scopes' \
"$cred_file" >"$tmp_file" 2>/dev/null || {
rm -f "$tmp_file"
return 1
}
chmod 600 "$tmp_file" 2>/dev/null || true
mv -f "$tmp_file" "$cred_file"
debug_log "refresh_oauth_credentials_file: refreshed OAuth token"
echo "$access_token"
}
get_oauth_token() {
# 1. Credentials file (Linux, or macOS plaintext fallback)
local cred_file="$CLAUDE_HOME/.claude/.credentials.json"
debug_log "get_oauth_token: checking $cred_file (CLAUDE_HOME=$CLAUDE_HOME)"
if [ -f "$cred_file" ]; then
local token=$(jq -r '.claudeAiOauth.accessToken // .access_token // empty' "$cred_file" 2>/dev/null)
if [ -n "$token" ]; then
local expires_at=$(jq -r '.claudeAiOauth.expiresAt // empty' "$cred_file" 2>/dev/null)
if oauth_token_expired "$expires_at"; then
debug_log "get_oauth_token: credentials token expired, attempting refresh"
local refreshed_token
refreshed_token=$(refresh_oauth_credentials_file "$cred_file" 2>/dev/null)
if [ -n "$refreshed_token" ]; then
debug_log "get_oauth_token: refreshed token from credentials file (${#refreshed_token} chars)"
echo "$refreshed_token"
return 0
fi
debug_log "get_oauth_token: refresh failed, using existing token"
fi
debug_log "get_oauth_token: token from credentials file (${#token} chars)"
echo "$token"
return 0
fi
fi
# 2. macOS Keychain — service="Claude Code-credentials", account=$USER
if command -v security >/dev/null 2>&1; then
local keychain_user="${USER:-$(whoami)}"
local service="Claude Code-credentials"
debug_log "get_oauth_token: trying macOS Keychain (service=$service account=$keychain_user)"
local kc_data=$(security find-generic-password -a "$keychain_user" -s "$service" -w 2>/dev/null)
if [ -n "$kc_data" ]; then
local token=$(echo "$kc_data" | jq -r '.claudeAiOauth.accessToken // .access_token // empty' 2>/dev/null)
if [ -n "$token" ]; then
debug_log "get_oauth_token: token from macOS Keychain (${#token} chars)"
echo "$token"
return 0
fi
fi
fi
debug_log "get_oauth_token: no token found"
return 1
}
get_user_profile() {
local token="$1"
local profile_cache="$CLAUDE_CACHE_DIR/profile.cache"
debug_log "get_user_profile: starting (cache: $profile_cache)"
if [ -f "$profile_cache" ]; then
local age=$(($(date +%s) - $(stat -c %Y "$profile_cache" 2>/dev/null || stat -f %m "$profile_cache" 2>/dev/null || echo 0)))
debug_log "get_user_profile: cache exists, age=${age}s"
if [ $age -lt 86400 ]; then
debug_log "get_user_profile: using cached profile"
cat "$profile_cache"
return 0
fi
fi
mkdir -p "$CLAUDE_CACHE_DIR"
debug_log "get_user_profile: fetching from API..."
local response=$(curl -s -w "\n%{http_code}" -X GET \
"https://api.anthropic.com/api/oauth/profile" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
--max-time 5)
local http_code=$(echo "$response" | tail -1)
local body=$(echo "$response" | sed '$d')
debug_log "API RESPONSE: HTTP $http_code"
debug_log "RESPONSE BODY: $body"
if [ "$http_code" = "200" ]; then
echo "$body" >"$profile_cache" 2>/dev/null
debug_log "get_user_profile: profile cached successfully"
cat "$profile_cache"
return 0
else
debug_log "get_user_profile: API failed (code: $http_code), using cache if available"
[ -f "$profile_cache" ] && cat "$profile_cache"
return 1
fi
}
fetch_usage_for_session() {
local session_id="$1"
local cache_file="$CLAUDE_CACHE_DIR/${session_id}.cache"
local lock_file="$CLAUDE_CACHE_DIR/${session_id}.lock"
local err_file="$CLAUDE_CACHE_DIR/${session_id}.err"
mkdir -p "$CLAUDE_CACHE_DIR"
debug_log "fetch_usage_for_session: session=$session_id"
if [ -f "$cache_file" ]; then
local fetched_at=$(jq -r '.fetched_at // 0' "$cache_file" 2>/dev/null)
local five_util=$(jq -r '.five_hour.utilization // 0' "$cache_file" 2>/dev/null)
local age=$(($(date +%s) - fetched_at))
# Adaptive TTL: poll less when quota is low, more when it's hot
local five_int=$(printf '%.0f' "$five_util" 2>/dev/null || echo 0)
local ttl=$(get_adaptive_ttl "$five_int")
debug_log "fetch_usage_for_session: cache age=${age}s ttl=${ttl}s (5h_util=${five_int}%)"
if [ $age -lt $ttl ]; then
cat "$cache_file"
return 0
fi
fi
# Exponential backoff on errors
if [ -f "$err_file" ]; then
local err_at=$(cat "$err_file" 2>/dev/null || echo 0)
local err_age=$(($(date +%s) - err_at))
if [ $err_age -lt 120 ]; then
debug_log "fetch_usage_for_session: in error backoff (${err_age}s < 120s)"
[ -f "$cache_file" ] && cat "$cache_file"
return 0
fi
rm -f "$err_file"
fi
if [ -f "$lock_file" ]; then
local lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || stat -f %m "$lock_file" 2>/dev/null || echo 0)))
if [ $lock_age -lt 10 ]; then
debug_log "fetch_usage_for_session: lock active, skip"
[ -f "$cache_file" ] && cat "$cache_file"
return 0
fi
rm -f "$lock_file"
fi
local token=$(get_oauth_token)
if [ -z "$token" ]; then
debug_log "fetch_usage_for_session: no token available"
[ -f "$cache_file" ] && cat "$cache_file"
return 1
fi
touch "$lock_file"
# Use CLI version from input for User-Agent, fall back to generic
local ua="claude-code/${cli_version:-2.1.76}"
debug_log "fetch_usage_for_session: fetching (User-Agent: $ua)..."
local response=$(curl -s -w "\n%{http_code}" -X GET \
"https://api.anthropic.com/api/oauth/usage" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
-H "User-Agent: $ua" \
--max-time 5)
local http_code=$(echo "$response" | tail -1)
local body=$(echo "$response" | sed '$d')
rm -f "$lock_file"
debug_log "API RESPONSE: HTTP $http_code"
debug_log "RESPONSE BODY: $body"
if [ "$http_code" = "200" ]; then
debug_log "fetch_usage_for_session: success"
debug_log "USAGE DATA: five_hour=$(echo "$body" | jq -r '.five_hour.utilization // "N/A"') seven_day=$(echo "$body" | jq -r '.seven_day.utilization // "N/A"')"
local tmp_cache="${cache_file}.tmp.$$"
echo "$body" | jq --arg ts "$(date +%s)" '. + {fetched_at: ($ts|tonumber)}' >"$tmp_cache" 2>/dev/null
mv -f "$tmp_cache" "$cache_file"
rm -f "$err_file"
cat "$cache_file"
log_usage_snapshot "$session_id" "$body" "$token"
return 0
else
debug_log "fetch_usage_for_session: API failed (code: $http_code)"
date +%s >"$err_file" 2>/dev/null
[ -f "$cache_file" ] && cat "$cache_file"
return 1
fi
}
get_cached_org_uuid() {
local profile_cache="$CLAUDE_CACHE_DIR/profile.cache"
if [ -f "$profile_cache" ]; then
jq -r '.organization.uuid // empty' "$profile_cache" 2>/dev/null
fi
}
fetch_prepaid_balance() {
local org_uuid="$1"
local cache_file="$CLAUDE_CACHE_DIR/prepaid_credits.cache"
local lock_file="$CLAUDE_CACHE_DIR/prepaid_credits.lock"
local err_file="$CLAUDE_CACHE_DIR/prepaid_credits.err"
[ -n "$org_uuid" ] || return 1
mkdir -p "$CLAUDE_CACHE_DIR"
debug_log "fetch_prepaid_balance: org=$org_uuid"
if [ -f "$cache_file" ]; then
local fetched_at=$(jq -r '.fetched_at // 0' "$cache_file" 2>/dev/null)
local age=$(($(date +%s) - fetched_at))
if [ $age -lt 300 ]; then
cat "$cache_file"
return 0
fi
fi
if [ -f "$err_file" ]; then
local err_at=$(cat "$err_file" 2>/dev/null || echo 0)
local err_age=$(($(date +%s) - err_at))
if [ $err_age -lt 120 ]; then
[ -f "$cache_file" ] && cat "$cache_file"
return 0
fi
rm -f "$err_file"
fi
if [ -f "$lock_file" ]; then
local lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || stat -f %m "$lock_file" 2>/dev/null || echo 0)))
if [ $lock_age -lt 10 ]; then
[ -f "$cache_file" ] && cat "$cache_file"
return 0
fi
rm -f "$lock_file"
fi
local token=$(get_oauth_token)
if [ -z "$token" ]; then
debug_log "fetch_prepaid_balance: no token available"
[ -f "$cache_file" ] && cat "$cache_file"
return 1
fi
touch "$lock_file"
local ua="claude-code/${cli_version:-2.1.76}"
local response=$(curl -s -w "\n%{http_code}" -X GET \
"https://api.anthropic.com/api/oauth/organizations/${org_uuid}/prepaid/credits" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
-H "User-Agent: $ua" \
-H "x-organization-uuid: $org_uuid" \
--max-time 5)
local http_code=$(echo "$response" | tail -1)
local body=$(echo "$response" | sed '$d')
rm -f "$lock_file"
debug_log "PREPAID API RESPONSE: HTTP $http_code"
debug_log "PREPAID RESPONSE BODY: $body"
if [ "$http_code" = "200" ]; then
local tmp_cache="${cache_file}.tmp.$$"
echo "$body" | jq --arg ts "$(date +%s)" '. + {fetched_at: ($ts|tonumber)}' >"$tmp_cache" 2>/dev/null
mv -f "$tmp_cache" "$cache_file"
rm -f "$err_file"
cat "$cache_file"
return 0
else
debug_log "fetch_prepaid_balance: API failed (code: $http_code)"
date +%s >"$err_file" 2>/dev/null
[ -f "$cache_file" ] && cat "$cache_file"
return 1
fi
}
log_usage_snapshot() {
local session_id="$1"
local usage_data="$2"
local token="$3"
mkdir -p "$CLAUDE_DATA_DIR"
local usage_log="$CLAUDE_DATA_DIR/usage.jsonl"
debug_log "log_usage_snapshot: session=$session_id"
detect_session_boundary "$session_id" "$usage_data"
local user_email=""
local user_name=""
local user_uuid=""
local user_display_name=""
local has_claude_pro="false"
local has_claude_max="false"
local org_name=""
local org_type=""
local billing_type=""
local rate_limit_tier=""
if [ -n "$token" ]; then
debug_log "log_usage_snapshot: fetching user profile..."
local profile=$(get_user_profile "$token")
if [ -n "$profile" ]; then
debug_log "log_usage_snapshot: profile received: ${profile:0:100}..."
eval "$(echo "$profile" | jq -r '
@sh "user_email=\(.account.email // .email // "")",
@sh "user_name=\(.account.full_name // .account.display_name // .name // "")",
@sh "user_uuid=\(.account.uuid // "")",
@sh "user_display_name=\(.account.display_name // "")",
@sh "has_claude_pro=\(.account.has_claude_pro // false)",
@sh "has_claude_max=\(.account.has_claude_max // false)",
@sh "org_name=\(.organization.name // "")",
@sh "org_type=\(.organization.organization_type // "")",
@sh "billing_type=\(.organization.billing_type // "")",
@sh "rate_limit_tier=\(.organization.rate_limit_tier // "")"
' 2>/dev/null)"
debug_log "log_usage_snapshot: extracted email='$user_email' name='$user_name' uuid='$user_uuid' pro='$has_claude_pro' max='$has_claude_max'"
else
debug_log "log_usage_snapshot: no profile data returned"
fi
else
debug_log "log_usage_snapshot: no token provided"
fi
echo "$usage_data" | jq -c \
--arg sid "$session_id" \
--arg ts "$(date +%s)" \
--arg email "$user_email" \
--arg name "$user_name" \
--arg uuid "$user_uuid" \
--arg display_name "$user_display_name" \
--arg pro "$has_claude_pro" \
--arg max "$has_claude_max" \
--arg org_name "$org_name" \
--arg org_type "$org_type" \
--arg billing "$billing_type" \
--arg rate_limit "$rate_limit_tier" \
'{
type:"usage",
session_id:$sid,
timestamp:($ts|tonumber),
user: {
email: $email,
name: $name,
uuid: $uuid,
display_name: $display_name,
subscriptions: {
claude_pro: ($pro == "true"),
claude_max: ($max == "true")
}
},
organization: {
name: $org_name,
type: $org_type,
billing_type: $billing,
rate_limit_tier: $rate_limit
},
five_hour:.five_hour,
seven_day:.seven_day,
seven_day_opus:.seven_day_opus,
extra_usage:.extra_usage
}' \
>>"$usage_log" 2>/dev/null
}
detect_session_boundary() {
local session_id="$1"
local usage_data="$2"
local usage_log="$CLAUDE_DATA_DIR/usage.jsonl"
local current_five_hour_reset=$(echo "$usage_data" | jq -r '.five_hour.resets_at // empty' 2>/dev/null)
local current_seven_day_reset=$(echo "$usage_data" | jq -r '.seven_day.resets_at // empty' 2>/dev/null)
_emit_session_start() {
jq -n -c --arg sid "$session_id" --arg ts "$(date +%s)" \
--arg fh "$current_five_hour_reset" --arg sd "$current_seven_day_reset" \
'{type:"session_start",session_id:$sid,timestamp:($ts|tonumber),
five_hour_window_end:$fh,seven_day_window_end:$sd}' \
>>"$usage_log" 2>/dev/null
}
if [ ! -f "$usage_log" ]; then
_emit_session_start
return 0
fi
local last_entry=$(tail -1 "$usage_log" 2>/dev/null)
if [ -z "$last_entry" ]; then
_emit_session_start
return 0
fi
local last_five_hour_reset=$(echo "$last_entry" | jq -r '.five_hour.resets_at // .data.five_hour.resets_at // empty' 2>/dev/null)
local last_session_id=$(echo "$last_entry" | jq -r '.session_id // empty' 2>/dev/null)
if [ "$last_five_hour_reset" != "$current_five_hour_reset" ] && [ -n "$last_five_hour_reset" ]; then
if [ -n "$last_session_id" ] && [ "$last_session_id" != "$session_id" ]; then
jq -n -c --arg sid "$last_session_id" --arg ts "$(date +%s)" \
'{type:"session_end",session_id:$sid,timestamp:($ts|tonumber)}' \
>>"$usage_log" 2>/dev/null
fi
_emit_session_start
fi
}
should_show_extra() {
local mode="$1" five_int="${2:-0}" seven_int="${3:-0}" extra_util="${4:-0}"
local five_reset_secs="${5:-}" seven_reset_secs="${6:-}"
case "$mode" in
"off") return 1 ;;
"on-limit")
[ "$five_int" -ge 80 ] || [ "$seven_int" -ge 70 ]
return $?
;;
"auto")
# Recovery suppresses pressure: if reset is imminent, quota isn't really "running out"
if [ "$five_int" -ge 80 ]; then
if [ -z "$five_reset_secs" ] || [ "$five_reset_secs" -gt $FIVE_HOUR_RECOVERY_SECS ] 2>/dev/null; then
return 0
fi
fi
if [ "$seven_int" -ge 70 ]; then
if [ -z "$seven_reset_secs" ] || [ "$seven_reset_secs" -gt $SEVEN_DAY_RECOVERY_SECS ] 2>/dev/null; then
return 0
fi
fi
[ "$extra_util" -ge $EXTRA_AUTO_UTIL_PCT ] && return 0
return 1
;;
*) return 0 ;;
esac
}
get_cache_health() {
local cache_read="${1:-0}" cache_creation="${2:-0}" uncached="${3:-0}"
local state_file="${4:-}"
[ -z "$cache_read" ] && cache_read=0
[ -z "$cache_creation" ] && cache_creation=0
[ -z "$uncached" ] && uncached=0
cache_read=$(printf '%.0f' "$cache_read" 2>/dev/null) || cache_read=0
cache_creation=$(printf '%.0f' "$cache_creation" 2>/dev/null) || cache_creation=0
uncached=$(printf '%.0f' "$uncached" 2>/dev/null) || uncached=0
local total=$((cache_read + cache_creation + uncached))
if [ "$total" -le 0 ]; then
echo "none"
return
fi
local prev_cache_read=""
[ -n "$state_file" ] && [ -f "$state_file" ] && prev_cache_read=$(cat "$state_file" 2>/dev/null)
if [ -n "$state_file" ]; then
mkdir -p "$(dirname "$state_file")" 2>/dev/null
echo "$cache_read" > "$state_file" 2>/dev/null
fi
if [ -z "$prev_cache_read" ] || [ "$prev_cache_read" -le 0 ] 2>/dev/null; then
if [ "$cache_read" -le 0 ] && [ "$cache_creation" -gt 0 ]; then
echo "building"
return
fi
echo "ok"
return
fi
local drop=$((prev_cache_read - cache_read))
local threshold=$((prev_cache_read * (100 - CACHE_BREAK_DROP_PCT) / 100))
if [ "$drop" -gt "$CACHE_BREAK_MIN_TOKENS" ] && [ "$cache_read" -lt "$threshold" ]; then
echo "break"
return
fi
if [ "$cache_read" -le 0 ] && [ "$cache_creation" -gt "$CACHE_BREAK_MIN_TOKENS" ]; then
echo "building"
return
fi
echo "ok"
}
render_bar() {
local pct=$1 width=$2 fill_char=$3 empty_char=$4
local filled=$((pct * width / 100))
[ "$pct" -gt 0 ] && [ "$filled" -eq 0 ] && filled=1
local empty=$((width - filled))
local bar=""
for ((i=0; i<filled; i++)); do bar+="$fill_char"; done
for ((i=0; i<empty; i++)); do bar+="$empty_char"; done
printf '%s' "$bar"
}
format_money_minor() {
local amount="${1:-}"
local currency="${2:-USD}"
local mode="${3:-fit}"
if [ -z "$amount" ] || [ "$amount" = "null" ]; then
echo ""
return
fi
local minor
minor=$(printf '%.0f' "$amount" 2>/dev/null) || {
echo ""
return
}
local upper_currency
upper_currency=$(printf '%s' "$currency" | tr '[:lower:]' '[:upper:]')
local symbol=""
case "$upper_currency" in
USD) symbol="$" ;;
EUR) symbol="€" ;;
GBP) symbol="£" ;;
JPY) symbol="¥" ;;
CAD) symbol="CA$" ;;
AUD) symbol="A$" ;;
NZD) symbol="NZ$" ;;
SGD) symbol="S$" ;;
BRL) symbol="R$" ;;
*) symbol="${upper_currency} " ;;
esac
case "$upper_currency" in
JPY|KRW|VND)
printf "%s%d" "$symbol" "$minor"
return
;;
esac
if [ "$mode" = "whole" ]; then
printf "%s%d" "$symbol" $(((minor + 50) / 100))
return
fi
local whole=$((minor / 100))
local cents=$((minor % 100))
if [ "$cents" -eq 0 ]; then
printf "%s%d" "$symbol" "$whole"
else
printf "%s%d.%02d" "$symbol" "$whole" "$cents"
fi
}
get_adaptive_ttl() {
local five_int=${1:-0}
if [ "$five_int" -ge 80 ]; then echo 30
elif [ "$five_int" -ge 50 ]; then echo 60
elif [ "$five_int" -ge 20 ]; then echo 120
else echo 300
fi
}
format_duration() {
local ms=${1:-0}
[ "$ms" -le 0 ] 2>/dev/null && { echo "0m"; return; }
local mins=$((ms / 60000))
[ $mins -eq 0 ] && mins=1
if [ $mins -ge 60 ]; then
local h=$((mins / 60))
local m=$((mins % 60))
if [ $m -gt 0 ]; then
echo "${h}h${m}m"
else
echo "${h}h"
fi
else
echo "${mins}m"
fi
}
format_reset_relative() {
local ts="$1"
[ -z "$ts" ] || [ "$ts" = "null" ] && return
local reset_epoch now_epoch delta
if [[ "$ts" =~ ^[0-9]+$ ]]; then
reset_epoch="$ts"
else
reset_epoch=$(date -d "$ts" +%s 2>/dev/null) || return
fi
now_epoch=$(date +%s)
delta=$((reset_epoch - now_epoch))
[ "$delta" -le 0 ] && { echo "now"; return; }
local days=$((delta / 86400))
local hours=$(((delta % 86400) / 3600))
local mins=$(((delta % 3600) / 60))
if [ "$days" -gt 0 ]; then
if [ "$hours" -gt 0 ]; then echo "${days}d${hours}h"
else echo "${days}d"
fi
elif [ "$hours" -gt 0 ]; then
if [ "$mins" -gt 0 ]; then echo "${hours}h${mins}m"
else echo "${hours}h"
fi
else
echo "${mins}m"
fi
}
format_reset_absolute() {
local ts="$1" kind="${2:-short}"
[ -z "$ts" ] || [ "$ts" = "null" ] && return
local reset_epoch
if [[ "$ts" =~ ^[0-9]+$ ]]; then
reset_epoch="$ts"
else
reset_epoch=$(date -d "$ts" +%s 2>/dev/null) || return
fi
local now_epoch=$(date +%s)
local delta=$((reset_epoch - now_epoch))
[ "$delta" -le 0 ] && { echo "now"; return; }
if [ "$kind" = "day" ]; then
local reset_day=$(date -d "@$reset_epoch" +%a 2>/dev/null) || return
local today=$(date +%a)
if [ "$reset_day" = "$today" ]; then
date -d "@$reset_epoch" +%H:%M 2>/dev/null
else
echo "$reset_day"
fi
else
date -d "@$reset_epoch" +%H:%M 2>/dev/null
fi
}
get_reset_seconds() {
local ts="$1"
[ -z "$ts" ] || [ "$ts" = "null" ] && { echo ""; return; }
local reset_epoch now_epoch
if [[ "$ts" =~ ^[0-9]+$ ]]; then
reset_epoch="$ts"
else
reset_epoch=$(date -d "$ts" +%s 2>/dev/null) || { echo ""; return; }
fi
now_epoch=$(date +%s)
local delta=$((reset_epoch - now_epoch))
[ "$delta" -lt 0 ] && delta=0
echo "$delta"
}
get_usage_color() {
local percent=$(printf '%.0f' "$1" 2>/dev/null || echo 0)
if [ "$percent" -ge 90 ]; then
echo "$RED"
elif [ "$percent" -ge 80 ]; then
echo "$YELLOW"
else
echo "$GREEN"
fi
}