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.
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'rbconfig'
5
+ require 'shellwords'
6
+ require 'time'
7
+
8
+ module ClaudeLimitWatch
9
+ # The recorder: checks the usage at intervals and appends each reading to
10
+ # the history file. Also finds, starts and stops a running recorder.
11
+ module Recorder
12
+ include Format
13
+ extend self
14
+
15
+ # Records every `minutes` minutes until stopped. Exits if another recorder
16
+ # is running.
17
+ def run(minutes)
18
+ FileUtils.mkdir_p(File.dirname(History.file))
19
+ # Open, and locked, for as long as the recorder runs.
20
+ lock = File.open(History.lock_file, File::RDWR | File::CREAT, 0o644) # rubocop:disable Style/FileOpen
21
+ unless lock.flock(File::LOCK_EX | File::LOCK_NB)
22
+ warn "Another recorder is already running (pid #{File.read(History.lock_file).strip}). " \
23
+ 'Only one can run at a time.'
24
+ exit 1
25
+ end
26
+ lock.truncate(0)
27
+ lock.write(Process.pid.to_s)
28
+ lock.flush
29
+ # HUP isn't trapped: under nohup it stays ignored, so closing the terminal
30
+ # that started the viewer doesn't stop a background recorder.
31
+ %w[INT TERM].each { |sig| trap(sig) { exit 0 } }
32
+
33
+ puts "Recording the Claude 5-hour usage every #{num(minutes)}m to #{History.file} " \
34
+ "(pid #{Process.pid}).#{zone_note} Stop with Ctrl-C or: #{stop_command(Process.pid)}"
35
+ last_prune = nil
36
+ loop do
37
+ if last_prune.nil? || Time.now - last_prune > 3600
38
+ History.prune
39
+ last_prune = Time.now
40
+ end
41
+ record_once(minutes)
42
+ $stdout.flush
43
+ sleep(minutes * 60)
44
+ end
45
+ end
46
+
47
+ # Checks the usage now, and appends the reading (or the error) to the
48
+ # history file and the log.
49
+ def record_once(minutes)
50
+ now = Time.now
51
+ reading = UsageApi.fetch_five_hour
52
+ stamp = clock(now, seconds: true)
53
+ if reading.is_a?(String)
54
+ History.append('t' => now.iso8601, 'interval_min' => minutes, 'error' => reading)
55
+ puts "#{stamp} error: #{reading}"
56
+ else
57
+ util, resets = reading
58
+ History.append('t' => now.iso8601, 'interval_min' => minutes, 'util' => util,
59
+ 'resets_at' => resets&.utc&.iso8601)
60
+ window = resets ? "window ends #{clock(resets)}" : 'no active window'
61
+ puts "#{stamp} #{format('%3d%%', util.round)} #{window}"
62
+ end
63
+ end
64
+
65
+ # Whether something holds the lock file's lock. The recorder holds it for
66
+ # as long as it runs, so it's the reliable sign of a running recorder.
67
+ def lock_held?
68
+ File.open(History.lock_file, File::RDWR) { |f| held?(f) }
69
+ rescue SystemCallError
70
+ false
71
+ end
72
+
73
+ # The running recorder's pid, or nil: the pid in the lock file, while the
74
+ # lock is held (checked again after reading it, in case the recorder just
75
+ # exited). nil for a held lock without a pid: a recorder in the instant
76
+ # between taking the lock and writing its pid (wait_for_pid waits that
77
+ # out), or something that isn't a recorder. So it's never a pid to show
78
+ # or signal that isn't in a held lock.
79
+ def pid
80
+ File.open(History.lock_file, File::RDWR) do |f|
81
+ next nil unless held?(f)
82
+
83
+ found = f.read.to_i
84
+ found.positive? && held?(f) ? found : nil
85
+ end
86
+ rescue SystemCallError
87
+ nil
88
+ end
89
+
90
+ # The pid of a recorder that's starting, once it has written it; nil if
91
+ # none appears within 2 seconds.
92
+ def wait_for_pid
93
+ 20.times do
94
+ sleep 0.1
95
+ found = pid
96
+ return found if found
97
+ end
98
+ nil
99
+ end
100
+
101
+ # Starts `record` in the background with nohup, in its own process group so
102
+ # Ctrl-C in the viewer's terminal doesn't reach it, recording to this
103
+ # process's history file (given with --file), with --utc if this process
104
+ # has it. Returns its pid (or nil if it didn't come up).
105
+ def start
106
+ log = History.log_file
107
+ FileUtils.mkdir_p(File.dirname(log))
108
+ child = Process.spawn('nohup', RbConfig.ruby, EXECUTABLE, 'record', '--file', History.file,
109
+ *('--utc' if Format.utc),
110
+ in: File::NULL, out: [log, 'a'], err: %i[child out], pgroup: true)
111
+ Process.detach(child)
112
+ wait_for_pid
113
+ end
114
+
115
+ # What to do when readings have stopped coming in, or nil. pid: the
116
+ # running recorder's, or nil. record: whether this viewer starts the
117
+ # recorder (not with --no-record or --once); restarting it the same way
118
+ # also keeps its history file. Short, for the panel, which
119
+ # truncates lines to the terminal's width.
120
+ def stale_hint(pid, record:)
121
+ if pid
122
+ "Check the output of the recorder (pid #{pid})"
123
+ elsif record
124
+ 'Restart the viewer, or see recorder.log'
125
+ end
126
+ end
127
+
128
+ # The running recorder's pid, waiting for one that holds the lock but
129
+ # hasn't written its pid yet. Returns [pid, foreign]: pid nil if there's
130
+ # no recorder, and foreign true if the lock is held all the same, by
131
+ # something that isn't a recorder (checked again after waiting, in case
132
+ # it let go).
133
+ def find
134
+ return [nil, false] unless lock_held?
135
+
136
+ found = pid || wait_for_pid
137
+ [found, found.nil? && lock_held?]
138
+ end
139
+
140
+ def foreign_lock_message
141
+ "Something holds #{History.lock_file} but isn't a recorder"
142
+ end
143
+
144
+ # Whether a recorder is running, as [pid, message], for a viewer that
145
+ # doesn't start one (--no-record).
146
+ def status
147
+ running, foreign = find
148
+ return [running, stop_hint(running)] if running
149
+
150
+ [nil, foreign ? "#{foreign_lock_message}." : 'No recorder is running.']
151
+ end
152
+
153
+ # How to stop the recorder with this pid. `claude-limit-watch stop` finds
154
+ # the recorder by its history file, so it needs --file unless this is the
155
+ # default file. brief: kill instead of --file, for the panel's footer,
156
+ # which has no room for a path.
157
+ def stop_command(pid, brief: false)
158
+ return 'claude-limit-watch stop' if bare_stop_works?
159
+
160
+ brief ? "kill #{pid}" : "claude-limit-watch stop --file #{Shellwords.escape(History.file)}"
161
+ end
162
+
163
+ def stop_hint(pid)
164
+ "Recorder running in the background (pid #{pid}). Stop it with: #{stop_command(pid)}"
165
+ end
166
+
167
+ # Makes sure a recorder is running. Returns [pid, message].
168
+ def ensure_running
169
+ running, foreign = find # a recorder, maybe just starting: don't start another
170
+ return [running, stop_hint(running)] if running
171
+ return [nil, "#{foreign_lock_message}; not starting one"] if foreign
172
+
173
+ started = start
174
+ if started
175
+ [started, "Started the recorder (every #{num(DEFAULT_INTERVAL_MIN)}m). #{stop_hint(started)}"]
176
+ else
177
+ [nil, "Couldn't start the recorder; see #{History.log_file}"]
178
+ end
179
+ end
180
+
181
+ # Stops the running recorder (the `stop` command).
182
+ def stop
183
+ running, foreign = find
184
+ if foreign
185
+ warn "#{foreign_lock_message}; not stopping anything."
186
+ exit 1
187
+ end
188
+ if running.nil?
189
+ puts 'No recorder is running.'
190
+ return
191
+ end
192
+ Process.kill('TERM', running)
193
+ 50.times do
194
+ sleep 0.1
195
+ if pid.nil?
196
+ puts "Stopped the recorder (pid #{running})."
197
+ return
198
+ end
199
+ end
200
+ warn "Sent TERM to pid #{running}, but it's still running."
201
+ exit 1
202
+ rescue Errno::ESRCH
203
+ puts "The recorder (pid #{running}) had already exited."
204
+ rescue Errno::EPERM
205
+ warn "Not allowed to stop pid #{running}."
206
+ exit 1
207
+ end
208
+
209
+ private def bare_stop_works?
210
+ History.file == File.expand_path(History.default_file)
211
+ rescue ArgumentError # HOME or XDG_STATE_HOME with ~nosuchuser: a bare stop couldn't use it either
212
+ false
213
+ end
214
+
215
+ # Whether something else holds the lock on f.
216
+ private def held?(f)
217
+ return true unless f.flock(File::LOCK_EX | File::LOCK_NB)
218
+
219
+ f.flock(File::LOCK_UN)
220
+ false
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ClaudeLimitWatch
4
+ # What the viewer shows for a history, as of a time.
5
+ module Snapshot
6
+ extend self
7
+
8
+ # Everything the viewer needs, derived from the history `records` as of
9
+ # `now`, with recent rates over the last `rate_window` minutes.
10
+ def build(records, now, rate_window:)
11
+ return { no_data: true } if records.empty?
12
+
13
+ last = records.last
14
+ st = { last_t: last[:t] }
15
+ st[:stale] = now - last[:t] > (last[:interval] * 60 * 2) + 60
16
+ if last[:error]
17
+ st[:error] = last[:error]
18
+ st[:error_at] = last[:t]
19
+ end
20
+
21
+ good = records.reject { |r| r[:error] }
22
+ latest = good.last
23
+ return st unless latest
24
+ return st.merge(no_window: latest[:util]) if latest[:resets].nil? || latest[:resets] <= now
25
+
26
+ window = good.select { |r| r[:resets] && (r[:resets] - latest[:resets]).abs < 60 }
27
+ prior = window[0...-1].map { |r| { t: r[:t], util: r[:util] } }
28
+ args = [prior, latest[:t], latest[:util], latest[:resets]]
29
+ st.merge(proj: Projection.project(*args, rate_window: rate_window),
30
+ table: Projection.projection_rows(*args, rate_window: rate_window))
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ClaudeLimitWatch
4
+ # Colors, and the terminal's size.
5
+ module Term
6
+ extend self
7
+
8
+ # 256-color codes: terminal themes often remap the 16 basic colors (yellow
9
+ # showing as orange, say), but generally leave these alone.
10
+ COLORS = { ok: '38;5;34', projected: '38;5;136', urgent: '38;5;196' }.freeze # green, yellow, red
11
+ WARN = COLORS[:projected] # warnings: yellow, as for a rate that runs out
12
+ # Secondary text. The one 16-color code, on purpose: themes remap bright
13
+ # black too, but to their own muted text color, which suits this text.
14
+ GRAY = 90
15
+ ANSI_RE = /\e\[[0-9;?]*[A-Za-z]/.freeze
16
+
17
+ # Text in the given SGR codes, or plain when colors are off or output
18
+ # isn't a terminal.
19
+ def paint(text, *codes)
20
+ return text if ENV['NO_COLOR'].to_s != '' || codes.empty? || !$stdout.tty?
21
+
22
+ "\e[#{codes.join(';')}m#{text}\e[0m"
23
+ end
24
+
25
+ # Truncate to a visible width, leaving ANSI escapes intact.
26
+ def fit(str, width)
27
+ out = +''
28
+ visible = 0
29
+ str.scan(/#{ANSI_RE}|./mo) do |tok|
30
+ if tok.start_with?("\e")
31
+ out << tok
32
+ elsif visible < width
33
+ out << tok
34
+ visible += 1
35
+ end
36
+ end
37
+ out
38
+ end
39
+
40
+ # The terminal's [rows, columns] (either may be 0 if unknown), or nil.
41
+ def term_size
42
+ require 'io/console'
43
+ IO.console&.winsize
44
+ rescue
45
+ nil
46
+ end
47
+
48
+ def term_width
49
+ cols = term_size&.last.to_i
50
+ cols.positive? ? cols : 80
51
+ end
52
+
53
+ # Terminal rows, or nil if unknown.
54
+ def term_height
55
+ rows = term_size&.first.to_i
56
+ rows.positive? ? rows : nil
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'open3'
6
+ require 'time'
7
+ require 'uri'
8
+
9
+ module ClaudeLimitWatch
10
+ # Fetches the 5-hour usage from the (undocumented) endpoint Claude Code's
11
+ # own usage display uses, with Claude Code's login.
12
+ module UsageApi
13
+ extend self
14
+
15
+ URL = URI('https://api.anthropic.com/api/oauth/usage')
16
+
17
+ def macos?
18
+ RUBY_PLATFORM.include?('darwin')
19
+ end
20
+
21
+ def access_token
22
+ raw =
23
+ if macos?
24
+ out, status = Open3.capture2('security', 'find-generic-password',
25
+ '-s', 'Claude Code-credentials', '-w')
26
+ status.success? ? out : nil
27
+ else
28
+ path = File.join(Dir.home, '.claude', '.credentials.json')
29
+ File.exist?(path) ? File.read(path) : nil
30
+ end
31
+ raw && JSON.parse(raw).dig('claudeAiOauth', 'accessToken')
32
+ rescue JSON::ParserError
33
+ nil
34
+ end
35
+
36
+ # Returns [utilization_percent, resets_at_or_nil], or an error string.
37
+ def fetch_five_hour
38
+ token = access_token or return 'no Claude Code credentials found'
39
+ req = Net::HTTP::Get.new(URL)
40
+ req['Authorization'] = "Bearer #{token}"
41
+ req['anthropic-beta'] = 'oauth-2025-04-20'
42
+ req['Accept'] = 'application/json'
43
+ req['User-Agent'] = 'claude-limit-watch'
44
+ res = Net::HTTP.start(URL.host, URL.port, use_ssl: true,
45
+ open_timeout: 10, read_timeout: 10) { |http| http.request(req) }
46
+ if res.code == '401'
47
+ return 'token expired (refreshes when a Claude Code session next runs)'
48
+ end
49
+ return 'rate-limited by the usage endpoint (HTTP 429); try a longer interval' if res.code == '429'
50
+ return "HTTP #{res.code} from usage endpoint" unless res.is_a?(Net::HTTPSuccess)
51
+
52
+ window = JSON.parse(res.body)['five_hour']
53
+ return 'no 5-hour window in response' unless window.is_a?(Hash) && window['utilization'].is_a?(Numeric)
54
+
55
+ resets = window['resets_at'] ? Time.parse(window['resets_at']) : nil
56
+ [window['utilization'].to_f, resets]
57
+ rescue => e
58
+ "#{e.class}: #{e.message}"
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ClaudeLimitWatch
4
+ VERSION = '0.1.0'
5
+ HOMEPAGE = 'https://github.com/keithrbennett/claude-limit-watch'
6
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ # claude-limit-watch: watch the Claude subscription's 5-hour usage limit.
4
+ #
5
+ # Two processes:
6
+ # - The recorder (`record`) checks usage every N minutes (default 5) and
7
+ # appends each reading to a history file (JSON Lines). Only one recorder
8
+ # runs at a time.
9
+ # - The viewer (the default command) starts the recorder in the background
10
+ # (nohup) if it isn't running (unless --no-record or --once), then shows the
11
+ # readings: a full-screen panel that redraws in place (quota used vs.
12
+ # time elapsed in the window, and projected use at the rate of the last
13
+ # 10m, 30m, 1h, 2h and the whole window), or with --lines / non-terminal
14
+ # output, one line per reading.
15
+ # It reads only the history file, so it can be closed and reopened freely
16
+ # and has the full history from the start.
17
+ #
18
+ # `claude-limit-watch --help` lists the commands and options.
19
+ #
20
+ # The utilization is account-wide (the same undocumented endpoint the
21
+ # claude-dashboard status line uses), so it covers every concurrent Claude
22
+ # Code session and any other tools using your Claude login.
23
+ #
24
+ # Stdlib only; works on Ruby 2.6+ (macOS system Ruby).
25
+ #
26
+ # The parts, each a module of functions:
27
+ # UsageApi fetches the current usage
28
+ # History the history file
29
+ # Recorder the recorder process, and starting and stopping it
30
+ # Projection burn rates and where they lead
31
+ # Snapshot what the viewer shows for a history, as of a time
32
+ # LinesView the one-line-per-reading view
33
+ # Panel the full-screen panel
34
+ # CLI the command line
35
+ # Format, Term text formatting, and colors and the terminal's size
36
+ #
37
+ # A module that includes Format or Term does so before `extend self`: before
38
+ # Ruby 3.0, extend self doesn't pick up modules included after it.
39
+
40
+ require_relative 'claude_limit_watch/version'
41
+
42
+ module ClaudeLimitWatch
43
+ WINDOW_MIN = 300.0 # the 5-hour window
44
+ DEFAULT_INTERVAL_MIN = 5 # how often to check
45
+ MIN_INTERVAL_MIN = 0.5 # polling much faster gets HTTP 429 from the endpoint
46
+ DEFAULT_RATE_WINDOW_MIN = 30 # recent burn rate uses readings from the last N minutes
47
+ VERSION_LINE = "claude-limit-watch #{VERSION} · #{HOMEPAGE}"
48
+ # The command, which Recorder.start runs to start a background recorder.
49
+ EXECUTABLE = File.expand_path('../exe/claude-limit-watch', __dir__)
50
+ end
51
+
52
+ require_relative 'claude_limit_watch/format'
53
+ require_relative 'claude_limit_watch/term'
54
+ require_relative 'claude_limit_watch/usage_api'
55
+ require_relative 'claude_limit_watch/history'
56
+ require_relative 'claude_limit_watch/projection'
57
+ require_relative 'claude_limit_watch/snapshot'
58
+ require_relative 'claude_limit_watch/recorder'
59
+ require_relative 'claude_limit_watch/lines_view'
60
+ require_relative 'claude_limit_watch/panel'
61
+ require_relative 'claude_limit_watch/cli'
metadata ADDED
@@ -0,0 +1,62 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: claude-limit-watch
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Keith R. Bennett
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Records Claude subscription usage in the background and shows a terminal
13
+ panel projecting when the 5-hour usage limit will be reached at recent burn rates.
14
+ Unofficial: not affiliated with Anthropic; uses an undocumented usage endpoint.'
15
+ email:
16
+ - keithrbennett@gmail.com
17
+ executables:
18
+ - claude-limit-watch
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - CHANGELOG.md
23
+ - LICENSE
24
+ - README.md
25
+ - docs/images/panel.png
26
+ - exe/claude-limit-watch
27
+ - lib/claude_limit_watch.rb
28
+ - lib/claude_limit_watch/cli.rb
29
+ - lib/claude_limit_watch/format.rb
30
+ - lib/claude_limit_watch/history.rb
31
+ - lib/claude_limit_watch/lines_view.rb
32
+ - lib/claude_limit_watch/panel.rb
33
+ - lib/claude_limit_watch/projection.rb
34
+ - lib/claude_limit_watch/recorder.rb
35
+ - lib/claude_limit_watch/snapshot.rb
36
+ - lib/claude_limit_watch/term.rb
37
+ - lib/claude_limit_watch/usage_api.rb
38
+ - lib/claude_limit_watch/version.rb
39
+ homepage: https://github.com/keithrbennett/claude-limit-watch
40
+ licenses:
41
+ - MIT
42
+ metadata:
43
+ changelog_uri: https://github.com/keithrbennett/claude-limit-watch/blob/main/CHANGELOG.md
44
+ rubygems_mfa_required: 'true'
45
+ rdoc_options: []
46
+ require_paths:
47
+ - lib
48
+ required_ruby_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '2.6'
53
+ required_rubygems_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '0'
58
+ requirements: []
59
+ rubygems_version: 4.0.23
60
+ specification_version: 4
61
+ summary: Watch the Claude subscription's 5-hour usage limit (unofficial)
62
+ test_files: []