claude-limit-watch 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +17 -0
- data/LICENSE +21 -0
- data/README.md +362 -0
- data/docs/images/panel.png +0 -0
- data/exe/claude-limit-watch +6 -0
- data/lib/claude_limit_watch/cli.rb +151 -0
- data/lib/claude_limit_watch/format.rb +58 -0
- data/lib/claude_limit_watch/history.rb +101 -0
- data/lib/claude_limit_watch/lines_view.rb +119 -0
- data/lib/claude_limit_watch/panel.rb +257 -0
- data/lib/claude_limit_watch/projection.rb +98 -0
- data/lib/claude_limit_watch/recorder.rb +223 -0
- data/lib/claude_limit_watch/snapshot.rb +33 -0
- data/lib/claude_limit_watch/term.rb +59 -0
- data/lib/claude_limit_watch/usage_api.rb +61 -0
- data/lib/claude_limit_watch/version.rb +6 -0
- data/lib/claude_limit_watch.rb +61 -0
- metadata +62 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'time'
|
|
5
|
+
|
|
6
|
+
module ClaudeLimitWatch
|
|
7
|
+
# The history file: one reading (or failed check) per line, as JSON. The
|
|
8
|
+
# recorder appends to it; the viewer only reads it.
|
|
9
|
+
module History
|
|
10
|
+
extend self
|
|
11
|
+
|
|
12
|
+
KEEP_DAYS = 7 # the recorder drops readings older than this
|
|
13
|
+
|
|
14
|
+
# The history file's absolute path: history.jsonl in the XDG state
|
|
15
|
+
# directory, unless set to another file (--file). Made absolute (and ~
|
|
16
|
+
# expanded) once, here, so the viewer, the recorder it starts and the stop
|
|
17
|
+
# hint all name the same file. Raises ArgumentError for a path that can't
|
|
18
|
+
# be expanded, such as ~nosuchuser/x.
|
|
19
|
+
def file
|
|
20
|
+
@file ||= File.expand_path(default_file)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def file=(path)
|
|
24
|
+
@file = path && File.expand_path(path)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# The history file without --file, not yet expanded. An empty
|
|
28
|
+
# XDG_STATE_HOME counts as unset, as the XDG spec says.
|
|
29
|
+
def default_file
|
|
30
|
+
state = ENV['XDG_STATE_HOME']
|
|
31
|
+
state = File.join(Dir.home, '.local', 'state') if state.nil? || state.empty?
|
|
32
|
+
File.join(state, 'claude-limit-watch', 'history.jsonl')
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Held by the running recorder; holds its pid.
|
|
36
|
+
def lock_file
|
|
37
|
+
"#{file}.lock"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# The background recorder's output.
|
|
41
|
+
def log_file
|
|
42
|
+
File.join(File.dirname(file), 'recorder.log')
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def append(rec)
|
|
46
|
+
File.open(file, 'a') { |f| f.puts(JSON.generate(rec)) }
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Drop readings older than KEEP_DAYS. Writes a new file and renames it over
|
|
50
|
+
# the old one, so a reader never sees a half-written file.
|
|
51
|
+
def prune
|
|
52
|
+
return unless File.exist?(file)
|
|
53
|
+
|
|
54
|
+
cutoff = Time.now - (KEEP_DAYS * 86_400)
|
|
55
|
+
kept = File.readlines(file).select do |line|
|
|
56
|
+
Time.parse(JSON.parse(line)['t']) >= cutoff
|
|
57
|
+
rescue
|
|
58
|
+
false
|
|
59
|
+
end
|
|
60
|
+
tmp = "#{file}.tmp"
|
|
61
|
+
File.write(tmp, kept.join)
|
|
62
|
+
File.rename(tmp, file)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Readings as hashes: { t:, interval:, util:, resets: } or { t:, interval:, error: }.
|
|
66
|
+
# Unparseable lines (e.g. one being written right now) are skipped.
|
|
67
|
+
def read
|
|
68
|
+
return [] unless File.exist?(file)
|
|
69
|
+
|
|
70
|
+
File.readlines(file).map do |line|
|
|
71
|
+
h = JSON.parse(line)
|
|
72
|
+
rec = { t: Time.parse(h['t']), interval: h['interval_min'].to_f }
|
|
73
|
+
if h['error']
|
|
74
|
+
rec.merge(error: h['error'])
|
|
75
|
+
else
|
|
76
|
+
rec.merge(util: h['util'].to_f, resets: h['resets_at'] && Time.parse(h['resets_at']))
|
|
77
|
+
end
|
|
78
|
+
rescue
|
|
79
|
+
nil
|
|
80
|
+
end.compact
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Reads the history file only when it has changed.
|
|
84
|
+
class Cache
|
|
85
|
+
def initialize
|
|
86
|
+
@sig = nil
|
|
87
|
+
@records = []
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def records
|
|
91
|
+
file = History.file
|
|
92
|
+
sig = File.exist?(file) ? [File.mtime(file), File.size(file)] : nil
|
|
93
|
+
if sig != @sig
|
|
94
|
+
@records = History.read
|
|
95
|
+
@sig = sig
|
|
96
|
+
end
|
|
97
|
+
@records
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
end
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ClaudeLimitWatch
|
|
4
|
+
# The viewer's one-line-per-reading output (--lines, or when output isn't
|
|
5
|
+
# a terminal).
|
|
6
|
+
module LinesView
|
|
7
|
+
include Format
|
|
8
|
+
include Term
|
|
9
|
+
extend self
|
|
10
|
+
|
|
11
|
+
RATE_COL = 23 # width of the burn-rate column
|
|
12
|
+
|
|
13
|
+
def header(rate_window)
|
|
14
|
+
['Time ', 'Level ', 'Window ', 'Ends ', 'Used', "#{num(rate_window)}m Burn Rate".ljust(RATE_COL),
|
|
15
|
+
' Pace', 'Outlook'].join(' | ')
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# One reading's line, from its projection (Projection.project).
|
|
19
|
+
def format_line(now, p)
|
|
20
|
+
rate_txt =
|
|
21
|
+
if p[:recent_rate]
|
|
22
|
+
"#{format('%4.1f', p[:recent_rate] * 60)}%/h (avg #{format('%.1f', p[:avg_rate] * 60)})"
|
|
23
|
+
elsif p[:avg_rate]
|
|
24
|
+
"#{format('%4.1f', p[:avg_rate] * 60)}%/h (avg so far)"
|
|
25
|
+
else
|
|
26
|
+
'rate n/a'
|
|
27
|
+
end
|
|
28
|
+
outlook =
|
|
29
|
+
if p[:util] >= 100
|
|
30
|
+
"AT LIMIT, resets in #{hm(p[:reset_min])}"
|
|
31
|
+
elsif p[:eta_min] && p[:left_at_reset].nil?
|
|
32
|
+
"LIMIT at #{clock(now + (p[:eta_min] * 60))} (in #{hm(p[:eta_min])}), " \
|
|
33
|
+
"#{hm(p[:reset_min] - p[:eta_min])} before reset"
|
|
34
|
+
elsif p[:left_at_reset]
|
|
35
|
+
"~#{p[:left_at_reset].round}% left at reset"
|
|
36
|
+
else
|
|
37
|
+
'not rising'
|
|
38
|
+
end
|
|
39
|
+
label = { ok: 'OK ', projected: 'WARN ', urgent: 'URGENT' }[p[:level]]
|
|
40
|
+
pace = p[:pace]&.finite? ? format('%.1fx', p[:pace]) : 'n/a'
|
|
41
|
+
[clock(now), label, "#{hm(p[:elapsed_min])} of 5:00", clock(p[:resets]),
|
|
42
|
+
format('%3d%%', p[:util].round), rate_txt.ljust(RATE_COL), pace.rjust(5), outlook].join(' | ')
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# The warning that readings have stopped coming in. pid: the running
|
|
46
|
+
# recorder's, or nil; record: as for run.
|
|
47
|
+
def stale_line(now, last_t, pid, record:)
|
|
48
|
+
hint = Recorder.stale_hint(pid, record: record)
|
|
49
|
+
paint("#{clock(now)} | no new readings for #{dur_m(now - last_t)}.#{" #{hint}" if hint}", WARN)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# The lines before the readings. pid: the running recorder's, or nil;
|
|
53
|
+
# recorder_message: what the viewer did about the recorder.
|
|
54
|
+
def intro(rate_window, pid, recorder_message)
|
|
55
|
+
keeps = pid ? ' (the recorder keeps running)' : ''
|
|
56
|
+
[paint(recorder_message, GRAY),
|
|
57
|
+
paint("Claude 5-hour limit, from #{History.file}; burn rate over the last " \
|
|
58
|
+
"#{num(rate_window)}m.#{zone_note} Ctrl-C to quit#{keeps}.", GRAY),
|
|
59
|
+
paint(VERSION_LINE, GRAY),
|
|
60
|
+
paint(header(rate_window), GRAY)]
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Prints a line per reading as they come in, until Ctrl-C. pid and
|
|
64
|
+
# recorder_message: as for intro. record: whether this viewer started the
|
|
65
|
+
# recorder (false with --no-record).
|
|
66
|
+
def run(rate_window, pid, recorder_message, record: true)
|
|
67
|
+
trap('INT') do
|
|
68
|
+
puts
|
|
69
|
+
exit 0
|
|
70
|
+
end
|
|
71
|
+
puts intro(rate_window, pid, recorder_message)
|
|
72
|
+
|
|
73
|
+
cache = History::Cache.new
|
|
74
|
+
shown_t = nil # time of the last reading printed
|
|
75
|
+
window = nil
|
|
76
|
+
stale_noted = false
|
|
77
|
+
loop do
|
|
78
|
+
records = cache.records
|
|
79
|
+
if shown_t.nil?
|
|
80
|
+
# Start with the readings in the current window (or nothing before now).
|
|
81
|
+
latest = records.reject { |r| r[:error] }.last
|
|
82
|
+
first = latest && latest[:resets] &&
|
|
83
|
+
records.find { |r| r[:resets] && (r[:resets] - latest[:resets]).abs < 60 }
|
|
84
|
+
shown_t = if first
|
|
85
|
+
first[:t] - 1
|
|
86
|
+
else
|
|
87
|
+
(records.last ? records.last[:t] : Time.at(0))
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
records.each_with_index do |rec, i|
|
|
91
|
+
next unless rec[:t] > shown_t
|
|
92
|
+
|
|
93
|
+
stamp = clock(rec[:t])
|
|
94
|
+
if rec[:error]
|
|
95
|
+
puts paint("#{stamp} | no reading: #{rec[:error]}", GRAY)
|
|
96
|
+
elsif rec[:resets].nil? || rec[:resets] <= rec[:t]
|
|
97
|
+
puts paint("#{stamp} | no active 5-hour window (#{rec[:util].round}% used)", GRAY)
|
|
98
|
+
else
|
|
99
|
+
unless window && (rec[:resets] - window).abs < 60
|
|
100
|
+
puts paint("-- 5-hour window ends at #{clock(rec[:resets])} --", GRAY) if window
|
|
101
|
+
window = rec[:resets]
|
|
102
|
+
end
|
|
103
|
+
st = Snapshot.build(records[0..i], rec[:t], rate_window: rate_window)
|
|
104
|
+
puts paint(format_line(rec[:t], st[:proj]), COLORS[st[:proj][:level]]) if st[:proj]
|
|
105
|
+
end
|
|
106
|
+
shown_t = rec[:t]
|
|
107
|
+
stale_noted = false
|
|
108
|
+
end
|
|
109
|
+
st = Snapshot.build(records, Time.now, rate_window: rate_window)
|
|
110
|
+
if st[:stale] && !stale_noted
|
|
111
|
+
puts stale_line(Time.now, st[:last_t], Recorder.pid, record: record)
|
|
112
|
+
stale_noted = true
|
|
113
|
+
end
|
|
114
|
+
$stdout.flush
|
|
115
|
+
sleep 2
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ClaudeLimitWatch
|
|
4
|
+
# The viewer's full-screen panel, redrawn in place each second.
|
|
5
|
+
module Panel
|
|
6
|
+
include Format
|
|
7
|
+
include Term
|
|
8
|
+
extend self
|
|
9
|
+
|
|
10
|
+
# Projection bar fills: distinct shapes, so the parts can be told apart
|
|
11
|
+
# without color too (NO_COLOR, piped --once).
|
|
12
|
+
SO_FAR_CHAR = '█'
|
|
13
|
+
LEFT_CHAR = '▒'
|
|
14
|
+
LOCKED_CHAR = 'X'
|
|
15
|
+
LOCKED_COLOR = [1, 38, 5, 196, 48, 5, 52].freeze # bold red X on a dark red background
|
|
16
|
+
ACCENT_COLOR = [38, 5, 141].freeze # lavender (256-color 141): the heading and the Time bar
|
|
17
|
+
|
|
18
|
+
# The panel's lines for a snapshot (Snapshot.build, plus :recorder_pid).
|
|
19
|
+
# once: printing a single copy (--once), so use a fixed width, don't
|
|
20
|
+
# truncate, and leave out the quit instruction.
|
|
21
|
+
# show_banner: false uses the one-line title even when the banner fits the
|
|
22
|
+
# width; the panel redraws that way when the terminal is too short for it.
|
|
23
|
+
# record: whether this viewer starts the recorder (false with --no-record).
|
|
24
|
+
def lines(st, now, once: false, show_banner: true, record: true)
|
|
25
|
+
w = once ? 100 : term_width
|
|
26
|
+
bar_w = (w - 47).clamp(10, 50) # leaves room for the projection rows' text
|
|
27
|
+
p = st[:proj]
|
|
28
|
+
now_text = "now #{clock(now)}" # on the Time bar's second line, and at the bottom
|
|
29
|
+
info =
|
|
30
|
+
if st[:last_t]
|
|
31
|
+
"last reading #{clock(st[:last_t])} (#{dur_m(now - st[:last_t])} ago)"
|
|
32
|
+
else
|
|
33
|
+
'no readings yet'
|
|
34
|
+
end
|
|
35
|
+
info = "times in UTC · #{info}" if Format.utc # covers every time on the panel
|
|
36
|
+
out = []
|
|
37
|
+
blank = -> { out << '' unless out.last.empty? } # a blank line, never two
|
|
38
|
+
banner_drawn = show_banner && w >= banner_rows.map(&:size).max + 4
|
|
39
|
+
legend_drawn = false
|
|
40
|
+
if banner_drawn
|
|
41
|
+
out.concat(banner.map { |row| " #{row}" })
|
|
42
|
+
out << ''
|
|
43
|
+
out << " #{paint("Claude's 5-hour usage limit · #{info}", GRAY)}"
|
|
44
|
+
else
|
|
45
|
+
out << "#{paint(' Claude 5-hour limit', 1)} #{paint(info, GRAY)}"
|
|
46
|
+
end
|
|
47
|
+
out << ''
|
|
48
|
+
status = headline(st, now)
|
|
49
|
+
out.push(" #{status[0]} #{status[1]}", '') if status
|
|
50
|
+
if p
|
|
51
|
+
elapsed = WINDOW_MIN - ((p[:resets] - now) / 60.0)
|
|
52
|
+
window_start = p[:resets] - (WINDOW_MIN * 60)
|
|
53
|
+
used_color = p[:util] >= 100 ? [COLORS[:urgent]] : [] # normal text color unless at the limit
|
|
54
|
+
out << " Used #{bar(p[:util] / 100.0, bar_w, *used_color)} #{format('%3d%%', p[:util].round)}"
|
|
55
|
+
out << " Time #{bar(elapsed / WINDOW_MIN, bar_w, *ACCENT_COLOR)} #{dur_m(elapsed * 60)} of 5h"
|
|
56
|
+
# The window's start and end times, then the current time, under the
|
|
57
|
+
# elapsed time above it.
|
|
58
|
+
times = "#{clock(window_start).ljust(bar_w - 5)}#{clock(p[:resets])}"
|
|
59
|
+
out << paint(" #{times} #{now_text}", GRAY)
|
|
60
|
+
if st[:table] && p[:util] < 100
|
|
61
|
+
out << ''
|
|
62
|
+
since = clock(window_start)
|
|
63
|
+
out << paint(" If usage continues at the rate of the last ... (all: since #{since}):", GRAY)
|
|
64
|
+
out << ''
|
|
65
|
+
out.concat(projection_bar_lines(st[:table], p, bar_w, now))
|
|
66
|
+
out << ''
|
|
67
|
+
out << legend
|
|
68
|
+
legend_drawn = true
|
|
69
|
+
elsif p[:util] < 100
|
|
70
|
+
out << ''
|
|
71
|
+
start_at = clock(window_start + (Projection::MIN_ELAPSED_MIN * 60))
|
|
72
|
+
out << paint(" Projections start #{Projection::MIN_ELAPSED_MIN}m into the window " \
|
|
73
|
+
"(at #{start_at}). Before then, there is not enough data.", GRAY)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
if st[:error]
|
|
77
|
+
blank.call
|
|
78
|
+
out << paint(" Last check failed at #{clock(st[:error_at])}: #{st[:error]}", WARN)
|
|
79
|
+
end
|
|
80
|
+
if st[:stale] || (st[:no_data] && st[:recorder_pid].nil?)
|
|
81
|
+
gap = st[:last_t] && "No new readings for #{dur_m(now - st[:last_t])}."
|
|
82
|
+
hint = Recorder.stale_hint(st[:recorder_pid], record: record)
|
|
83
|
+
warning = [gap, hint].compact.join(' ')
|
|
84
|
+
unless warning.empty?
|
|
85
|
+
blank.call
|
|
86
|
+
out << paint(" #{warning}", WARN)
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
recorder =
|
|
90
|
+
if st[:recorder_pid]
|
|
91
|
+
"Recorder running (pid #{st[:recorder_pid]}), writing to #{home_relative(History.file)}"
|
|
92
|
+
else
|
|
93
|
+
"Recorder not running (history file: #{home_relative(History.file)})"
|
|
94
|
+
end
|
|
95
|
+
# The rule ends where the legend does (or at the edge of a narrower
|
|
96
|
+
# terminal). A blank line goes above it only when no legend was drawn
|
|
97
|
+
# and the last line isn't already blank. With a legend, the rule sits
|
|
98
|
+
# right under it, or under any warning after it, with no blank line:
|
|
99
|
+
# one there would push the worst case past 24 rows.
|
|
100
|
+
blank.call unless legend_drawn
|
|
101
|
+
rule_w = [[legend_width, w].min - 2, 0].max
|
|
102
|
+
out << paint(" #{'─' * rule_w}", GRAY)
|
|
103
|
+
# How to quit and stop the recorder (not with --once), then the current
|
|
104
|
+
# time, ending where the rule does.
|
|
105
|
+
footer =
|
|
106
|
+
if once
|
|
107
|
+
''
|
|
108
|
+
elsif st[:recorder_pid]
|
|
109
|
+
"q to quit · stop the recorder with: #{Recorder.stop_command(st[:recorder_pid], brief: true)}"
|
|
110
|
+
else
|
|
111
|
+
'q to quit'
|
|
112
|
+
end
|
|
113
|
+
out << paint(" #{footer}#{' ' * [rule_w - footer.size - now_text.size, 2].max}#{now_text}", GRAY)
|
|
114
|
+
out << paint(" #{VERSION_LINE}", GRAY)
|
|
115
|
+
out << paint(" #{recorder}", GRAY)
|
|
116
|
+
return out if once
|
|
117
|
+
|
|
118
|
+
# In a terminal too short for the panel, the one-line title replaces the
|
|
119
|
+
# banner (4 rows fewer) rather than letting the top scroll off.
|
|
120
|
+
h = term_height
|
|
121
|
+
return lines(st, now, show_banner: false, record: record) if banner_drawn && h && out.size > h
|
|
122
|
+
|
|
123
|
+
out.map { |l| fit(l, w) }
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# One bar per look-back window, on the same time scale as the Time bar and
|
|
127
|
+
# aligned under it: the time so far, then the time you could keep working
|
|
128
|
+
# at that rate, then (red) the time you'd be locked out after hitting the
|
|
129
|
+
# limit, at least one column whenever there's any.
|
|
130
|
+
def projection_bar_lines(rows, p, bar_w, now)
|
|
131
|
+
start = p[:resets] - (WINDOW_MIN * 60)
|
|
132
|
+
# Same rounding as bar(), so the time-so-far part lines up with the Time bar.
|
|
133
|
+
cells = ->(t) { (((t - start) / (WINDOW_MIN * 60)) * bar_w).round.clamp(0, bar_w) }
|
|
134
|
+
so_far = cells.call(now)
|
|
135
|
+
rows.map do |r|
|
|
136
|
+
label = (r[:label] == 'window' ? 'all' : r[:label]).ljust(6)
|
|
137
|
+
next " #{label} #{paint("not enough history yet (have #{dur_m(r[:have] * 60)})", GRAY)}" if r[:na]
|
|
138
|
+
|
|
139
|
+
# Time left is always green; a rate that runs out is followed by red,
|
|
140
|
+
# the locked-out time, and its text is red too.
|
|
141
|
+
runs_out = r[:eta_at] && r[:eta_at] < p[:resets]
|
|
142
|
+
if runs_out
|
|
143
|
+
hit = cells.call(r[:eta_at]).clamp(so_far, bar_w - 1) # leave at least one red cell
|
|
144
|
+
locked = p[:resets] - [r[:eta_at], now].max
|
|
145
|
+
bar = paint(SO_FAR_CHAR * so_far, *ACCENT_COLOR) + paint(LEFT_CHAR * (hit - so_far), COLORS[:ok]) +
|
|
146
|
+
paint(LOCKED_CHAR * (bar_w - hit), *LOCKED_COLOR)
|
|
147
|
+
text = "limit at #{clock(r[:eta_at])} · #{dur_m(locked)} locked out"
|
|
148
|
+
else
|
|
149
|
+
bar = paint(SO_FAR_CHAR * so_far, *ACCENT_COLOR) + paint(LEFT_CHAR * (bar_w - so_far), COLORS[:ok])
|
|
150
|
+
text = "limit not reached · #{r[:end_pct].round}% at the end"
|
|
151
|
+
end
|
|
152
|
+
" #{label} #{bar}#{paint('│', GRAY)} #{paint(text, COLORS[runs_out ? :urgent : :ok])}"
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# Prints the panel once, without the full-screen mode. Never starts the
|
|
157
|
+
# recorder.
|
|
158
|
+
def run_once(rate_window)
|
|
159
|
+
now = Time.now
|
|
160
|
+
st = Snapshot.build(History.read, now, rate_window: rate_window).merge(recorder_pid: Recorder.pid)
|
|
161
|
+
puts lines(st, now, once: true, record: false) # --once never starts one
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Shows the panel full-screen, redrawing it each second, until q or Ctrl-C.
|
|
165
|
+
# CLI starts the recorder first, unless record is false (--no-record).
|
|
166
|
+
def run(rate_window, record: true)
|
|
167
|
+
# Read keys as they're pressed (no Enter, no echo), so q quits. Ctrl-C
|
|
168
|
+
# still works. The terminal settings are restored on exit.
|
|
169
|
+
keys = $stdin.tty?
|
|
170
|
+
saved_tty = keys ? `stty -g`.chomp : nil
|
|
171
|
+
system('stty', '-icanon', '-echo', 'min', '1') if keys
|
|
172
|
+
$stdout.write("\e[?1049h\e[?25l") # alternate screen, hide cursor
|
|
173
|
+
at_exit do
|
|
174
|
+
system('stty', saved_tty) if saved_tty && !saved_tty.empty?
|
|
175
|
+
$stdout.write("\e[?25h\e[?1049l")
|
|
176
|
+
# Leave the stop instruction in the scrollback.
|
|
177
|
+
pid = Recorder.pid
|
|
178
|
+
puts pid ? Recorder.stop_hint(pid) : 'The recorder is not running.'
|
|
179
|
+
puts VERSION_LINE
|
|
180
|
+
$stdout.flush
|
|
181
|
+
end
|
|
182
|
+
%w[INT TERM HUP].each { |sig| trap(sig) { exit 0 } }
|
|
183
|
+
|
|
184
|
+
cache = History::Cache.new
|
|
185
|
+
pid = nil
|
|
186
|
+
ticks = 0
|
|
187
|
+
loop do
|
|
188
|
+
pid = Recorder.pid if (ticks % 5).zero? # check every 5 seconds
|
|
189
|
+
ticks += 1
|
|
190
|
+
now = Time.now
|
|
191
|
+
st = Snapshot.build(cache.records, now, rate_window: rate_window).merge(recorder_pid: pid)
|
|
192
|
+
render(lines(st, now, record: record))
|
|
193
|
+
if keys
|
|
194
|
+
# Wait up to a second for a key.
|
|
195
|
+
if IO.select([$stdin], nil, nil, 1) # rubocop:disable Lint/IncompatibleIoSelectWithFiberScheduler -- no fibers
|
|
196
|
+
key = $stdin.read_nonblock(1, exception: false)
|
|
197
|
+
exit 0 if key.is_a?(String) && key.casecmp?('q')
|
|
198
|
+
end
|
|
199
|
+
else
|
|
200
|
+
sleep 1
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
private def bar(fraction, width, *codes)
|
|
206
|
+
filled = (fraction.clamp(0.0, 1.0) * width).round
|
|
207
|
+
paint('█' * filled, *codes) + paint('░' * (width - filled), GRAY)
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# A status line for the states that aren't projections (no data, no active
|
|
211
|
+
# window, at the limit), or nil. Projections are shown per look-back window
|
|
212
|
+
# in the bars instead, so there's no single headline projection.
|
|
213
|
+
private def headline(st, now)
|
|
214
|
+
p = st[:proj]
|
|
215
|
+
return [paint(' NO DATA ', 1, 7, GRAY), "No readings yet in #{History.file}"] if st[:no_data]
|
|
216
|
+
if st[:no_window]
|
|
217
|
+
return [paint(' IDLE ', 1, 7, GRAY), "No active 5-hour window (#{st[:no_window].round}% used)"]
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
return [paint(' ? ', 1, 7, GRAY), 'No successful reading yet'] unless p
|
|
221
|
+
return nil if p[:util] < 100
|
|
222
|
+
|
|
223
|
+
[paint(' AT LIMIT ', 1, 7, COLORS[:urgent]),
|
|
224
|
+
paint("Resets at #{clock(p[:resets])} (in #{dur_m(p[:resets] - now)})", 1, COLORS[:urgent])]
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
private def banner_rows
|
|
228
|
+
inner = " ◆ #{'Claude Limit Watch'.upcase.chars.join(' ')} ◆ "
|
|
229
|
+
["╔#{'═' * inner.size}╗", "║#{inner}║", "╚#{'═' * inner.size}╝"]
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# The framed heading, in one color (plain when colors are off).
|
|
233
|
+
private def banner
|
|
234
|
+
banner_rows.map { |row| paint(row, 1, *ACCENT_COLOR) }
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
# The projection bars' key: each symbol drawn as it appears in the bars.
|
|
238
|
+
private def legend
|
|
239
|
+
" #{paint(SO_FAR_CHAR, *ACCENT_COLOR)}#{paint(' time so far · ', GRAY)}" \
|
|
240
|
+
"#{paint(LEFT_CHAR, COLORS[:ok])}#{paint(' time left at that rate · ', GRAY)}" \
|
|
241
|
+
"#{paint(LOCKED_CHAR, *LOCKED_COLOR)}#{paint(' locked out (limit reached) · │ window ends', GRAY)}"
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# The legend's visible width (it's the same with or without colors).
|
|
245
|
+
private def legend_width
|
|
246
|
+
@legend_width ||= legend.gsub(ANSI_RE, '').size
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
private def render(lines)
|
|
250
|
+
return if lines == @last_render
|
|
251
|
+
|
|
252
|
+
@last_render = lines
|
|
253
|
+
$stdout.write("\e[H" + lines.map { |l| "#{l}\e[K" }.join("\n") + "\e[J")
|
|
254
|
+
$stdout.flush
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
end
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ClaudeLimitWatch
|
|
4
|
+
# Burn rates, and where they lead: the numbers behind both views.
|
|
5
|
+
#
|
|
6
|
+
# `history` is the earlier readings in the 5-hour window, oldest first, as
|
|
7
|
+
# { t:, util: }; `util` is the latest reading's utilization (percent) and
|
|
8
|
+
# `now` its time; `resets` is when the window ends.
|
|
9
|
+
module Projection
|
|
10
|
+
include Format
|
|
11
|
+
extend self
|
|
12
|
+
|
|
13
|
+
URGENT_MIN = 20 # urgent when the limit is this close, whatever the pace
|
|
14
|
+
URGENT_PACE = 2.0 # urgent when burning this many times the sustainable rate
|
|
15
|
+
MIN_ELAPSED_MIN = 30 # no projections until this many minutes into the window
|
|
16
|
+
PROJECTION_WINDOWS = [10, 30, 60, 120].freeze # look-back windows shown on the panel
|
|
17
|
+
|
|
18
|
+
# Rate (points per minute) over about the last `window` minutes, and the time
|
|
19
|
+
# it actually covers, or nil when the history doesn't reach back far enough
|
|
20
|
+
# (to at least 3/4 of the window). Readings come at intervals, so this uses
|
|
21
|
+
# the reading closest to `window` minutes ago, allowing it to be up to 10%
|
|
22
|
+
# (at least a minute) older.
|
|
23
|
+
def rate_over(history, now, util, window)
|
|
24
|
+
oldest = now - ((window + [window * 0.1, 1].max) * 60)
|
|
25
|
+
first = history.select { |h| h[:t] >= oldest }.min_by { |h| (((now - h[:t]) / 60.0) - window).abs }
|
|
26
|
+
return nil unless first
|
|
27
|
+
|
|
28
|
+
span = (now - first[:t]) / 60.0
|
|
29
|
+
span >= window * 0.75 ? [(util - first[:util]) / span, span] : nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Pace, projected limit time and level for a given rate.
|
|
33
|
+
def assess(util, rate, reset_min)
|
|
34
|
+
return { level: :urgent } if util >= 100
|
|
35
|
+
return { level: :ok } unless rate && reset_min.positive?
|
|
36
|
+
|
|
37
|
+
remaining = 100.0 - util
|
|
38
|
+
a = { pace: remaining.positive? ? rate / (remaining / reset_min) : Float::INFINITY }
|
|
39
|
+
a[:eta_min] = remaining / rate if rate.positive?
|
|
40
|
+
hits_first = a[:eta_min] && a[:eta_min] < reset_min
|
|
41
|
+
a[:left_at_reset] = remaining - (rate * reset_min) unless hits_first
|
|
42
|
+
a[:level] =
|
|
43
|
+
if hits_first && (a[:eta_min] <= URGENT_MIN || a[:pace] >= URGENT_PACE) then :urgent
|
|
44
|
+
elsif hits_first then :projected
|
|
45
|
+
else :ok
|
|
46
|
+
end
|
|
47
|
+
a
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Projection from the readings in the current window. Uses the recent rate
|
|
51
|
+
# (the last `rate_window` minutes) when there's enough history, otherwise
|
|
52
|
+
# the average since the window started.
|
|
53
|
+
def project(history, now, util, resets, rate_window:)
|
|
54
|
+
reset_min = (resets - now) / 60.0
|
|
55
|
+
elapsed_min = WINDOW_MIN - reset_min
|
|
56
|
+
avg_rate = elapsed_min.positive? ? util / elapsed_min : nil
|
|
57
|
+
recent_rate, = rate_over(history, now, util, rate_window)
|
|
58
|
+
rate = recent_rate || avg_rate
|
|
59
|
+
{ util: util, resets: resets, reset_min: reset_min, elapsed_min: elapsed_min,
|
|
60
|
+
avg_rate: avg_rate, recent_rate: recent_rate, rate: rate }
|
|
61
|
+
.merge(assess(util, rate, reset_min))
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# One row per look-back window (PROJECTION_WINDOWS and `rate_window`), plus
|
|
65
|
+
# the whole 5-hour window so far, each with its rate, where it leads
|
|
66
|
+
# (assess) and the projected use at the window's end.
|
|
67
|
+
# Returns nil during the window's first MIN_ELAPSED_MIN minutes: windows often
|
|
68
|
+
# start with a burst (resumed sessions re-sending their whole conversation),
|
|
69
|
+
# and any projection from those minutes predicts a limit hit that isn't
|
|
70
|
+
# coming.
|
|
71
|
+
def projection_rows(history, now, util, resets, rate_window:)
|
|
72
|
+
reset_min = (resets - now) / 60.0
|
|
73
|
+
elapsed = WINDOW_MIN - reset_min
|
|
74
|
+
return nil if elapsed < MIN_ELAPSED_MIN
|
|
75
|
+
|
|
76
|
+
have = history.first ? (now - history.first[:t]) / 60.0 : 0
|
|
77
|
+
windows = (PROJECTION_WINDOWS + [rate_window]).map(&:to_f).uniq.sort
|
|
78
|
+
rows = windows.map do |w|
|
|
79
|
+
label = w >= 60 && (w % 60).zero? ? "#{(w / 60).to_i}h" : "#{num(w)}m"
|
|
80
|
+
rate, span = rate_over(history, now, util, w)
|
|
81
|
+
next { label: label, na: true, have: have } unless rate
|
|
82
|
+
|
|
83
|
+
# When the history doesn't reach back the whole window, label the row
|
|
84
|
+
# with what it actually covers (e.g. "1h50m" instead of "2h").
|
|
85
|
+
label = span_label(span) if span < w * 0.95
|
|
86
|
+
|
|
87
|
+
{ label: label, rate: rate }.merge(assess(util, rate, reset_min))
|
|
88
|
+
end
|
|
89
|
+
rows << { label: 'window', rate: util / elapsed }.merge(assess(util, util / elapsed, reset_min))
|
|
90
|
+
rows.each do |r|
|
|
91
|
+
next if r[:na]
|
|
92
|
+
|
|
93
|
+
r[:end_pct] = util + (r[:rate] * reset_min)
|
|
94
|
+
r[:eta_at] = now + (r[:eta_min] * 60) if r[:eta_min]
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|