-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmycc
More file actions
executable file
·1112 lines (958 loc) · 35.7 KB
/
mycc
File metadata and controls
executable file
·1112 lines (958 loc) · 35.7 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 bash
set -euo pipefail
# ============================================
# MyCC (My Claude Code) - quota monitor + auto-resume
# Combines monitoring + countdown + auto-resume for Claude Code
# ============================================
VERSION="1.0.0"
CONF_FILE="$HOME/.mycc.conf"
# --- Defaults ---
MODE="basic"
RESUME_MODE="continue"
RESUME_PROMPT="continue"
AUTO_RESUME=true
WATCH_MODE=false
CHECK_ONLY=false
OUTPUT_JSON=false
QUIET=false
NO_COLOR=false
NOTIFY=true
REFRESH_INTERVAL=120
TEST_MODE_SECS=""
SESSION_KEY=""
ORG_ID=""
COMPACT=false
LAUNCH=false
LAUNCH_ARGS=""
LAUNCH_DETAILED=false
# --- State ---
LIMIT_DETECTED=false
LIMIT_NAME=""
RESET_TIMESTAMP=""
FIVE_HOUR_PCT="" FIVE_HOUR_RESETS=""
SEVEN_DAY_PCT="" SEVEN_DAY_RESETS=""
OPUS_PCT="" OPUS_RESETS=""
SONNET_PCT="" SONNET_RESETS=""
IS_GNU_DATE=false
RAW_LIMIT_MSG=""
# --- ANSI Colors ---
C_RESET=$'\033[0m'
C_RED=$'\033[31m'
C_GREEN=$'\033[32m'
C_YELLOW=$'\033[33m'
C_BLUE=$'\033[34m'
C_MAGENTA=$'\033[35m'
C_CYAN=$'\033[36m'
C_BOLD=$'\033[1m'
C_DIM=$'\033[2m'
# ============================================
# Utility Functions
# ============================================
info() { echo -e "${C_CYAN}[INFO]${C_RESET} $*"; }
warn() { echo -e "${C_YELLOW}[WARN]${C_RESET} $*" >&2; }
error() { echo -e "${C_RED}[ERROR]${C_RESET} $*" >&2; }
die() { error "$@"; exit 1; }
detect_os() {
if date --version &>/dev/null; then
IS_GNU_DATE=true
else
IS_GNU_DATE=false
fi
}
# Convert ISO 8601 (UTC) to epoch seconds
iso_to_epoch() {
local iso="$1"
[[ -z "$iso" ]] && return 1
# Strip fractional seconds: 2026-02-10T15:00:00.123Z -> 2026-02-10T15:00:00Z
local cleaned
cleaned=$(echo "$iso" | sed -E 's/\.[0-9]+Z$/Z/')
if $IS_GNU_DATE; then
date -d "$cleaned" +%s
else
# BSD date: strip Z, replace T with space
local dt="${cleaned%Z}"
dt="${dt//T/ }"
date -j -u -f "%Y-%m-%d %H:%M:%S" "$dt" +%s
fi
}
# Format seconds to human-readable duration
format_duration() {
local secs="$1"
local days=$(( secs / 86400 ))
local hours=$(( (secs % 86400) / 3600 ))
local mins=$(( (secs % 3600) / 60 ))
local s=$(( secs % 60 ))
if (( days > 0 )); then
printf "%dd %02dh %02dm %02ds" "$days" "$hours" "$mins" "$s"
elif (( hours > 0 )); then
printf "%02d:%02d:%02d" "$hours" "$mins" "$s"
else
printf "%02d:%02d" "$mins" "$s"
fi
}
# Return ANSI color based on utilization percentage
color_for_pct() {
local pct="$1"
if (( pct < 50 )); then echo -ne "$C_GREEN"
elif (( pct < 70 )); then echo -ne "$C_YELLOW"
elif (( pct < 90 )); then echo -ne "$C_RED"
else echo -ne "${C_BOLD}${C_RED}"
fi
}
# Render a bar graph: [████████░░░░] 65%
bar_graph() {
local pct="$1"
local width="${2:-20}"
(( pct > 100 )) && pct=100
local filled=$(( pct * width / 100 ))
local empty=$(( width - filled ))
local bar=""
local i
for (( i=0; i<filled; i++ )); do bar+="█"; done
for (( i=0; i<empty; i++ )); do bar+="░"; done
local color
color=$(color_for_pct "$pct")
printf "%b[%s]%b %3d%%" "$color" "$bar" "$C_RESET" "$pct"
}
# Run command with timeout (macOS compatible)
run_with_timeout() {
local secs="$1"; shift
perl -e "alarm $secs; exec @ARGV" -- "$@"
}
# ============================================
# Configuration
# ============================================
load_config() {
if [[ -f "$CONF_FILE" ]]; then
local perms
perms=$(stat -f '%Lp' "$CONF_FILE" 2>/dev/null || stat -c '%a' "$CONF_FILE" 2>/dev/null)
if [[ "$perms" != "600" ]]; then
warn "Config file permissions are $perms, should be 600. Run: chmod 600 $CONF_FILE"
fi
# Source config, overriding defaults
local key val
while IFS='=' read -r key val; do
key=$(echo "$key" | xargs)
[[ -z "$key" || "$key" == \#* ]] && continue
val=$(echo "$val" | sed 's/^["'"'"']//; s/["'"'"']$//')
case "$key" in
SESSION_KEY) [[ -z "$SESSION_KEY" ]] && SESSION_KEY="$val" ;;
ORG_ID) [[ -z "$ORG_ID" ]] && ORG_ID="$val" ;;
RESUME_MODE) RESUME_MODE="$val" ;;
RESUME_PROMPT) RESUME_PROMPT="$val" ;;
REFRESH_INTERVAL) REFRESH_INTERVAL="$val" ;;
NOTIFY) NOTIFY="$val" ;;
esac
done < "$CONF_FILE"
fi
}
# ============================================
# CLI Argument Parsing
# ============================================
show_help() {
cat <<'HELP'
mycc - Claude Code quota monitor + auto-resume
Usage: mycc [OPTIONS]
Modes:
(no flag) Basic mode - detect limits via claude CLI
-d, --detailed Detailed mode - Claude.ai API for utilization %
Auto-resume:
-c, --continue Continue previous conversation (default)
-n, --new Start new session when resuming
-p, --prompt TEXT Custom resume prompt (default: "continue")
--no-resume Monitor only, don't auto-resume
-w, --watch Keep watching after resume (loop mode)
Configuration:
--setup Interactive setup wizard
--org-id ID Override organization ID (one-time)
--refresh Open browser to download fresh usage data
--bookmarklet Show bookmarklet for one-click refresh
Launch:
--launch Start tmux: Claude Code (top) + status bar (bottom)
--launch "ARGS" Same, but pass ARGS to claude (e.g. --launch "-c")
Display:
--compact Single-line status bar (for tmux pane)
-q, --quiet Minimal output
--no-color Disable ANSI colors
--json Output status as JSON
--check One-shot status check, then exit
Other:
--test-mode SECS Simulate rate limit (for testing)
-h, --help Show this help
-v, --version Show version
Examples:
mycc --launch # Start Claude + live status bar
mycc --launch "-c" # Continue previous session + bar
mycc -d --compact # Detailed compact bar (standalone)
mycc --test-mode 10 # Test with simulated limit
HELP
}
parse_args() {
while [[ $# -gt 0 ]]; do
case "$1" in
-d|--detailed) MODE=detailed; shift ;;
-c|--continue) RESUME_MODE=continue; shift ;;
-n|--new) RESUME_MODE=new; shift ;;
-p|--prompt) [[ -z "${2:-}" ]] && die "-p requires a value"; RESUME_PROMPT="$2"; shift 2 ;;
--no-resume) AUTO_RESUME=false; shift ;;
-w|--watch) WATCH_MODE=true; shift ;;
--setup) setup_wizard; trap - EXIT; exit 0 ;;
--org-id) [[ -z "${2:-}" ]] && die "--org-id requires a value"; ORG_ID="$2"; shift 2 ;;
--refresh) REFRESH_CMD=true; shift ;;
--bookmarklet) BOOKMARKLET_CMD=true; shift ;;
--launch) LAUNCH=true; shift; if [[ -n "${1:-}" && "${1:-}" != --* ]]; then LAUNCH_ARGS="$1"; shift; fi ;;
--compact) COMPACT=true; WATCH_MODE=true; AUTO_RESUME=false; shift ;;
-q|--quiet) QUIET=true; shift ;;
--no-color) NO_COLOR=true; shift ;;
--json) OUTPUT_JSON=true; shift ;;
--check) CHECK_ONLY=true; AUTO_RESUME=false; shift ;;
--test-mode) [[ -z "${2:-}" ]] && die "--test-mode requires seconds"; TEST_MODE_SECS="$2"; shift 2 ;;
-h|--help) show_help; trap - EXIT; exit 0 ;;
-v|--version) echo "mycc v${VERSION}"; trap - EXIT; exit 0 ;;
*) die "Unknown option: $1. Use --help for usage." ;;
esac
done
}
# ============================================
# Basic Mode: CLI Detection
# ============================================
check_basic() {
info "Checking Claude Code status..."
local output exit_code=0
output=$(run_with_timeout 120 claude -p 'check' 2>&1) || exit_code=$?
# Pattern 1: "hit your limit · resets 3am" or "hit your limit · resets 3am (Europe/Paris)"
# Pattern 2: "5-hour limit reached · resets 3am"
# Pattern 3: Old pipe format "Claude AI usage limit reached|<timestamp>"
local limit_line
limit_line=$(echo "$output" | grep -E "(hit your limit|limit reached).*resets" || true)
if [[ -n "$limit_line" ]]; then
LIMIT_DETECTED=true
RAW_LIMIT_MSG="$limit_line"
parse_reset_time_from_msg "$limit_line"
return
fi
# Old pipe format
limit_line=$(echo "$output" | grep -F "usage limit reached|" || true)
if [[ -n "$limit_line" ]]; then
LIMIT_DETECTED=true
RAW_LIMIT_MSG="$limit_line"
RESET_TIMESTAMP=$(echo "$limit_line" | awk -F'|' '{print $2}' | tr -d '[:space:]')
return
fi
LIMIT_DETECTED=false
}
parse_reset_time_from_msg() {
local msg="$1"
# Extract reset time like "3am", "11pm", "12am"
local reset_raw
reset_raw=$(echo "$msg" | grep -oE 'resets [0-9]{1,2}[ap]m' | awk '{print $2}')
if [[ -z "$reset_raw" ]]; then
warn "Could not parse reset time from: $msg"
# Fallback: 30 minutes from now
RESET_TIMESTAMP=$(( $(date +%s) + 1800 ))
LIMIT_NAME="unknown"
return
fi
local hour period hour24
hour=$(echo "$reset_raw" | sed 's/[ap]m$//')
period=$(echo "$reset_raw" | grep -oE '[ap]m$')
if [[ "$period" == "am" ]]; then
hour24=$(( hour == 12 ? 0 : hour ))
else
hour24=$(( hour == 12 ? 12 : hour + 12 ))
fi
local now_ts today_reset
now_ts=$(date +%s)
if $IS_GNU_DATE; then
today_reset=$(date -d "today ${hour24}:00:00" +%s)
else
today_reset=$(date -j -f "%Y-%m-%d %H:%M:%S" "$(date +%Y-%m-%d) $(printf '%02d' $hour24):00:00" +%s)
fi
if (( now_ts > today_reset )); then
# Reset is tomorrow
if $IS_GNU_DATE; then
RESET_TIMESTAMP=$(date -d "tomorrow ${hour24}:00:00" +%s)
else
local tomorrow
tomorrow=$(date -j -v+1d +%Y-%m-%d)
RESET_TIMESTAMP=$(date -j -f "%Y-%m-%d %H:%M:%S" "${tomorrow} $(printf '%02d' $hour24):00:00" +%s)
fi
else
RESET_TIMESTAMP=$today_reset
fi
# Extract limit name if present
LIMIT_NAME=$(echo "$msg" | grep -oE '[0-9]+-hour' || echo "usage")
}
# ============================================
# Detailed Mode: Local cache + browser refresh
# ============================================
USAGE_CACHE="$HOME/.mycc-usage.json"
# Refresh usage data via local HTTP server + browser
refresh_usage() {
if [[ -z "$ORG_ID" ]]; then
die "No ORG_ID configured. Run 'mycc --setup' first."
fi
local port=18898
local html_file="/tmp/mycc-refresh-$$.html"
# Create HTML page with refresh script
cat > "$html_file" <<REFRESH
<!DOCTYPE html>
<html><head><title>MyCC Refresh</title></head>
<body>
<h2>MyCC 用量刷新</h2>
<p>点击下方按钮刷新数据:</p>
<button onclick="refresh()">刷新用量数据</button>
<p id="msg"></p>
<script>
const orgId = '$ORG_ID';
function refresh() {
document.getElementById('msg').textContent = '刷新中...';
fetch('https://claude.ai/api/organizations/' + orgId + '/usage')
.then(r => r.json())
.then(d => {
// Download as file (auto-imported by mycc)
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([JSON.stringify(d)]));
a.download = 'mycc-usage.json';
a.click();
document.getElementById('msg').textContent = '✓ 刷新成功!可以关闭此页面了。';
document.getElementById('msg').style.color = 'green';
})
.catch(e => {
document.getElementById('msg').textContent = '✗ 失败: ' + e.message;
document.getElementById('msg').style.color = 'red';
});
}
</script></body></html>
REFRESH
info "打开浏览器刷新页面..."
open "file://$html_file" 2>/dev/null || {
warn "无法自动打开浏览器。请手动打开: file://$html_file"
return
}
info "请在浏览器中点击'刷新用量数据'按钮"
info "下载的文件会被自动导入到 ~/.mycc-usage.json"
}
# Import usage JSON from Downloads folder or a given path
import_usage() {
local src="${1:-$HOME/Downloads/mycc-usage.json}"
if [[ ! -f "$src" ]]; then
die "File not found: $src"
fi
# Validate JSON
if ! jq -e '.five_hour' "$src" &>/dev/null; then
die "Invalid usage JSON: $src"
fi
cp "$src" "$USAGE_CACHE"
info "Imported usage data to $USAGE_CACHE"
# Clean up source if it's in Downloads
if [[ "$src" == "$HOME/Downloads/mycc-usage.json" ]]; then
rm -f "$src"
fi
}
check_detailed() {
local dl_file="$HOME/Downloads/mycc-usage.json"
# Auto-import from Downloads if:
# - cache doesn't exist, OR
# - Downloads file is newer than cache
if [[ -f "$dl_file" ]]; then
local should_import=false
if [[ ! -f "$USAGE_CACHE" ]]; then
should_import=true
else
# Compare modification times
local cache_ts dl_ts
if [[ "$IS_GNU_DATE" == "false" ]]; then
cache_ts=$(stat -f '%m' "$USAGE_CACHE")
dl_ts=$(stat -f '%m' "$dl_file")
else
cache_ts=$(stat -c '%Y' "$USAGE_CACHE")
dl_ts=$(stat -c '%Y' "$dl_file")
fi
if (( dl_ts > cache_ts )); then
should_import=true
fi
fi
if [[ "$should_import" == "true" ]]; then
import_usage "$dl_file" 2>/dev/null || true
fi
fi
if [[ ! -f "$USAGE_CACHE" ]]; then
die "No usage data. Run in browser console at claude.ai:\n\n fetch('/api/organizations/${ORG_ID}/usage').then(r=>r.json()).then(d=>{var a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(d)]));a.download='mycc-usage.json';a.click()})\n\nThen run: mycc -d --check"
fi
local body
body=$(cat "$USAGE_CACHE")
# Show cache age
local cache_ts
if [[ "$IS_GNU_DATE" == "false" ]]; then
cache_ts=$(stat -f '%m' "$USAGE_CACHE")
else
cache_ts=$(stat -c '%Y' "$USAGE_CACHE")
fi
local now_ts
now_ts=$(date +%s)
local age=$(( now_ts - cache_ts ))
local age_min=$(( age / 60 ))
if (( age_min > 0 )); then
info "Usage data is ${age_min}m old (from cache)"
fi
# Parse — utilization is already 0-100 integer from the API
FIVE_HOUR_PCT=$(echo "$body" | jq -r '.five_hour.utilization // 0')
FIVE_HOUR_RESETS=$(echo "$body" | jq -r '.five_hour.resets_at // empty')
SEVEN_DAY_PCT=$(echo "$body" | jq -r '.seven_day.utilization // 0')
SEVEN_DAY_RESETS=$(echo "$body" | jq -r '.seven_day.resets_at // empty')
# Opus/Sonnet may be null (no separate limit) — use empty string to distinguish from 0%
OPUS_PCT=$(echo "$body" | jq -r 'if .seven_day_opus then (.seven_day_opus.utilization // 0) else "" end')
OPUS_RESETS=$(echo "$body" | jq -r '.seven_day_opus.resets_at // empty')
SONNET_PCT=$(echo "$body" | jq -r 'if .seven_day_sonnet then (.seven_day_sonnet.utilization // 0) else "" end')
SONNET_RESETS=$(echo "$body" | jq -r '.seven_day_sonnet.resets_at // empty')
# Determine which limit is hit (if any)
LIMIT_DETECTED=false
RESET_TIMESTAMP=""
LIMIT_NAME=""
local check_limit
check_limit() {
local name="$1" pct="$2" resets="$3"
if (( pct >= 100 )) && [[ -n "$resets" ]]; then
LIMIT_DETECTED=true
LIMIT_NAME="$name"
RESET_TIMESTAMP=$(iso_to_epoch "$resets")
fi
}
# Check in priority order: 5-hour first (most common)
check_limit "5-hour" "${FIVE_HOUR_PCT:-0}" "${FIVE_HOUR_RESETS:-}"
if [[ "$LIMIT_DETECTED" != "true" ]]; then
check_limit "7-day Opus" "${OPUS_PCT:-0}" "${OPUS_RESETS:-}"
fi
if [[ "$LIMIT_DETECTED" != "true" ]]; then
check_limit "7-day Sonnet" "${SONNET_PCT:-0}" "${SONNET_RESETS:-}"
fi
if [[ "$LIMIT_DETECTED" != "true" ]]; then
check_limit "7-day" "${SEVEN_DAY_PCT:-0}" "${SEVEN_DAY_RESETS:-}"
fi
}
# ============================================
# Terminal Display
# ============================================
draw_line() {
local width="$1" char="${2:-─}"
local i
for (( i=0; i<width; i++ )); do printf "%s" "$char"; done
}
# Print a box row: │ <content padded to W visible chars> │
# $1 = visible_text (plain, no ANSI)
# $2 = formatted_text (with ANSI codes, same visible content as $1)
# $3 = W (box inner width)
boxrow() {
local visible="$1" formatted="$2" W="$3"
local vlen=${#visible}
local pad=$(( W - vlen ))
(( pad < 0 )) && pad=0
printf " %b│%b%s%*s%b│%b\n" "$C_DIM" "$C_RESET" "$formatted" "$pad" "" "$C_DIM" "$C_RESET"
}
render_status() {
local W=52
printf "\n"
printf " %b┌%s┐%b\n" "$C_DIM" "$(draw_line $W)" "$C_RESET"
local title=" MyCC v${VERSION}"
boxrow "$title" " ${C_BOLD}MyCC${C_RESET} v${VERSION}" "$W"
printf " %b├%s┤%b\n" "$C_DIM" "$(draw_line $W)" "$C_RESET"
if [[ "$MODE" == "detailed" ]]; then
render_detailed_body "$W"
else
render_basic_body "$W"
fi
printf " %b└%s┘%b\n" "$C_DIM" "$(draw_line $W)" "$C_RESET"
}
render_basic_body() {
local W="$1"
if [[ "$LIMIT_DETECTED" == "true" ]]; then
local reset_human remaining_human
reset_human=$(date -r "$RESET_TIMESTAMP" "+%Y-%m-%d %H:%M" 2>/dev/null || date -d "@$RESET_TIMESTAMP" "+%Y-%m-%d %H:%M" 2>/dev/null)
local now_ts remaining
now_ts=$(date +%s)
remaining=$(( RESET_TIMESTAMP - now_ts ))
(( remaining < 0 )) && remaining=0
remaining_human=$(format_duration "$remaining")
local s=" Status: RATE LIMITED"
boxrow "$s" " Status: ${C_RED}RATE LIMITED${C_RESET}" "$W"
s=" Limit: ${LIMIT_NAME} limit reached"
boxrow "$s" "$s" "$W"
local rl="$reset_human (in $remaining_human)"
s=" Resets: $rl"
boxrow "$s" " Resets: ${C_CYAN}${rl}${C_RESET}" "$W"
if [[ "$AUTO_RESUME" == "true" ]]; then
local at="Auto-resume ($RESUME_MODE)"
s=" Action: $at"
boxrow "$s" " Action: ${C_GREEN}${at}${C_RESET}" "$W"
else
s=" Action: Monitor only"
boxrow "$s" "$s" "$W"
fi
else
local s=" Status: ALL CLEAR"
boxrow "$s" " Status: ${C_GREEN}ALL CLEAR${C_RESET}" "$W"
s=" No rate limit detected."
boxrow "$s" "$s" "$W"
fi
}
render_detailed_body() {
local W="$1"
local dimensions=("5-Hour" "7-Day" "Opus" "Sonnet")
local pcts=("${FIVE_HOUR_PCT:-0}" "${SEVEN_DAY_PCT:-0}" "${OPUS_PCT:-}" "${SONNET_PCT:-}")
local resets_arr=("${FIVE_HOUR_RESETS:-}" "${SEVEN_DAY_RESETS:-}" "${OPUS_RESETS:-}" "${SONNET_RESETS:-}")
for idx in "${!dimensions[@]}"; do
local name="${dimensions[$idx]}"
local pct="${pcts[$idx]}"
local reset_iso="${resets_arr[$idx]}"
# Skip dimensions that are null (empty pct) from the API
if [[ -z "$pct" ]]; then
continue
fi
local reset_short=""
if [[ -n "$reset_iso" ]]; then
local reset_epoch
reset_epoch=$(iso_to_epoch "$reset_iso" 2>/dev/null || echo "")
if [[ -n "$reset_epoch" ]]; then
reset_short=$(date -r "$reset_epoch" "+%b %d %l%p" 2>/dev/null | sed 's/ / /g' || echo "")
fi
fi
local bar_str
bar_str=$(bar_graph "$pct" 20)
local label
label=$(printf "%-7s" "$name")
local reset_padded
reset_padded=$(printf "%-13s" "$reset_short")
# Visible: " " + label(7) + " " + bar_visible(27) + " " + reset(13) = 51
# bar_visible = [xxxx] NNN% = 1+20+1+1+3+1 = 27
local visible_line=" ${label} $(printf '['; printf '%0.s#' $(seq 1 20); printf '] %3d%%' "$pct") ${reset_padded}"
# Simplified: count directly
local vlen=$(( 2 + 7 + 1 + 27 + 1 + 13 )) # = 51
local pad=$(( W - vlen ))
(( pad < 0 )) && pad=0
printf " %b│%b %s %s %s%*s%b│%b\n" \
"$C_DIM" "$C_RESET" "$label" "$bar_str" "$reset_padded" "$pad" "" "$C_DIM" "$C_RESET"
done
boxrow "" "" "$W"
if [[ "$LIMIT_DETECTED" == "true" ]]; then
local st="RATE LIMITED ($LIMIT_NAME)"
local s=" Status: $st"
boxrow "$s" " Status: ${C_RED}${st}${C_RESET}" "$W"
if [[ -n "$RESET_TIMESTAMP" ]]; then
local now_ts remaining remaining_human
now_ts=$(date +%s)
remaining=$(( RESET_TIMESTAMP - now_ts ))
(( remaining < 0 )) && remaining=0
remaining_human=$(format_duration "$remaining")
local rl="Resets in $remaining_human"
s=" $rl"
boxrow "$s" " ${C_CYAN}${rl}${C_RESET}" "$W"
fi
if [[ "$AUTO_RESUME" == "true" ]]; then
local at="Action: Auto-resume ($RESUME_MODE)"
s=" $at"
boxrow "$s" " ${C_GREEN}${at}${C_RESET}" "$W"
fi
else
local s=" Status: ALL CLEAR"
boxrow "$s" " Status: ${C_GREEN}ALL CLEAR${C_RESET}" "$W"
fi
}
# ============================================
# Countdown Timer
# ============================================
countdown_loop() {
local target_ts="$1"
local last_refresh=0
# Hide cursor during countdown
printf "\033[?25l"
while true; do
local now_ts
now_ts=$(date +%s)
local remaining=$(( target_ts - now_ts ))
if (( remaining <= 0 )); then
break
fi
# Periodic API refresh in detailed mode
if [[ "$MODE" == "detailed" && -n "$ORG_ID" ]]; then
local since_refresh=$(( now_ts - last_refresh ))
if (( since_refresh >= REFRESH_INTERVAL )); then
check_detailed 2>/dev/null || true
last_refresh=$now_ts
if [[ -n "$RESET_TIMESTAMP" ]]; then
target_ts="$RESET_TIMESTAMP"
remaining=$(( target_ts - now_ts ))
fi
if [[ "$LIMIT_DETECTED" != "true" ]]; then
break
fi
fi
fi
# Render countdown
local dur
dur=$(format_duration "$remaining")
printf "\r %b⏱ Countdown: %b%s%b " "$C_DIM" "$C_CYAN" "$dur" "$C_RESET"
sleep 1
done
# Show cursor
printf "\033[?25h"
echo ""
}
# ============================================
# Auto-Resume
# ============================================
resume_claude() {
info "Reset time reached. Waiting 10s buffer..."
sleep 10
# macOS desktop notification
if [[ "$NOTIFY" == "true" ]] && command -v osascript &>/dev/null; then
osascript -e 'display notification "Rate limit lifted. Resuming Claude Code..." with title "MyCC" sound name "Glass"' 2>/dev/null || true
fi
local cmd_display
if [[ "$RESUME_MODE" == "continue" ]]; then
cmd_display="claude -c --dangerously-skip-permissions -p \"$RESUME_PROMPT\""
info "Resuming: $cmd_display"
claude -c --dangerously-skip-permissions -p "$RESUME_PROMPT"
else
cmd_display="claude --dangerously-skip-permissions -p \"$RESUME_PROMPT\""
info "Resuming: $cmd_display"
claude --dangerously-skip-permissions -p "$RESUME_PROMPT"
fi
}
# ============================================
# Setup Wizard
# ============================================
setup_wizard() {
echo -e "${C_BOLD}MyCC Setup${C_RESET}"
echo "====================="
echo ""
echo "Detailed mode reads usage data from a local cache file."
echo "To get the data, run this in your browser console at claude.ai:"
echo ""
# Ask for orgId
local oid
read -rp "Organization ID (from browser cookies 'lastActiveOrg', or press Enter to skip): " oid
ORG_ID="${oid:-${ORG_ID:-}}"
if [[ -n "$ORG_ID" ]]; then
echo ""
echo -e "${C_BOLD}Run this in your browser console (F12 > Console) at claude.ai:${C_RESET}"
echo ""
echo " fetch('/api/organizations/${ORG_ID}/usage').then(r=>r.json()).then(d=>{var a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(d)]));a.download='mycc-usage.json';a.click()})"
echo ""
echo "This downloads mycc-usage.json. MyCC will auto-import it."
echo ""
fi
local rm
read -rp "Default resume mode [continue/new] (default: continue): " rm
RESUME_MODE="${rm:-continue}"
local rp
read -rp "Default resume prompt (default: continue): " rp
RESUME_PROMPT="${rp:-continue}"
local ri
read -rp "Refresh interval in seconds for compact mode (default: 120): " ri
REFRESH_INTERVAL="${ri:-120}"
# Write config
cat > "$CONF_FILE" <<CONFEOF
# mycc configuration
# Generated: $(date -u +"%Y-%m-%dT%H:%M:%SZ")
ORG_ID=${ORG_ID}
RESUME_MODE=${RESUME_MODE}
RESUME_PROMPT=${RESUME_PROMPT}
REFRESH_INTERVAL=${REFRESH_INTERVAL}
NOTIFY=true
CONFEOF
chmod 600 "$CONF_FILE"
echo ""
info "Config saved to $CONF_FILE"
echo ""
if [[ -n "$ORG_ID" ]]; then
echo "Next: download usage data from browser, then run: mycc -d --check"
else
echo "Test with: mycc --check"
fi
}
show_bookmarklet() {
if [[ -z "$ORG_ID" ]]; then
die "No ORG_ID configured. Run 'mycc --setup' first."
fi
echo ""
echo -e "${C_BOLD}MyCC Bookmarklet${C_RESET}"
echo "================"
echo ""
echo "Create a bookmark in your browser with this URL:"
echo ""
echo " javascript:void(fetch('/api/organizations/${ORG_ID}/usage').then(r=>r.json()).then(d=>{var a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(d)]));a.download='mycc-usage.json';a.click()}))"
echo ""
echo "Click it on any claude.ai page to download fresh usage data."
echo "MyCC will auto-import from ~/Downloads/mycc-usage.json."
echo ""
echo "Or run in browser console (F12):"
echo ""
echo " fetch('/api/organizations/${ORG_ID}/usage').then(r=>r.json()).then(d=>{var a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(d)]));a.download='mycc-usage.json';a.click()})"
echo ""
}
# ============================================
# JSON Output
# ============================================
output_json() {
if [[ "$MODE" == "detailed" ]]; then
jq -n \
--arg status "$([ "$LIMIT_DETECTED" == "true" ] && echo "limited" || echo "ok")" \
--arg limit_name "${LIMIT_NAME:-}" \
--argjson five_hour "${FIVE_HOUR_PCT:-0}" \
--arg five_hour_resets "${FIVE_HOUR_RESETS:-}" \
--argjson seven_day "${SEVEN_DAY_PCT:-0}" \
--arg seven_day_resets "${SEVEN_DAY_RESETS:-}" \
--argjson opus "${OPUS_PCT:-0}" \
--arg opus_resets "${OPUS_RESETS:-}" \
--argjson sonnet "${SONNET_PCT:-0}" \
--arg sonnet_resets "${SONNET_RESETS:-}" \
'{
status: $status,
limit_name: $limit_name,
five_hour: { pct: $five_hour, resets_at: $five_hour_resets },
seven_day: { pct: $seven_day, resets_at: $seven_day_resets },
opus: { pct: $opus, resets_at: $opus_resets },
sonnet: { pct: $sonnet, resets_at: $sonnet_resets }
}'
else
local resets_iso=""
if [[ -n "${RESET_TIMESTAMP:-}" ]]; then
if $IS_GNU_DATE; then
resets_iso=$(date -d "@$RESET_TIMESTAMP" -u +"%Y-%m-%dT%H:%M:%SZ")
else
resets_iso=$(date -r "$RESET_TIMESTAMP" -u +"%Y-%m-%dT%H:%M:%SZ")
fi
fi
jq -n \
--arg status "$([ "$LIMIT_DETECTED" == "true" ] && echo "limited" || echo "ok")" \
--arg limit_name "${LIMIT_NAME:-}" \
--arg resets_at "$resets_iso" \
'{ status: $status, limit_name: $limit_name, resets_at: $resets_at }'
fi
}
# ============================================
# Test Mode
# ============================================
run_test_mode() {
local wait_secs="$1"
LIMIT_DETECTED=true
LIMIT_NAME="test"
RESET_TIMESTAMP=$(( $(date +%s) + wait_secs ))
if [[ "$MODE" == "detailed" ]]; then
FIVE_HOUR_PCT=100
if $IS_GNU_DATE; then
FIVE_HOUR_RESETS=$(date -u -d "@$RESET_TIMESTAMP" +"%Y-%m-%dT%H:%M:%SZ")
else
FIVE_HOUR_RESETS=$(date -u -r "$RESET_TIMESTAMP" +"%Y-%m-%dT%H:%M:%SZ")
fi
SEVEN_DAY_PCT=45
SEVEN_DAY_RESETS=""
OPUS_PCT=72
OPUS_RESETS=""
SONNET_PCT=18
SONNET_RESETS=""
fi
warn "TEST MODE: Simulating rate limit (${wait_secs}s wait)"
}
# ============================================
# Compact Mode (single-line status bar)
# ============================================
render_compact() {
local now_ts
now_ts=$(date +%s)
local line=""
if [[ "$MODE" == "detailed" && -n "${FIVE_HOUR_PCT:-}" ]]; then
# Detailed compact: show all dimensions inline
local mini_bar
mini_bar() {
local pct="$1" name="$2" w=8
(( pct > 100 )) && pct=100
local filled=$(( pct * w / 100 ))
local empty=$(( w - filled ))
local bar=""
local i
for (( i=0; i<filled; i++ )); do bar+="█"; done
for (( i=0; i<empty; i++ )); do bar+="░"; done
local color
color=$(color_for_pct "$pct")
printf "%s %b%s%b %d%%" "$name" "$color" "$bar" "$C_RESET" "$pct"
}
line+=" $(mini_bar "${FIVE_HOUR_PCT:-0}" "5h")"
[[ -n "${SEVEN_DAY_PCT:-}" ]] && line+=" $(mini_bar "${SEVEN_DAY_PCT}" "7d")"
[[ -n "${OPUS_PCT:-}" ]] && line+=" $(mini_bar "${OPUS_PCT}" "Op")"
[[ -n "${SONNET_PCT:-}" ]] && line+=" $(mini_bar "${SONNET_PCT}" "So")"
fi
# Status + countdown
if [[ "$LIMIT_DETECTED" == "true" && -n "$RESET_TIMESTAMP" ]]; then
local remaining=$(( RESET_TIMESTAMP - now_ts ))
(( remaining < 0 )) && remaining=0
local dur
dur=$(format_duration "$remaining")
if [[ -n "$line" ]]; then
line+=" ${C_RED}LIMITED${C_RESET} ${C_CYAN}${dur}${C_RESET}"
else
line+=" ${C_RED}RATE LIMITED${C_RESET} resets in ${C_CYAN}${dur}${C_RESET}"
fi
else
if [[ -n "$line" ]]; then
line+=" ${C_GREEN}OK${C_RESET}"
else
line+=" ${C_GREEN}ALL CLEAR${C_RESET}"
fi
fi
local ts
ts=$(date "+%H:%M:%S")
printf "\r${C_DIM}[%s]${C_RESET}%s " "$ts" "$line"
}
compact_loop() {
local last_check=0
local check_interval="${REFRESH_INTERVAL}"
# In basic mode, check less frequently (CLI call is expensive)
[[ "$MODE" == "basic" ]] && check_interval=300
printf "\033[?25l" # Hide cursor
while true; do
local now_ts
now_ts=$(date +%s)
local since_check=$(( now_ts - last_check ))
if (( since_check >= check_interval )) || (( last_check == 0 )); then
if [[ -n "$TEST_MODE_SECS" ]]; then
run_test_mode "$TEST_MODE_SECS"
TEST_MODE_SECS=""
last_check=$now_ts
elif [[ "$MODE" == "detailed" && -n "$ORG_ID" ]]; then
check_detailed 2>/dev/null || true
last_check=$now_ts
elif [[ "$MODE" == "basic" ]]; then
check_basic 2>/dev/null || true
last_check=$now_ts
fi
fi
render_compact
sleep 1
done
}
# ============================================
# tmux Launch
# ============================================
launch_tmux() {
command -v tmux &>/dev/null || die "--launch requires tmux. Install: brew install tmux"
[[ -t 0 ]] || die "--launch requires an interactive terminal (TTY). Run this command directly in your terminal, not from a script or pipe."
local session_name="mycc"
# Always pass -d if user requested it; the compact process loads its own config
local sentinel_cmd="$0 --compact"
[[ "$LAUNCH_DETAILED" == "true" ]] && sentinel_cmd="$0 -d --compact"
# Kill existing session if present
tmux kill-session -t "$session_name" 2>/dev/null || true
# Build claude command
local claude_cmd="claude"
if [[ -n "$LAUNCH_ARGS" ]]; then
claude_cmd="claude $LAUNCH_ARGS"
fi
# Create session with Claude Code on top
tmux new-session -d -s "$session_name" -x "$(tput cols)" -y "$(tput lines)" "$claude_cmd"
# Split: bottom pane (3 lines) for sentinel
tmux split-window -v -t "$session_name" -l 2 "$sentinel_cmd"
# Focus on Claude Code pane (top)
tmux select-pane -t "$session_name":0.0
# Attach
tmux attach-session -t "$session_name"
}
# ============================================
# Signal Handling
# ============================================
cleanup() {
printf "\033[?25h" 2>/dev/null # Show cursor
echo ""