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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 897bd10ce968a85f70e8d9d5ddb6b0c56552ef37c7a15c599c6847554d3afb2a
4
+ data.tar.gz: 9b2f3ae11cd163373d4008cd62beb77180cf94fbbebcfdf7a62208d0d776ad2a
5
+ SHA512:
6
+ metadata.gz: 3c3eccb2d1d38eec527944342e25c9772bff363e0cc11213c4147bd0b771b76613d8b9dfa4e875b1eab7840aee6708346412c1370d072e079043d2283b12c31a
7
+ data.tar.gz: 8c425a80e103b6537cdba6af556d683752e6ff95c5e428c443b862afc1c4b95acb57c49f0e155c0b0b15ffcf0cac4f86a5ba45d4be614ba8f36d664e068dc93c
data/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-23)
4
+
5
+ First release as a gem.
6
+
7
+ - Background recorder that checks the 5-hour usage every 5 minutes (or a
8
+ chosen interval) and keeps a JSON Lines history; `stop` stops it.
9
+ - Full-screen panel: quota used, time elapsed, and projection bars for
10
+ the rates of the last 10m, 30m, 1h, 2h and the whole window, showing when
11
+ each rate would reach the limit and how long you'd be locked out.
12
+ - `--lines` output (one line per reading) and `--once` (print the panel
13
+ once and exit).
14
+ - `--no-record`: view the history file without starting a recorder.
15
+ - `--utc`: show times in UTC instead of local time.
16
+ - `--file PATH` (any command): the history file to use.
17
+ - `--help` and `--version`.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Keith R. Bennett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,362 @@
1
+ # claude-limit-watch
2
+
3
+ [![CI](https://github.com/keithrbennett/claude-limit-watch/actions/workflows/ci.yml/badge.svg)](https://github.com/keithrbennett/claude-limit-watch/actions/workflows/ci.yml)
4
+
5
+ Watch your Claude subscription's 5-hour usage limit from the terminal. It
6
+ records your usage over time and projects when you will reach the limit.
7
+
8
+ **Unofficial.** claude-limit-watch isn't made, endorsed or supported by
9
+ Anthropic. It reads your usage from an undocumented endpoint, which may
10
+ change or stop working at any time. It uses the OAuth token Claude Code
11
+ stores on your machine, and sends it only to `api.anthropic.com`.
12
+
13
+ ![The claude-limit-watch panel](docs/images/panel.png)
14
+
15
+ ## Installation
16
+
17
+ gem install claude-limit-watch
18
+
19
+ It needs Ruby 2.6 or later and uses only the standard library, so it runs
20
+ on macOS's system Ruby.
21
+
22
+ ### Platforms
23
+
24
+ Linux and macOS are supported; CI tests both, on Ruby 2.6 through 4.0.
25
+ WSL on Windows is expected to work but isn't tested.
26
+
27
+ To use it in WSL, Claude Code must be signed in inside WSL, because
28
+ claude-limit-watch reads the credentials from `~/.claude/.credentials.json`
29
+ there.
30
+
31
+ Native Windows isn't supported, because the viewer starts the recorder with
32
+ `nohup` in its own Unix process group, and the panel reads keys through
33
+ `stty`.
34
+
35
+ ## Usage
36
+
37
+ claude-limit-watch [view] [rate-window-minutes]
38
+ [--lines] [--once] [--no-record] [--utc] [--file PATH]
39
+
40
+ `view` is the default command, so normally you just run
41
+ `claude-limit-watch`. `claude-limit-watch --help` lists all the commands
42
+ and options, and `--version` shows the version.
43
+
44
+ claude-limit-watch has two parts, which run as separate processes:
45
+
46
+ - **The recorder** checks your usage every 5 minutes and appends each
47
+ reading to the [history file](#history-file). Only one recorder runs at a
48
+ time for each history file.
49
+ - **The viewer** displays the readings from the history file. It never
50
+ contacts the network, so you can close and reopen it at any time without
51
+ losing history.
52
+
53
+ When the viewer starts, it starts a recorder in the background if one
54
+ isn't already running (unless you pass `--no-record` or `--once`). The
55
+ recorder is started with `nohup` in its own process group, so it keeps
56
+ running after you quit the viewer or close its terminal.
57
+
58
+ In a terminal, the viewer shows a full-screen [panel](#panel). With
59
+ `--lines`, or when its output isn't a terminal, it prints
60
+ [one line per reading](#line-output) instead.
61
+
62
+ ### Options
63
+
64
+ - **rate-window-minutes** (default 30): how far back the burn rate looks in
65
+ `--lines` output. On the panel, if it isn't 10, 30, 60 or 120, it
66
+ adds a row to the projection bars.
67
+ - **`--lines`**: print one line per reading instead of the panel.
68
+ - **`--once`**: print the panel once and exit, without starting a
69
+ recorder. When piped, the output has no colors.
70
+ - **`--no-record`**: don't start a recorder; just show the history file.
71
+ See [Viewing without recording](#viewing-without-recording).
72
+ - **`--utc`**: show times in UTC. See [Times in UTC](#times-in-utc).
73
+ - **`--file PATH`**: use a different history file. Every command takes
74
+ this option.
75
+
76
+ ## Panel
77
+
78
+ The panel takes over the whole terminal window, like `less` or `vim`,
79
+ and when you quit, your earlier terminal output is restored. Press **q** or
80
+ Ctrl-C to quit; the recorder keeps running.
81
+
82
+ ![The claude-limit-watch panel](docs/images/panel.png)
83
+
84
+ From top to bottom:
85
+
86
+ - **Heading**: a framed title in lavender. If the terminal is too narrow
87
+ for the frame, or too short for the whole panel, a one-line title
88
+ replaces it. This saves 4 rows, so the panel fits in a 24-row
89
+ terminal.
90
+ - **Used**: the percentage of the quota used in the current window.
91
+ - **Time**: how much of the 5-hour window has passed (in lavender). Below
92
+ it are the window's start and end times, followed by the current time.
93
+ - **Projection bars**: one bar per look-back period, showing what happens
94
+ if usage continues at the rate of the last 10 minutes, 30 minutes, 1
95
+ hour or 2 hours (plus your rate window, if it's different). The `all`
96
+ row uses the average rate since the window started. There is no single
97
+ overall projection.
98
+ - **Bottom lines**, below a horizontal rule: how to quit and how to stop
99
+ the recorder, with the current time on the right; the version and
100
+ project page; and whether the recorder is running, with its pid and the
101
+ history file it writes to. With `--once`, the line about quitting is
102
+ left out, but the current time is still shown.
103
+
104
+ ### Reading the projection bars
105
+
106
+ Each bar uses the same time scale as the Time bar and lines up under it. A
107
+ bar has up to three parts, each with its own fill character and color:
108
+
109
+ | Fill | Color | Meaning |
110
+ |------|--------------------------|-----------------------------------------------|
111
+ | █ | lavender | time elapsed so far |
112
+ | ▒ | green | time you can keep working at that rate |
113
+ | X | bold red on dark red | time you'd be locked out after the limit |
114
+ | │ | | the end of the window |
115
+
116
+ A bar that lasts to the end of the window has only █ and ▒. A bar that
117
+ reaches the limit also has X, shown with at least one X whenever there is
118
+ any lockout, and its text is red. Because the fill characters differ, you
119
+ can tell the parts apart without color.
120
+
121
+ The text after each bar gives either the time you'd reach the limit and
122
+ how long you'd be locked out (`limit at 01:49 · 20m locked out`), or how
123
+ much of the quota you'd have used when the window ends
124
+ (`limit not reached · 88% at the end`).
125
+
126
+ If the history doesn't go back as far as a row's look-back period, the row
127
+ is labeled with the period it actually covers (for example `1h50m` instead
128
+ of `2h`). If there is too little history for a row, the row says so.
129
+
130
+ ### When the panel shows no projections
131
+
132
+ - **During the first 30 minutes of a window** (`MIN_ELAPSED_MIN`), a single
133
+ line says when projections will start. Usage often spikes at the start
134
+ of a window, because resumed sessions resend their whole conversation.
135
+ A rate measured during those minutes would predict a limit that you
136
+ won't actually reach.
137
+ - **At the limit**, with no readings yet, or with no active window, a
138
+ status line replaces the projection bars. At the limit, the line is red
139
+ and shows the reset time.
140
+
141
+ ### Errors
142
+
143
+ A failed check (for example, an expired token, an HTTP 429 response or a
144
+ network error) appears as a yellow line. If readings stop arriving, the
145
+ panel says so and suggests what to do; see
146
+ [When readings stop](#when-readings-stop).
147
+
148
+ ### Copying from the panel
149
+
150
+ The panel checks for changes every second, but redraws only when its
151
+ text changes. Times are shown to the minute, so this is usually about once
152
+ a minute, and you can select and copy text between redraws. To copy the
153
+ whole panel, print it once:
154
+
155
+ claude-limit-watch --once | xclip -selection clipboard # pbcopy on macOS
156
+
157
+ ## Line output
158
+
159
+ With `--lines`, or when output isn't a terminal, the viewer prints the
160
+ readings already recorded for the current window, then one line for each
161
+ new reading:
162
+
163
+ Time | Level | Window | Ends | Used | 30m Burn Rate | Pace | Outlook
164
+ 22:49 | WARN | 2:00 of 5:00 | 01:49 | 33% | 30.0%/h (avg 16.2) | 1.3x | LIMIT at 01:04 (in 2:15), 0:45 before reset
165
+ 23:18 | no reading: rate-limited by the usage endpoint (HTTP 429); try a longer interval
166
+
167
+ Durations are shown as h:mm. At the limit, the Outlook column shows
168
+ `AT LIMIT, resets in h:mm`.
169
+
170
+ **Pace** is the current rate divided by the rate that would use exactly
171
+ the remaining quota by the end of the window. A pace of 1.0x reaches the
172
+ limit just as the window ends. For example, using 20% in the first 20
173
+ minutes is a pace of about 3.5x.
174
+
175
+ ### Levels
176
+
177
+ Each line is colored by its level:
178
+
179
+ - **OK** (green): at this rate, you won't reach the limit before the window
180
+ ends.
181
+ - **WARN** (yellow): at this rate, you will reach the limit before the
182
+ window ends.
183
+ - **URGENT** (red): you'll reach the limit before the window ends, and
184
+ either the pace is 2x or more or the limit is 20 minutes away or less.
185
+ Also shown when you're at the limit.
186
+
187
+ The thresholds are constants at the top of
188
+ `lib/claude_limit_watch/projection.rb`.
189
+
190
+ ## Colors
191
+
192
+ Colors come from the 256-color palette (green 34, yellow 136, red 196,
193
+ dark red 52, lavender 141), because terminal themes often change the 16
194
+ basic colors (showing yellow as orange, for example). The exception is the
195
+ gray used for secondary text: it is the basic "bright black", which themes
196
+ change to their own muted text color.
197
+
198
+ Set the `NO_COLOR` environment variable to turn colors off.
199
+
200
+ ## Viewing without recording
201
+
202
+ claude-limit-watch --no-record
203
+
204
+ The viewer shows the history file without starting a recorder. Use this
205
+ for a history file that nothing should record to, such as a copy from
206
+ another machine, a demo file, or any file you open with `--file` just to
207
+ look at it.
208
+
209
+ A recorder that is already running keeps running, and the viewer still
210
+ shows whether one is running. If readings stop, the viewer says so, but
211
+ doesn't suggest starting a recorder. `--once` behaves the same way.
212
+
213
+ ## Times in UTC
214
+
215
+ claude-limit-watch --utc
216
+
217
+ Shows all times in UTC instead of local time. Local time, the default, has
218
+ no marker. With UTC:
219
+
220
+ - the panel heading says so once for all times
221
+ (`times in UTC · last reading 09:00`);
222
+ - `--lines` output prints `Times are in UTC.` before the readings.
223
+
224
+ `record --utc` does the same for the recorder's own output. A recorder that
225
+ the viewer starts uses the viewer's setting for as long as it runs.
226
+
227
+ This option changes only what's displayed. The history file is the same
228
+ either way, because its times include their UTC offsets.
229
+
230
+ ## The recorder
231
+
232
+ ### Running the recorder yourself
233
+
234
+ claude-limit-watch record [interval-minutes] [--utc] [--file PATH]
235
+
236
+ Runs the recorder in the foreground, printing one short line per reading.
237
+ Press Ctrl-C to stop it.
238
+
239
+ Use this to check at a different interval. The default is 5 minutes; the
240
+ minimum is 0.5, and fractions are allowed. Start the recorder before the
241
+ viewer, and the viewer will use it instead of starting its own. The viewer
242
+ finds the recorder by its history file, so if you use `--file`, give both
243
+ commands the same path.
244
+
245
+ The minimum exists because checking every few seconds gets HTTP 429 (Too
246
+ Many Requests) responses from the usage endpoint. The endpoint's actual
247
+ rate limit isn't documented.
248
+
249
+ ### Stopping the recorder
250
+
251
+ claude-limit-watch stop
252
+
253
+ `stop` finds the recorder by its history file. If you use a history file
254
+ other than the default, give `stop` the same file:
255
+
256
+ claude-limit-watch stop --file PATH
257
+
258
+ You don't need to remember this command. The bottom of the panel shows
259
+ how to stop the recorder, and when you quit the viewer, it prints the
260
+ command again so it stays in your scrollback. For a non-default history
261
+ file, the printed command includes `--file PATH`. The panel has no room
262
+ for a path, so for such a file it shows `kill <pid>` instead, which works
263
+ for any recorder.
264
+
265
+ ### When readings stop
266
+
267
+ The viewer starts a recorder only when the viewer itself starts. If the
268
+ recorder stops while the viewer is open, the viewer reports that readings
269
+ have stopped, and suggests one of the following:
270
+
271
+ - **No recorder is running**: restart the viewer to start a new recorder.
272
+ If a new recorder fails to start, see `recorder.log`, in the same
273
+ directory as the history file.
274
+ - **A recorder is running, but readings have stopped anyway**: check the
275
+ recorder's output. For a recorder the viewer started, that's
276
+ `recorder.log`.
277
+
278
+ With `--no-record` or `--once`, the viewer only reports that readings have
279
+ stopped.
280
+
281
+ ## History file
282
+
283
+ The default history file is
284
+ `~/.local/state/claude-limit-watch/history.jsonl`, or
285
+ `$XDG_STATE_HOME/claude-limit-watch/history.jsonl` if `XDG_STATE_HOME` is
286
+ set. Every command takes `--file PATH` to use a different file. A recorder
287
+ that the viewer starts uses the viewer's history file.
288
+
289
+ The file is in JSON Lines format: one JSON object per reading. Readings are
290
+ only ever appended, so the viewer never sees a partly rewritten file.
291
+
292
+ {"t":"2026-11-17T23:19:47+08:00","interval_min":5.0,"util":46.0,"resets_at":"2026-11-17T18:09:59Z"}
293
+ {"t":"2026-11-17T23:24:47+08:00","interval_min":5.0,"error":"HTTP 429 from usage endpoint"}
294
+
295
+ The recorder deletes readings older than 7 days. A background recorder
296
+ writes its output to `recorder.log`, in the same directory as the history
297
+ file.
298
+
299
+ ## Upgrading
300
+
301
+ gem update claude-limit-watch
302
+ claude-limit-watch stop
303
+
304
+ A running recorder keeps running the version it started with, and a new
305
+ viewer uses the running recorder instead of starting its own. So after
306
+ updating, stop the recorder (see
307
+ [Stopping the recorder](#stopping-the-recorder)); the next viewer you start
308
+ will start a recorder running the new version.
309
+
310
+ ## How it works
311
+
312
+ - **Data source**: `https://api.anthropic.com/api/oauth/usage`. This
313
+ endpoint is undocumented; the claude-dashboard status line also uses it.
314
+ Requests are authenticated with Claude Code's OAuth token, which is read
315
+ from `~/.claude/.credentials.json` on Linux, or from the
316
+ `Claude Code-credentials` Keychain item on macOS. The first Keychain read
317
+ may ask for permission.
318
+ - **Scope**: utilization is account-wide. It includes every Claude Code
319
+ session running at the same time, and any other tools that use your
320
+ Claude login.
321
+ - **History**: the endpoint returns only the current utilization and the
322
+ window's reset time. All history comes from the recorder's own readings.
323
+ - **Rate over the last N minutes**: calculated from the reading closest to
324
+ N minutes ago. That reading may be up to 10% older than N minutes (at
325
+ least 1 minute older is always allowed). The history must cover at least
326
+ 3/4 of N minutes, or the rate isn't calculated.
327
+ - **Window average**: utilization divided by the time since the window
328
+ started (the reset time minus 5 hours). The `all` row uses it, and so
329
+ does `--lines` output until there's enough history for the rate window.
330
+ - **Precision**: utilization is reported in whole percentage points, so
331
+ rates over short periods are coarse. Over 10 minutes, a change of one
332
+ point is a rate of 6%/h.
333
+ - **Expired tokens**: if no Claude Code session has run for a while, the
334
+ token may have expired. The recorder logs an error for each check until
335
+ Claude Code refreshes the token.
336
+
337
+ ## Development
338
+
339
+ bundle install
340
+ bundle exec rake # run the specs (RSpec)
341
+ bundle exec rake rubocop # check the style (needs Ruby 2.7 or later)
342
+ bin/setup-hooks # optional: run both before each commit
343
+
344
+ `bin/setup-hooks` sets git's `core.hooksPath` to the tracked `hooks/`
345
+ directory, so the hooks you run are always the committed versions. For this
346
+ repository only, that setting overrides any global hooks path and any hooks
347
+ in `.git/hooks`.
348
+
349
+ The pre-commit hook checks the working tree, not just the staged changes,
350
+ and skips RuboCop on Ruby 2.6. To skip the hook for one commit, use
351
+ `git commit --no-verify`. To turn it off, run
352
+ `git config --unset core.hooksPath`.
353
+
354
+ CI (`.github/workflows/ci.yml`) runs the specs on Ruby 2.6 through 4.0, on
355
+ Linux and macOS, and runs RuboCop in a separate job on Ruby 4.0.
356
+
357
+ `ruby script/demo_history.rb` writes an invented history file for taking
358
+ screenshots; see the comment at the top of the script for details.
359
+
360
+ ## License
361
+
362
+ MIT; see [LICENSE](LICENSE).
Binary file
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative '../lib/claude_limit_watch'
5
+
6
+ ClaudeLimitWatch::CLI.main
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ClaudeLimitWatch
4
+ # The command line.
5
+ module CLI
6
+ include Format
7
+ extend self
8
+
9
+ def usage
10
+ <<~TEXT
11
+ Usage:
12
+ claude-limit-watch record [interval-minutes] [--utc]
13
+ Check usage every N minutes (default #{DEFAULT_INTERVAL_MIN}; #{MIN_INTERVAL_MIN} or more) and append
14
+ each reading to #{shown_file}.
15
+ --utc: show times in UTC instead of local time.
16
+ claude-limit-watch stop
17
+ Stop the recorder for this history file: for a history file other
18
+ than the default, give the same --file as the recorder's.
19
+ claude-limit-watch [view] [rate-window-minutes]
20
+ [--lines] [--once] [--no-record] [--utc]
21
+ Show the readings, first starting the recorder in the background if it
22
+ isn't running (except with --no-record or --once).
23
+ rate-window-minutes: the look-back for --lines output's burn rate
24
+ (default #{DEFAULT_RATE_WINDOW_MIN}); on the panel, it adds a row if it isn't 10, 30, 60
25
+ or 120.
26
+ --lines: one line per reading instead of the full-screen panel.
27
+ --once: print the panel once and exit (for copying).
28
+ --no-record: don't start the recorder; just show the history file.
29
+ --utc: show times in UTC instead of local time.
30
+ claude-limit-watch --help | -h
31
+ Show this help.
32
+ claude-limit-watch --version | -v
33
+ Show the version.
34
+
35
+ Every command also takes:
36
+ --file PATH: the history file to use (default:
37
+ #{home_relative(History.default_file)}).
38
+
39
+ #{VERSION_LINE}
40
+ TEXT
41
+ end
42
+
43
+ def main(argv = ARGV)
44
+ args = argv.dup
45
+ file_option(args)
46
+ if (args & %w[--help -h]).any?
47
+ puts usage
48
+ elsif (args & %w[--version -v]).any?
49
+ puts "claude-limit-watch #{VERSION}"
50
+ else
51
+ check_file
52
+ command(args)
53
+ end
54
+ end
55
+
56
+ private def command(args)
57
+ if args.first == 'record'
58
+ args.shift
59
+ utc_option(args)
60
+ minutes = number_arg(args[0], DEFAULT_INTERVAL_MIN, MIN_INTERVAL_MIN)
61
+ usage_error if minutes.nil? || args.size > 1
62
+ Recorder.run(minutes)
63
+ elsif args.first == 'stop'
64
+ usage_error if args.size > 1
65
+ Recorder.stop
66
+ else
67
+ view(args)
68
+ end
69
+ end
70
+
71
+ # Reports a history file path that can't be expanded (~nosuchuser) now,
72
+ # not partway through a command.
73
+ private def check_file
74
+ History.file
75
+ rescue ArgumentError => e
76
+ abort "claude-limit-watch: can't use the default history file (check HOME and XDG_STATE_HOME): " \
77
+ "#{e.message}"
78
+ end
79
+
80
+ # The history file for the help, with ~ for the home directory; as given,
81
+ # if it can't be expanded, so the help still shows.
82
+ private def shown_file
83
+ home_relative(History.file)
84
+ rescue ArgumentError
85
+ History.default_file
86
+ end
87
+
88
+ private def view(args)
89
+ args.shift if args.first == 'view'
90
+ utc_option(args)
91
+ lines_mode = !args.delete('--lines').nil?
92
+ once = !args.delete('--once').nil?
93
+ record = args.delete('--no-record').nil?
94
+ rate_window = number_arg(args[0], DEFAULT_RATE_WINDOW_MIN, 1)
95
+ usage_error if rate_window.nil? || args.size > 1
96
+ return Panel.run_once(rate_window) if once
97
+
98
+ # Ctrl-C while the recorder starts (up to 2 seconds) exits quietly.
99
+ trap('INT') do
100
+ puts
101
+ exit 0
102
+ end
103
+ # The viewer starts the recorder, unless told not to.
104
+ if lines_mode || !$stdout.tty?
105
+ pid, message = record ? Recorder.ensure_running : Recorder.status
106
+ LinesView.run(rate_window, pid, message, record: record)
107
+ else
108
+ Recorder.ensure_running if record
109
+ Panel.run(rate_window, record: record)
110
+ end
111
+ end
112
+
113
+ # Takes --file PATH (or --file=PATH) out of the arguments, and uses that
114
+ # history file.
115
+ private def file_option(args)
116
+ file_arg = ->(a) { a == '--file' || a.start_with?('--file=') }
117
+ i = args.index(&file_arg)
118
+ return unless i
119
+
120
+ arg = args.delete_at(i)
121
+ # A separate path can't look like an option (--file --once); with = it can.
122
+ path = arg == '--file' ? args.delete_at(i) : arg.sub('--file=', '')
123
+ looks_like_option = arg == '--file' && path&.start_with?('-')
124
+ usage_error if path.nil? || path.empty? || looks_like_option || args.any?(&file_arg)
125
+ begin
126
+ History.file = path
127
+ rescue ArgumentError => e
128
+ abort "claude-limit-watch: can't use --file #{path}: #{e.message}"
129
+ end
130
+ end
131
+
132
+ # Takes --utc out of the arguments; times are in UTC if it was there.
133
+ private def utc_option(args)
134
+ Format.utc = !args.delete('--utc').nil?
135
+ end
136
+
137
+ # The argument as a number, or the default if it's missing; nil if it
138
+ # isn't a number at least `min`.
139
+ private def number_arg(arg, default, min)
140
+ n = Float(arg || default)
141
+ n.finite? && n >= min ? n : nil
142
+ rescue ArgumentError, TypeError
143
+ nil
144
+ end
145
+
146
+ private def usage_error
147
+ warn usage
148
+ exit 1
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ClaudeLimitWatch
4
+ # Numbers, durations and times as text.
5
+ module Format
6
+ extend self
7
+
8
+ class << self
9
+ # Whether times are shown in UTC (--utc) rather than local time.
10
+ attr_accessor :utc
11
+ end
12
+
13
+ # Minutes for display: "5", "2.5".
14
+ def num(minutes)
15
+ minutes == minutes.round ? minutes.round.to_s : minutes.to_s
16
+ end
17
+
18
+ # Duration in minutes as h:mm.
19
+ def hm(min)
20
+ min = [min.round, 0].max
21
+ format('%d:%02d', min / 60, min % 60)
22
+ end
23
+
24
+ # A compact duration label, in minutes: "50m", "1h50m".
25
+ def span_label(min)
26
+ m = min.round
27
+ m < 60 ? "#{m}m" : format('%dh%02dm', m / 60, m % 60)
28
+ end
29
+
30
+ # A time of day, in local time or (with --utc) UTC: "08:00", or with
31
+ # seconds, "08:00:15".
32
+ # Through UTC, since getlocal leaves a time that's already local as it is,
33
+ # in whatever zone was local when its local fields were worked out.
34
+ def clock(time, seconds: false)
35
+ t = Format.utc ? time.getutc : time.getutc.getlocal
36
+ t.strftime(seconds ? '%H:%M:%S' : '%H:%M')
37
+ end
38
+
39
+ # A note that times are in UTC, for the text that introduces them; empty
40
+ # for local time.
41
+ def zone_note
42
+ Format.utc ? ' Times are in UTC.' : ''
43
+ end
44
+
45
+ # Duration, rounded to the minute: "1h 12m", "58m", "<1m". On the panel,
46
+ # that means the text (and the screen) changes only about once a minute.
47
+ def dur_m(seconds)
48
+ m = (seconds / 60.0).round
49
+ return '<1m' if m < 1
50
+
51
+ m >= 60 ? format('%dh %02dm', m / 60, m % 60) : "#{m}m"
52
+ end
53
+
54
+ def home_relative(path)
55
+ path.start_with?("#{Dir.home}/") ? "~#{path[Dir.home.size..]}" : path
56
+ end
57
+ end
58
+ end