claude-usage-limits 0.2.1__tar.gz → 0.3.1__tar.gz

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.
Files changed (20) hide show
  1. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/PKG-INFO +52 -16
  2. claude_usage_limits-0.2.1/src/claude_usage_limits.egg-info/PKG-INFO → claude_usage_limits-0.3.1/README.md +49 -33
  3. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/pyproject.toml +3 -3
  4. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage/__init__.py +1 -1
  5. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage/api.py +25 -5
  6. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage/cli.py +16 -6
  7. claude_usage_limits-0.3.1/src/claude_usage/report.py +221 -0
  8. claude_usage_limits-0.2.1/README.md → claude_usage_limits-0.3.1/src/claude_usage_limits.egg-info/PKG-INFO +69 -13
  9. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/tests/test_report.py +107 -1
  10. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/tests/test_sources.py +59 -0
  11. claude_usage_limits-0.2.1/src/claude_usage/report.py +0 -111
  12. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/LICENSE +0 -0
  13. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/setup.cfg +0 -0
  14. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage/__main__.py +0 -0
  15. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage/auth.py +0 -0
  16. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
  17. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
  18. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
  19. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
  20. {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.1}/tests/test_auth.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.2.1
4
- Summary: CLI for Claude subscription usage and model limits, with status-line output and warning thresholds.
3
+ Version: 0.3.1
4
+ Summary: CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds.
5
5
  Author: claude-usage contributors
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
8
8
  Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
9
- Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,cli
9
+ Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,swiftbar,menubar,cli
10
10
  Classifier: Development Status :: 4 - Beta
11
11
  Classifier: Environment :: Console
12
12
  Classifier: Intended Audience :: Developers
@@ -45,21 +45,23 @@ login already on your machine. No API key to manage, nothing to configure.
45
45
 
46
46
  The 5-hour window appears when your plan has one and the usage source reports
47
47
  it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
48
+ Usage-based plans such as Enterprise show spend instead of percentages.
48
49
 
49
50
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
50
51
 
51
52
  ```text
52
53
  $ claude-usage
54
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
53
55
  7-day: 59% used, resets Sun 03:00 (in 12h29m)
54
56
  ```
55
57
 
56
58
  ## ✨ Features
57
59
 
58
60
  - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
59
- - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
61
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available, all weekly limits, and spend percentage. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
60
62
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
61
63
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
62
- - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
64
+ - **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
63
65
  - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
64
66
  - **🔋 Zero dependencies** — pure Python standard library.
65
67
  - **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
@@ -80,10 +82,13 @@ its access token fresh.
80
82
  |---|---|
81
83
  | `claude-usage` | Available usage windows and their reset times |
82
84
  | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
83
- | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
85
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
84
86
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
85
87
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
86
- | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
88
+ | `claude-usage --format {plain,json,short,menubar}` | Choose output format (default plain) |
89
+ | `claude-usage --format menubar` | Print SwiftBar/xbar plugin output |
90
+ | `claude-usage --max-age SECONDS` | Set the fresh cache age (default 300, clamped to 30–3600) |
91
+ | `claude-usage --live` | Prefer a fresh status-line cache from an active Claude Code session (Pro/Max) |
87
92
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
88
93
  | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
89
94
  | `claude-usage -V`, `--version` | Print the version |
@@ -97,6 +102,7 @@ only in plain format, keeping JSON machine-readable and short output on one line
97
102
  <summary><b>📊 Example: <code>--all</code></b></summary>
98
103
 
99
104
  ```text
105
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
100
106
  7-day: 60% used, resets Sun 03:00 (in 12h11m)
101
107
  kind percent severity active model reset
102
108
  ------------------------------------------------------------------------------
@@ -121,8 +127,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
121
127
  either threshold trips or no source answers, **2** for an argument error.
122
128
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
123
129
  Missing or null windows do not trigger warnings. `--warn` includes session and
124
- weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
125
- usage windows appear in plain and short output and are checked by `--warn`.
130
+ weekly entries in `limits[]`, and spend percentage when there is a spend limit.
131
+ `--warn-7d` checks only `seven_day`. Populated `seven_day_*` usage windows appear
132
+ in plain and short output and are checked by `--warn`.
126
133
  JSON preserves the source payload, including null fields and weekly share indices.
127
134
 
128
135
  ## 📟 Claude Code status line
@@ -146,17 +153,45 @@ Missing parts are omitted. This mode never looks up credentials or makes a netwo
146
153
  call. It also writes `last-statusline.json`, feeding the documented fallback when
147
154
  the endpoint is unavailable. Invalid input produces no output and exits 0.
148
155
  `claude-usage --format short` gives the same compact format from the normal source
149
- order; endpoint answers usually have no model, so show `7d 59%`.
156
+ order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
157
+
158
+ ## 🖥️ SwiftBar menu bar
159
+
160
+ ```text
161
+ $ claude-usage --format menubar
162
+ 5h 23% · 7d 59% | sfimage=gauge.with.dots.needle.50percent
163
+ ---
164
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
165
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
166
+ weekly_scoped (Fable): 9%
167
+ Source: endpoint | size=11
168
+ ```
169
+
170
+ The title turns orange at 70% and red at 90%. On usage-based plans it shows the
171
+ spend, e.g. `$12.34`. If every source fails, the item shows `Claude ⚠` with the reason.
172
+
173
+ Save `claude-usage.1m.sh` in your SwiftBar plugin folder and make it executable.
174
+
175
+ ```sh
176
+ #!/bin/sh
177
+ claude-usage --format menubar --live --max-age 60
178
+ ```
179
+
180
+ SwiftBar uses a minimal `PATH`, so replace `claude-usage` in the script with its
181
+ absolute path. Set up the Claude Code status line above to get live updates.
150
182
 
151
183
  ## 🤔 How it works
152
184
 
153
185
  Sources are tried in this order:
154
186
 
155
- 1. `last-usage.json` if less than **5 minutes** old.
187
+ 1. `last-usage.json` if less than **5 minutes** old by default.
156
188
  2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
157
189
  3. `last-usage.json` if less than **60 minutes** old.
158
190
  4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
159
191
 
192
+ `--max-age` sets the fresh cache age for step 1 and `--live`. With `--live`, a
193
+ fresh status-line cache is tried first if the endpoint cache is older or missing.
194
+
160
195
  Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
161
196
  atomic. Cached answers at least a minute old show their source and age, e.g.
162
197
  `(from the endpoint, 3 min ago)`; status-line answers always show their age.
@@ -202,11 +237,12 @@ For the protocol and a recipe to rebuild the tool, see
202
237
 
203
238
  - The OAuth usage endpoint is **undocumented and rate limited**; it may change or
204
239
  disappear. The documented status-line path is the fallback.
205
- - Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
206
- after the first API response, and drops individual windows after they reset.
207
- It updates only while a Claude Code session is active and repainting.
208
- - The observed endpoint response came from a Max account. Fields on other plans
209
- may differ; an API key is not a Claude Code OAuth login.
240
+ - Usage-based plans report spend. Subscription plans report usage percentages.
241
+ - Status-line `rate_limits`, which powers `--live`, is **Pro/Max only**. It appears
242
+ after the first API response, drops individual windows after they reset, and
243
+ updates while a Claude Code session is active and repainting.
244
+ - The observed endpoint responses came from Max and Enterprise accounts. Fields on
245
+ other plans may differ; an API key is not a Claude Code OAuth login.
210
246
  - Any running `claude` keeps the access token fresh. This tool deliberately does
211
247
  not implement the undocumented refresh flow.
212
248
  - Use **`/feedback` in Claude Code** to ask Anthropic for an official
@@ -1,23 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: claude-usage-limits
3
- Version: 0.2.1
4
- Summary: CLI for Claude subscription usage and model limits, with status-line output and warning thresholds.
5
- Author: claude-usage contributors
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
8
- Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
9
- Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,cli
10
- Classifier: Development Status :: 4 - Beta
11
- Classifier: Environment :: Console
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Operating System :: OS Independent
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Topic :: Utilities
16
- Requires-Python: >=3.9
17
- Description-Content-Type: text/markdown
18
- License-File: LICENSE
19
- Dynamic: license-file
20
-
21
1
  <h1 align="center">📊 claude-usage</h1>
22
2
 
23
3
  <p align="center">
@@ -45,21 +25,23 @@ login already on your machine. No API key to manage, nothing to configure.
45
25
 
46
26
  The 5-hour window appears when your plan has one and the usage source reports
47
27
  it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
28
+ Usage-based plans such as Enterprise show spend instead of percentages.
48
29
 
49
30
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
50
31
 
51
32
  ```text
52
33
  $ claude-usage
34
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
53
35
  7-day: 59% used, resets Sun 03:00 (in 12h29m)
54
36
  ```
55
37
 
56
38
  ## ✨ Features
57
39
 
58
40
  - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
59
- - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
41
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available, all weekly limits, and spend percentage. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
60
42
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
61
43
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
62
- - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
44
+ - **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
63
45
  - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
64
46
  - **🔋 Zero dependencies** — pure Python standard library.
65
47
  - **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
@@ -80,10 +62,13 @@ its access token fresh.
80
62
  |---|---|
81
63
  | `claude-usage` | Available usage windows and their reset times |
82
64
  | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
83
- | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
65
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
84
66
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
85
67
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
86
- | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
68
+ | `claude-usage --format {plain,json,short,menubar}` | Choose output format (default plain) |
69
+ | `claude-usage --format menubar` | Print SwiftBar/xbar plugin output |
70
+ | `claude-usage --max-age SECONDS` | Set the fresh cache age (default 300, clamped to 30–3600) |
71
+ | `claude-usage --live` | Prefer a fresh status-line cache from an active Claude Code session (Pro/Max) |
87
72
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
88
73
  | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
89
74
  | `claude-usage -V`, `--version` | Print the version |
@@ -97,6 +82,7 @@ only in plain format, keeping JSON machine-readable and short output on one line
97
82
  <summary><b>📊 Example: <code>--all</code></b></summary>
98
83
 
99
84
  ```text
85
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
100
86
  7-day: 60% used, resets Sun 03:00 (in 12h11m)
101
87
  kind percent severity active model reset
102
88
  ------------------------------------------------------------------------------
@@ -121,8 +107,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
121
107
  either threshold trips or no source answers, **2** for an argument error.
122
108
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
123
109
  Missing or null windows do not trigger warnings. `--warn` includes session and
124
- weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
125
- usage windows appear in plain and short output and are checked by `--warn`.
110
+ weekly entries in `limits[]`, and spend percentage when there is a spend limit.
111
+ `--warn-7d` checks only `seven_day`. Populated `seven_day_*` usage windows appear
112
+ in plain and short output and are checked by `--warn`.
126
113
  JSON preserves the source payload, including null fields and weekly share indices.
127
114
 
128
115
  ## 📟 Claude Code status line
@@ -146,17 +133,45 @@ Missing parts are omitted. This mode never looks up credentials or makes a netwo
146
133
  call. It also writes `last-statusline.json`, feeding the documented fallback when
147
134
  the endpoint is unavailable. Invalid input produces no output and exits 0.
148
135
  `claude-usage --format short` gives the same compact format from the normal source
149
- order; endpoint answers usually have no model, so show `7d 59%`.
136
+ order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
137
+
138
+ ## 🖥️ SwiftBar menu bar
139
+
140
+ ```text
141
+ $ claude-usage --format menubar
142
+ 5h 23% · 7d 59% | sfimage=gauge.with.dots.needle.50percent
143
+ ---
144
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
145
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
146
+ weekly_scoped (Fable): 9%
147
+ Source: endpoint | size=11
148
+ ```
149
+
150
+ The title turns orange at 70% and red at 90%. On usage-based plans it shows the
151
+ spend, e.g. `$12.34`. If every source fails, the item shows `Claude ⚠` with the reason.
152
+
153
+ Save `claude-usage.1m.sh` in your SwiftBar plugin folder and make it executable.
154
+
155
+ ```sh
156
+ #!/bin/sh
157
+ claude-usage --format menubar --live --max-age 60
158
+ ```
159
+
160
+ SwiftBar uses a minimal `PATH`, so replace `claude-usage` in the script with its
161
+ absolute path. Set up the Claude Code status line above to get live updates.
150
162
 
151
163
  ## 🤔 How it works
152
164
 
153
165
  Sources are tried in this order:
154
166
 
155
- 1. `last-usage.json` if less than **5 minutes** old.
167
+ 1. `last-usage.json` if less than **5 minutes** old by default.
156
168
  2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
157
169
  3. `last-usage.json` if less than **60 minutes** old.
158
170
  4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
159
171
 
172
+ `--max-age` sets the fresh cache age for step 1 and `--live`. With `--live`, a
173
+ fresh status-line cache is tried first if the endpoint cache is older or missing.
174
+
160
175
  Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
161
176
  atomic. Cached answers at least a minute old show their source and age, e.g.
162
177
  `(from the endpoint, 3 min ago)`; status-line answers always show their age.
@@ -202,11 +217,12 @@ For the protocol and a recipe to rebuild the tool, see
202
217
 
203
218
  - The OAuth usage endpoint is **undocumented and rate limited**; it may change or
204
219
  disappear. The documented status-line path is the fallback.
205
- - Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
206
- after the first API response, and drops individual windows after they reset.
207
- It updates only while a Claude Code session is active and repainting.
208
- - The observed endpoint response came from a Max account. Fields on other plans
209
- may differ; an API key is not a Claude Code OAuth login.
220
+ - Usage-based plans report spend. Subscription plans report usage percentages.
221
+ - Status-line `rate_limits`, which powers `--live`, is **Pro/Max only**. It appears
222
+ after the first API response, drops individual windows after they reset, and
223
+ updates while a Claude Code session is active and repainting.
224
+ - The observed endpoint responses came from Max and Enterprise accounts. Fields on
225
+ other plans may differ; an API key is not a Claude Code OAuth login.
210
226
  - Any running `claude` keeps the access token fresh. This tool deliberately does
211
227
  not implement the undocumented refresh flow.
212
228
  - Use **`/feedback` in Claude Code** to ask Anthropic for an official
@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "claude-usage-limits"
7
- version = "0.2.1"
8
- description = "CLI for Claude subscription usage and model limits, with status-line output and warning thresholds."
7
+ version = "0.3.1"
8
+ description = "CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE"]
12
12
  requires-python = ">=3.9"
13
13
  authors = [{ name = "claude-usage contributors" }]
14
- keywords = ["claude", "claude-code", "anthropic", "usage", "rate-limit", "weekly-usage", "subscription", "statusline", "cli"]
14
+ keywords = ["claude", "claude-code", "anthropic", "usage", "rate-limit", "weekly-usage", "subscription", "statusline", "swiftbar", "menubar", "cli"]
15
15
  classifiers = [
16
16
  "Development Status :: 4 - Beta",
17
17
  "Environment :: Console",
@@ -1,3 +1,3 @@
1
1
  """claude-usage: read your Claude subscription rate-limit windows."""
2
2
 
3
- __version__ = "0.2.1"
3
+ __version__ = "0.3.1"
@@ -1,6 +1,6 @@
1
1
  """Minimal OAuth usage client with endpoint and documented status-line caches.
2
2
 
3
- The undocumented endpoint is rate limited: reuse answers for five minutes,
3
+ The undocumented endpoint is rate limited: reuse answers for five minutes by default,
4
4
  make at most one live request, then accept either cache for up to an hour.
5
5
  No retries, polling, or token refresh. All HTTP goes through ``_get_json``.
6
6
  """
@@ -18,6 +18,7 @@ from .report import shape
18
18
 
19
19
  URL = "https://api.anthropic.com/api/oauth/usage"
20
20
  FRESH = 300
21
+ MIN_FRESH = 30
21
22
  MAX_AGE = 3600
22
23
 
23
24
 
@@ -84,19 +85,38 @@ def from_cache(config):
84
85
  return shape(data, f'status line, {int(age // 60)} min ago')
85
86
 
86
87
 
87
- def usage(config=None, verbose=False):
88
+ def from_live_statusline(config, fresh):
89
+ config = Path(config)
90
+ try:
91
+ status_mtime = (config / 'last-statusline.json').stat().st_mtime
92
+ except FileNotFoundError:
93
+ raise RuntimeError('status-line cache not fresh') from None
94
+ try:
95
+ endpoint_mtime = (config / 'last-usage.json').stat().st_mtime
96
+ except FileNotFoundError:
97
+ endpoint_mtime = None
98
+ if (time.time() - status_mtime >= fresh or
99
+ (endpoint_mtime is not None and status_mtime <= endpoint_mtime)):
100
+ raise RuntimeError('status-line cache not fresh')
101
+ return from_cache(config)
102
+
103
+
104
+ def usage(config=None, verbose=False, fresh=FRESH, live=False):
88
105
  """Return the first available source or raise its distinct failure reasons."""
89
106
  config = Path(config) if config is not None else config_dir()
90
107
  errors = []
91
- sources = (lambda: from_last(config, FRESH),
108
+ fresh = max(MIN_FRESH, min(fresh, MAX_AGE))
109
+ sources = (lambda: from_last(config, fresh),
92
110
  lambda: from_endpoint(config, verbose=verbose),
93
111
  lambda: from_last(config, MAX_AGE),
94
112
  lambda: from_cache(config))
95
- for source in sources:
113
+ if live:
114
+ sources = (lambda: from_live_statusline(config, fresh),) + sources
115
+ for index, source in enumerate(sources):
96
116
  try:
97
117
  out = source()
98
118
  except (RuntimeError, OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError) as exc:
99
- if str(exc) not in errors:
119
+ if (not live or index > 0) and str(exc) not in errors:
100
120
  errors.append(str(exc))
101
121
  else:
102
122
  if verbose:
@@ -5,9 +5,10 @@ import json
5
5
  import sys
6
6
 
7
7
  from . import __version__
8
- from .api import usage, write_cache
8
+ from .api import FRESH, MAX_AGE, MIN_FRESH, usage, write_cache
9
9
  from .auth import config_dir, resolve_plan
10
- from .report import render_limits, render_plain, render_short, shape, warning_reached
10
+ from .report import (render_limits, render_menubar, render_menubar_error, render_plain,
11
+ render_short, shape, warning_reached)
11
12
 
12
13
 
13
14
  def build_parser():
@@ -18,14 +19,19 @@ def build_parser():
18
19
  p.add_argument('--json', action='store_const', dest='format', const='json',
19
20
  help='print the raw usage JSON (alias for --format json)')
20
21
  p.add_argument('--warn', type=int, nargs='?', const=70, metavar='N',
21
- help='check the 5-hour window (when your plan has one) and weekly limits, '
22
- 'exiting 1 at or above N%% (default 70)')
22
+ help='check the 5-hour window (when your plan has one), weekly limits and '
23
+ 'spend, exiting 1 at or above N%% (default 70)')
23
24
  p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
24
25
  help='exit 1 when the 7-day window is at or above N%% (default 70)')
25
26
  p.add_argument('--all', action='store_true',
26
27
  help='add per-limit details and the weekly surface breakdown (plain format)')
27
- p.add_argument('--format', choices=('plain', 'json', 'short'), default='plain',
28
+ p.add_argument('--format', choices=('plain', 'json', 'short', 'menubar'), default='plain',
28
29
  help='output format (default: plain)')
30
+ p.add_argument('--max-age', type=int, metavar='SECONDS', default=FRESH,
31
+ help=f'fresh cache age in seconds (default {FRESH}, clamped to {MIN_FRESH}–{MAX_AGE})')
32
+ p.add_argument('--live', action='store_true',
33
+ help='follow active Claude Code sessions without extra requests '
34
+ '(status-line rate_limits are Pro/Max only)')
29
35
  p.add_argument('--statusline', action='store_true', help=argparse.SUPPRESS)
30
36
  p.add_argument('-v', '--verbose', action='store_true',
31
37
  help='log credential and usage sources and the plan to stderr')
@@ -51,7 +57,7 @@ def main(argv=None):
51
57
  if args.statusline:
52
58
  return statusline()
53
59
  try:
54
- out = usage(verbose=args.verbose)
60
+ out = usage(verbose=args.verbose, fresh=args.max_age, live=args.live)
55
61
  if args.verbose:
56
62
  plan = resolve_plan()
57
63
  if plan is not None:
@@ -61,6 +67,8 @@ def main(argv=None):
61
67
  print()
62
68
  elif args.format == 'short':
63
69
  print(render_short(out))
70
+ elif args.format == 'menubar':
71
+ print(render_menubar(out))
64
72
  else:
65
73
  print(render_plain(out))
66
74
  if args.all:
@@ -68,6 +76,8 @@ def main(argv=None):
68
76
  if details:
69
77
  print(details)
70
78
  except (RuntimeError, OSError, ValueError, TypeError, AttributeError, OverflowError) as exc:
79
+ if args.format == 'menubar':
80
+ print(render_menubar_error(str(exc)))
71
81
  print('claude-usage: ' + str(exc), file=sys.stderr)
72
82
  return 1
73
83
  if args.warn is not None and warning_reached(out, args.warn):
@@ -0,0 +1,221 @@
1
+ """Turn endpoint and status-line payloads into compact usage reports."""
2
+
3
+ from datetime import datetime, timezone
4
+
5
+ MENUBAR_WARN = 70
6
+ MENUBAR_CRIT = 90
7
+
8
+
9
+ def shape(data, source):
10
+ """Normalize usage windows and retain the untouched payload for JSON output."""
11
+ if not isinstance(data, dict):
12
+ raise ValueError("usage data is not a JSON object")
13
+ out = {"source": source, "raw": data}
14
+ status = source.startswith("status line")
15
+ windows = (data.get("rate_limits") or {}) if status else data
16
+ keys = ["seven_day"] + sorted(key for key, value in windows.items()
17
+ if key.startswith("seven_day_") and isinstance(value, dict)
18
+ and ("utilization" in value or "used_percentage" in value))
19
+ if isinstance(windows.get("five_hour"), dict):
20
+ keys.insert(0, "five_hour")
21
+ for key in keys:
22
+ window = windows.get(key) or {}
23
+ reset = window.get("resets_at")
24
+ if status and reset is not None:
25
+ reset = datetime.fromtimestamp(reset, timezone.utc).isoformat()
26
+ used = window.get("used_percentage" if status else "utilization")
27
+ out[key] = {"utilization": float(used) if used is not None else None,
28
+ "resets_at": reset}
29
+ return out
30
+
31
+
32
+ def usage_windows(usage):
33
+ """Yield normalized usage windows in display order."""
34
+ return ((key, window) for key, window in usage.items()
35
+ if key in ("five_hour", "seven_day") or key.startswith("seven_day_"))
36
+
37
+
38
+ def peak(usage):
39
+ return max((window['utilization'] for _, window in usage_windows(usage)
40
+ if window['utilization'] is not None), default=None)
41
+
42
+
43
+ def window_label(key, short=False):
44
+ if key == "five_hour":
45
+ return "5h" if short else "5-hour"
46
+ label = "7d" if short else "7-day"
47
+ suffix = key[len("seven_day"):].strip("_").replace("_", " ")
48
+ return f"{label} {suffix}" if suffix else label
49
+
50
+
51
+ def warning_reached(usage, threshold):
52
+ """Check normalized windows, session and weekly limits, and spend."""
53
+ values = [window['utilization'] for _, window in usage_windows(usage)]
54
+ values.extend(limit.get('percent') for limit in usage['raw'].get('limits') or []
55
+ if limit.get('group') in ('session', 'weekly') or limit.get('kind') == 'session'
56
+ or limit.get('kind', '').startswith('weekly_'))
57
+ spending = spend(usage)
58
+ if spending is not None:
59
+ values.append(spending['percent'])
60
+ return any(value is not None and float(value) >= threshold for value in values)
61
+
62
+
63
+ def when(iso):
64
+ if not iso:
65
+ return "reset time unknown"
66
+ t = datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone()
67
+ now = datetime.now(t.tzinfo)
68
+ mins = max(0, int((t - now).total_seconds() // 60))
69
+ h, m = divmod(mins, 60)
70
+ span = f"{h}h{m:02d}m" if h else f"{m}m"
71
+ day = "" if t.date() == now.date() else t.strftime("%a ")
72
+ return f"resets {day}{t:%H:%M} (in {span})"
73
+
74
+
75
+ def pct(window):
76
+ used = window.get("utilization")
77
+ return "?" if used is None else f"{used:.0f}%"
78
+
79
+
80
+ def _money(amount, currency, places):
81
+ if not isinstance(currency, str) or not currency:
82
+ raise ValueError('missing currency')
83
+ text = f'{amount / 10**places:,.2f}'
84
+ return f'${text}' if currency == 'USD' else f'{text} {currency}'
85
+
86
+
87
+ def spend(usage):
88
+ try:
89
+ raw = usage['raw']
90
+ data = raw.get('spend')
91
+ limit = None
92
+ if isinstance(data, dict) and data.get('enabled') and isinstance(data.get('used'), dict):
93
+ amount = data['used']
94
+ currency = amount['currency']
95
+ used = _money(amount['amount_minor'], currency, amount.get('exponent', 2))
96
+ ceiling = data.get('limit')
97
+ if not isinstance(ceiling, dict) or 'amount_minor' not in ceiling:
98
+ ceiling = data.get('cap')
99
+ if isinstance(ceiling, dict) and 'amount_minor' in ceiling:
100
+ limit = _money(ceiling['amount_minor'], currency, ceiling.get('exponent', 2))
101
+ percent = data.get('percent')
102
+ else:
103
+ data = raw.get('extra_usage')
104
+ if not data or not data.get('is_enabled') or data.get('used_credits') is None:
105
+ return None
106
+ currency, places = data['currency'], data.get('decimal_places', 2)
107
+ used = _money(data['used_credits'], currency, places)
108
+ if data.get('monthly_limit') is not None:
109
+ limit = _money(data['monthly_limit'], currency, places)
110
+ percent = data.get('utilization')
111
+ return {'used': used, 'limit': limit,
112
+ 'percent': float(percent) if limit is not None and percent is not None else None}
113
+ except (KeyError, TypeError, ValueError, AttributeError, ArithmeticError):
114
+ return None
115
+
116
+
117
+ def _spend_title(spending):
118
+ used, limit = spending['used'], spending['limit']
119
+ return f'{used} / {limit}' if limit is not None else used
120
+
121
+
122
+ def spend_line(usage):
123
+ spending = spend(usage)
124
+ if spending is None:
125
+ return None
126
+ used, limit, percent = spending['used'], spending['limit'], spending['percent']
127
+ if limit is None:
128
+ return f'Spend: {used} (no limit)'
129
+ suffix = f' ({percent:.0f}%)' if percent is not None else ''
130
+ return f'Spend: {used} of {limit}{suffix}'
131
+
132
+
133
+ def _report_rows(usage):
134
+ spending = spend_line(usage)
135
+ for key, window in usage_windows(usage):
136
+ if spending is None or window['utilization'] is not None:
137
+ yield f"{window_label(key)}: {pct(window)} used, {when(window['resets_at'])}"
138
+ if spending is not None:
139
+ yield spending
140
+
141
+
142
+ def render_plain(usage):
143
+ out = list(_report_rows(usage))
144
+ if usage['source'] != 'endpoint':
145
+ out.append(f"(from the {usage['source']})")
146
+ return '\n'.join(out)
147
+
148
+
149
+ def _window_parts(usage):
150
+ return [f'{window_label(key, short=True)} {pct(window)}' for key, window in usage_windows(usage)
151
+ if window['utilization'] is not None]
152
+
153
+
154
+ def render_short(usage):
155
+ """Render the same compact line for ``--format short`` and ``--statusline``."""
156
+ model = (usage['raw'].get('model') or {}).get('display_name')
157
+ parts = _window_parts(usage)
158
+ if not parts:
159
+ spending = spend(usage)
160
+ if spending is not None:
161
+ parts.append(_spend_title(spending))
162
+ return ' · '.join(([model] if model else []) + parts)
163
+
164
+
165
+ def _menubar_escape(line):
166
+ line = line.replace('|', '/').replace('\r', ' ').replace('\n', ' ')
167
+ return '- ' + line[1:] if line.startswith('-') else line
168
+
169
+
170
+ def render_menubar(usage, warn=MENUBAR_WARN, crit=MENUBAR_CRIT):
171
+ title = ' · '.join(_window_parts(usage))
172
+ percent = peak(usage)
173
+ if not title:
174
+ spending = spend(usage)
175
+ if spending is not None:
176
+ title, percent = _spend_title(spending), spending['percent']
177
+ icon = ' | sfimage=gauge.with.dots.needle.50percent'
178
+ if percent is not None:
179
+ if percent >= crit:
180
+ icon += ' color=#FF453A'
181
+ elif percent >= warn:
182
+ icon += ' color=#FF9F0A'
183
+ out = [_menubar_escape(title or 'Claude ?') + icon, '---']
184
+ out.extend(_menubar_escape(row) for row in _report_rows(usage))
185
+ for limit in usage['raw'].get('limits') or []:
186
+ model = ((limit.get('scope') or {}).get('model') or {}).get('display_name')
187
+ if model:
188
+ percent = pct({'utilization': limit.get('percent')})
189
+ out.append(_menubar_escape(f"{limit.get('kind', '?')} ({model}): {percent}"))
190
+ out.append(_menubar_escape(f"Source: {usage['source']}") + ' | size=11')
191
+ return '\n'.join(out)
192
+
193
+
194
+ def render_menubar_error(message):
195
+ return 'Claude ⚠ | sfimage=exclamationmark.triangle color=#FF9F0A\n---\n' + _menubar_escape(message)
196
+
197
+
198
+ def render_limits(usage):
199
+ """Render per-limit detail and the weekly surface split, when available."""
200
+ if usage['source'].startswith('status line'):
201
+ return '(details not available from the status-line source)'
202
+ raw = usage['raw']
203
+ out = []
204
+ limits = raw.get('limits') or []
205
+ if limits:
206
+ out.append('%-16s %7s %-10s %-7s %-12s %s' %
207
+ ('kind', 'percent', 'severity', 'active', 'model', 'reset'))
208
+ out.append('-' * 78)
209
+ for limit in limits:
210
+ model = ((limit.get('scope') or {}).get('model') or {}).get('display_name', '')
211
+ out.append('%-16s %7s %-10s %-7s %-12s %s' % (
212
+ limit.get('kind', '?'), pct({'utilization': limit.get('percent')}),
213
+ limit.get('severity', '?'), 'active' if limit.get('is_active') else '',
214
+ model, when(limit.get('resets_at')),
215
+ ))
216
+ rows = (raw.get('seven_day_breakdown') or {}).get('rows') or []
217
+ if rows:
218
+ out.append(', '.join('%s %s' % (row.get('display_name', row.get('key', '?')),
219
+ pct({'utilization': row.get('percent')}))
220
+ for row in sorted(rows, key=lambda row: -(row.get('percent') or 0))))
221
+ return '\n'.join(out)
@@ -1,3 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude-usage-limits
3
+ Version: 0.3.1
4
+ Summary: CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds.
5
+ Author: claude-usage contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
8
+ Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
9
+ Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,swiftbar,menubar,cli
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Utilities
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
1
21
  <h1 align="center">📊 claude-usage</h1>
2
22
 
3
23
  <p align="center">
@@ -25,21 +45,23 @@ login already on your machine. No API key to manage, nothing to configure.
25
45
 
26
46
  The 5-hour window appears when your plan has one and the usage source reports
27
47
  it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
48
+ Usage-based plans such as Enterprise show spend instead of percentages.
28
49
 
29
50
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
30
51
 
31
52
  ```text
32
53
  $ claude-usage
54
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
33
55
  7-day: 59% used, resets Sun 03:00 (in 12h29m)
34
56
  ```
35
57
 
36
58
  ## ✨ Features
37
59
 
38
60
  - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
39
- - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
61
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available, all weekly limits, and spend percentage. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
40
62
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
41
63
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
42
- - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
64
+ - **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
43
65
  - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
44
66
  - **🔋 Zero dependencies** — pure Python standard library.
45
67
  - **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
@@ -60,10 +82,13 @@ its access token fresh.
60
82
  |---|---|
61
83
  | `claude-usage` | Available usage windows and their reset times |
62
84
  | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
63
- | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
85
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
64
86
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
65
87
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
66
- | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
88
+ | `claude-usage --format {plain,json,short,menubar}` | Choose output format (default plain) |
89
+ | `claude-usage --format menubar` | Print SwiftBar/xbar plugin output |
90
+ | `claude-usage --max-age SECONDS` | Set the fresh cache age (default 300, clamped to 30–3600) |
91
+ | `claude-usage --live` | Prefer a fresh status-line cache from an active Claude Code session (Pro/Max) |
67
92
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
68
93
  | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
69
94
  | `claude-usage -V`, `--version` | Print the version |
@@ -77,6 +102,7 @@ only in plain format, keeping JSON machine-readable and short output on one line
77
102
  <summary><b>📊 Example: <code>--all</code></b></summary>
78
103
 
79
104
  ```text
105
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
80
106
  7-day: 60% used, resets Sun 03:00 (in 12h11m)
81
107
  kind percent severity active model reset
82
108
  ------------------------------------------------------------------------------
@@ -101,8 +127,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
101
127
  either threshold trips or no source answers, **2** for an argument error.
102
128
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
103
129
  Missing or null windows do not trigger warnings. `--warn` includes session and
104
- weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
105
- usage windows appear in plain and short output and are checked by `--warn`.
130
+ weekly entries in `limits[]`, and spend percentage when there is a spend limit.
131
+ `--warn-7d` checks only `seven_day`. Populated `seven_day_*` usage windows appear
132
+ in plain and short output and are checked by `--warn`.
106
133
  JSON preserves the source payload, including null fields and weekly share indices.
107
134
 
108
135
  ## 📟 Claude Code status line
@@ -126,17 +153,45 @@ Missing parts are omitted. This mode never looks up credentials or makes a netwo
126
153
  call. It also writes `last-statusline.json`, feeding the documented fallback when
127
154
  the endpoint is unavailable. Invalid input produces no output and exits 0.
128
155
  `claude-usage --format short` gives the same compact format from the normal source
129
- order; endpoint answers usually have no model, so show `7d 59%`.
156
+ order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
157
+
158
+ ## 🖥️ SwiftBar menu bar
159
+
160
+ ```text
161
+ $ claude-usage --format menubar
162
+ 5h 23% · 7d 59% | sfimage=gauge.with.dots.needle.50percent
163
+ ---
164
+ 5-hour: 23% used, resets 17:40 (in 2h13m)
165
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
166
+ weekly_scoped (Fable): 9%
167
+ Source: endpoint | size=11
168
+ ```
169
+
170
+ The title turns orange at 70% and red at 90%. On usage-based plans it shows the
171
+ spend, e.g. `$12.34`. If every source fails, the item shows `Claude ⚠` with the reason.
172
+
173
+ Save `claude-usage.1m.sh` in your SwiftBar plugin folder and make it executable.
174
+
175
+ ```sh
176
+ #!/bin/sh
177
+ claude-usage --format menubar --live --max-age 60
178
+ ```
179
+
180
+ SwiftBar uses a minimal `PATH`, so replace `claude-usage` in the script with its
181
+ absolute path. Set up the Claude Code status line above to get live updates.
130
182
 
131
183
  ## 🤔 How it works
132
184
 
133
185
  Sources are tried in this order:
134
186
 
135
- 1. `last-usage.json` if less than **5 minutes** old.
187
+ 1. `last-usage.json` if less than **5 minutes** old by default.
136
188
  2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
137
189
  3. `last-usage.json` if less than **60 minutes** old.
138
190
  4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
139
191
 
192
+ `--max-age` sets the fresh cache age for step 1 and `--live`. With `--live`, a
193
+ fresh status-line cache is tried first if the endpoint cache is older or missing.
194
+
140
195
  Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
141
196
  atomic. Cached answers at least a minute old show their source and age, e.g.
142
197
  `(from the endpoint, 3 min ago)`; status-line answers always show their age.
@@ -182,11 +237,12 @@ For the protocol and a recipe to rebuild the tool, see
182
237
 
183
238
  - The OAuth usage endpoint is **undocumented and rate limited**; it may change or
184
239
  disappear. The documented status-line path is the fallback.
185
- - Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
186
- after the first API response, and drops individual windows after they reset.
187
- It updates only while a Claude Code session is active and repainting.
188
- - The observed endpoint response came from a Max account. Fields on other plans
189
- may differ; an API key is not a Claude Code OAuth login.
240
+ - Usage-based plans report spend. Subscription plans report usage percentages.
241
+ - Status-line `rate_limits`, which powers `--live`, is **Pro/Max only**. It appears
242
+ after the first API response, drops individual windows after they reset, and
243
+ updates while a Claude Code session is active and repainting.
244
+ - The observed endpoint responses came from Max and Enterprise accounts. Fields on
245
+ other plans may differ; an API key is not a Claude Code OAuth login.
190
246
  - Any running `claude` keeps the access token fresh. This tool deliberately does
191
247
  not implement the undocumented refresh flow.
192
248
  - Use **`/feedback` in Claude Code** to ask Anthropic for an official
@@ -210,7 +210,7 @@ def test_version(capsys):
210
210
  with pytest.raises(SystemExit) as exc:
211
211
  cli.main(["--version"])
212
212
  assert exc.value.code == 0
213
- assert capsys.readouterr().out == "claude-usage 0.2.1\n"
213
+ assert capsys.readouterr().out == "claude-usage 0.3.1\n"
214
214
 
215
215
 
216
216
  def test_help_hides_statusline(capsys):
@@ -267,3 +267,109 @@ def test_weekly_scoped_limit_warning(monkeypatch, percent, code):
267
267
  def test_missing_weekly_window_does_not_warn_at_zero(monkeypatch):
268
268
  monkeypatch.setattr(cli, 'usage', lambda **kwargs: report.shape({}, 'endpoint'))
269
269
  assert cli.main(['--warn', '0', '--warn-7d', '0']) == 0
270
+
271
+
272
+ GAUGE = ' | sfimage=gauge.with.dots.needle.50percent'
273
+ SPEND = {'used': {'amount_minor': 1234, 'currency': 'USD', 'exponent': 2},
274
+ 'limit': None, 'cap': None, 'percent': 0, 'enabled': True}
275
+
276
+
277
+ def test_menubar_layout(monkeypatch):
278
+ raw = dict(ENDPOINT, model={'display_name': 'Fable'}, seven_day_opus={'utilization': 25})
279
+ out = report.shape(raw, 'endpoint, 3 min ago')
280
+ monkeypatch.setattr(report, 'when', lambda iso: 'resets 18:00 (in 1h12m)')
281
+ assert report.render_menubar(out).splitlines() == [
282
+ '7d 59% · 7d opus 25%' + GAUGE,
283
+ '---',
284
+ '7-day: 59% used, resets 18:00 (in 1h12m)',
285
+ '7-day opus: 25% used, resets 18:00 (in 1h12m)',
286
+ 'weekly_scoped (Fable): 6%',
287
+ 'Source: endpoint, 3 min ago | size=11',
288
+ ]
289
+
290
+
291
+ @pytest.mark.parametrize('value,color', [(69, ''), (70, ' color=#FF9F0A'), (90, ' color=#FF453A')])
292
+ def test_menubar_colors(value, color):
293
+ out = report.shape({'seven_day': {'utilization': 10}, 'seven_day_opus': {'utilization': value}}, 'endpoint')
294
+ assert report.peak(out) == value
295
+ assert report.render_menubar(out).splitlines()[0] == f'7d 10% · 7d opus {value}%' + GAUGE + color
296
+
297
+
298
+ def test_menubar_unknown():
299
+ out = report.shape({}, 'endpoint')
300
+ assert report.peak(out) is None
301
+ assert report.render_menubar(out).splitlines()[0] == 'Claude ?' + GAUGE
302
+
303
+
304
+ def test_menubar_escaping():
305
+ raw = {'limits': [{'kind': '--- weekly', 'scope': {'model': {'display_name': 'A\nB | C'}}, 'percent': 9}]}
306
+ out = report.shape(raw, 'read\rme | now')
307
+ assert report.render_menubar(out).splitlines()[-2:] == [
308
+ '- -- weekly (A B / C): 9%', 'Source: read me / now | size=11',
309
+ ]
310
+ assert report.render_menubar_error('--- a | b\nnext').splitlines()[2:] == ['- -- a / b next']
311
+
312
+
313
+ def test_spend_only_report():
314
+ raw = {'seven_day': None, 'seven_day_opus': {'utilization': None}, 'limits': [], 'spend': SPEND,
315
+ 'extra_usage': {'is_enabled': True, 'used_credits': 5678.0, 'currency': 'USD', 'decimal_places': 2}}
316
+ out = report.shape(raw, 'endpoint')
317
+ assert report.spend(out) == {'used': '$12.34', 'limit': None, 'percent': None}
318
+ assert report.render_menubar(out).splitlines() == [
319
+ '$12.34' + GAUGE, '---', 'Spend: $12.34 (no limit)', 'Source: endpoint | size=11',
320
+ ]
321
+ assert report.render_plain(out) == 'Spend: $12.34 (no limit)'
322
+ assert report.render_short(out) == '$12.34'
323
+ assert not report.warning_reached(out, 0)
324
+
325
+
326
+ @pytest.mark.parametrize('field', ['limit', 'cap'])
327
+ def test_spend_limit_report(monkeypatch, capsys, field):
328
+ data = dict(SPEND, used={'amount_minor': 9500, 'currency': 'USD'}, percent=95,
329
+ **{field: {'amount_minor': 100000, 'exponent': 3}})
330
+ out = report.shape({'spend': data}, 'endpoint')
331
+ assert report.render_menubar(out).splitlines() == [
332
+ '$95.00 / $100.00' + GAUGE + ' color=#FF453A', '---', 'Spend: $95.00 of $100.00 (95%)',
333
+ 'Source: endpoint | size=11',
334
+ ]
335
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: out)
336
+ assert cli.main(['--format', 'short', '--warn', '95']) == 1
337
+ assert capsys.readouterr().out == '$95.00 / $100.00\n'
338
+ assert cli.main(['--warn', '96', '--warn-7d', '0']) == 0
339
+
340
+
341
+ def test_extra_usage_spend_in_euros():
342
+ raw = {'spend': None, 'extra_usage': {'is_enabled': True, 'used_credits': 123456.0,
343
+ 'monthly_limit': 200000, 'currency': 'EUR', 'decimal_places': 2, 'utilization': 61.7}}
344
+ out = report.shape(raw, 'endpoint')
345
+ assert report.spend(out) == {'used': '1,234.56 EUR', 'limit': '2,000.00 EUR', 'percent': 61.7}
346
+ assert report.spend_line(out) == 'Spend: 1,234.56 EUR of 2,000.00 EUR (62%)'
347
+
348
+
349
+ def test_weekly_windows_take_menubar_priority_over_spend():
350
+ raw = {'seven_day': {'utilization': 0}, 'spend': dict(SPEND, percent=95, limit=SPEND['used'])}
351
+ out = report.shape(raw, 'endpoint, 3 min ago')
352
+ assert report.render_menubar(out).splitlines() == [
353
+ '7d 0%' + GAUGE, '---', '7-day: 0% used, reset time unknown',
354
+ 'Spend: $12.34 of $12.34 (95%)', 'Source: endpoint, 3 min ago | size=11',
355
+ ]
356
+ assert report.render_plain(out).splitlines()[-2:] == [
357
+ 'Spend: $12.34 of $12.34 (95%)', '(from the endpoint, 3 min ago)',
358
+ ]
359
+ assert report.warning_reached(out, 90)
360
+
361
+
362
+ @pytest.mark.parametrize('raw', [
363
+ {'spend': {'enabled': True, 'used': {}}},
364
+ {'spend': dict(SPEND, used={'amount_minor': [], 'currency': 'USD'})},
365
+ {'spend': dict(SPEND, used={'amount_minor': 1, 'currency': 'USD', 'exponent': 'bad'})},
366
+ {'extra_usage': ['bad']},
367
+ ])
368
+ def test_malformed_spend(raw):
369
+ assert report.spend(report.shape(raw, 'endpoint')) is None
370
+
371
+
372
+ def test_menubar_shows_five_hour_window():
373
+ out = report.render_menubar(report.shape(WITH_SESSION, "endpoint")).splitlines()
374
+ assert out[0] == "5h 23% · 7d 59% | sfimage=gauge.with.dots.needle.50percent"
375
+ assert out[2].startswith("5-hour: 23% used,")
@@ -214,3 +214,62 @@ def test_unreadable_plan_is_ignored(monkeypatch, tmp_path, capsys):
214
214
  assert auth.resolve_plan() is None
215
215
  assert cli.main(['-v']) == 0
216
216
  assert capsys.readouterr().err == 'usage: endpoint\n'
217
+
218
+
219
+ def test_live_prefers_newer_statusline(tmp_path, capsys):
220
+ save(tmp_path, 'last-usage.json', ENDPOINT, 120)
221
+ save(tmp_path, 'last-statusline.json', STATUS, 10)
222
+ assert api.usage(live=False)['source'] == 'endpoint, 2 min ago'
223
+ assert api.usage(live=True, verbose=True)['source'] == 'status line, 0 min ago'
224
+ assert capsys.readouterr().err == 'usage: status line, 0 min ago\n'
225
+
226
+
227
+ def test_live_ignores_older_statusline(tmp_path):
228
+ save(tmp_path, 'last-usage.json', ENDPOINT, 120)
229
+ save(tmp_path, 'last-statusline.json', STATUS, 180)
230
+ assert api.usage(live=True)['source'] == 'endpoint, 2 min ago'
231
+
232
+
233
+ def test_live_requires_rate_limits(tmp_path):
234
+ save(tmp_path, 'last-usage.json', ENDPOINT, 120)
235
+ save(tmp_path, 'last-statusline.json', {'model': STATUS['model']}, 10)
236
+ assert api.usage(live=True)['source'] == 'endpoint, 2 min ago'
237
+
238
+
239
+ def test_cli_live_without_endpoint_cache(tmp_path, capsys):
240
+ save(tmp_path, 'last-statusline.json', STATUS, 10)
241
+ assert cli.main(['--live', '--max-age', '60', '--format', 'menubar']) == 0
242
+ assert capsys.readouterr().out.endswith('Source: status line, 0 min ago | size=11\n')
243
+
244
+
245
+ def test_max_age_forces_one_request(monkeypatch, tmp_path):
246
+ save(tmp_path, 'last-usage.json', ENDPOINT, 90)
247
+ save(tmp_path, 'last-statusline.json', STATUS, 75)
248
+ requests = []
249
+ def get(*args):
250
+ requests.append(args)
251
+ return ENDPOINT
252
+ monkeypatch.setattr(api, '_get_json', get)
253
+ assert api.usage(fresh=60, live=True)['source'] == 'endpoint'
254
+ assert len(requests) == 1
255
+
256
+
257
+ def test_max_age_clamps_to_minimum(tmp_path):
258
+ save(tmp_path, 'last-usage.json', ENDPOINT, 20)
259
+ assert api.usage(fresh=1)['source'] == 'endpoint'
260
+
261
+
262
+ def test_max_age_clamps_to_maximum(monkeypatch, tmp_path):
263
+ save(tmp_path, 'last-usage.json', ENDPOINT, 3700)
264
+ monkeypatch.setattr(api, '_get_json', lambda *args: ENDPOINT)
265
+ assert api.usage(fresh=4000)['source'] == 'endpoint'
266
+
267
+
268
+ def test_cli_menubar_when_all_sources_fail(monkeypatch, capsys):
269
+ monkeypatch.setattr(api, '_get_json', rate_limited)
270
+ assert cli.main(['--live', '--format', 'menubar']) == 1
271
+ out, err = capsys.readouterr()
272
+ reason = ('no saved endpoint answer yet; HTTP 429 from ' + api.URL +
273
+ '; no status-line cache yet (is the status line set to `claude-usage --statusline`?)')
274
+ assert err == f'claude-usage: {reason}\n'
275
+ assert out == f'Claude ⚠ | sfimage=exclamationmark.triangle color=#FF9F0A\n---\n{reason}\n'
@@ -1,111 +0,0 @@
1
- """Turn endpoint and status-line payloads into compact usage reports."""
2
-
3
- from datetime import datetime, timezone
4
-
5
-
6
- def shape(data, source):
7
- """Normalize usage windows and retain the untouched payload for JSON output."""
8
- if not isinstance(data, dict):
9
- raise ValueError("usage data is not a JSON object")
10
- out = {"source": source, "raw": data}
11
- status = source.startswith("status line")
12
- windows = (data.get("rate_limits") or {}) if status else data
13
- keys = ["seven_day"] + sorted(key for key, value in windows.items()
14
- if key.startswith("seven_day_") and isinstance(value, dict)
15
- and ("utilization" in value or "used_percentage" in value))
16
- if isinstance(windows.get("five_hour"), dict):
17
- keys.insert(0, "five_hour")
18
- for key in keys:
19
- window = windows.get(key) or {}
20
- reset = window.get("resets_at")
21
- if status and reset is not None:
22
- reset = datetime.fromtimestamp(reset, timezone.utc).isoformat()
23
- used = window.get("used_percentage" if status else "utilization")
24
- out[key] = {"utilization": float(used) if used is not None else None,
25
- "resets_at": reset}
26
- return out
27
-
28
-
29
- def usage_windows(usage):
30
- """Yield normalized usage windows in display order."""
31
- return ((key, window) for key, window in usage.items()
32
- if key in ("five_hour", "seven_day") or key.startswith("seven_day_"))
33
-
34
-
35
- def window_label(key, short=False):
36
- if key == "five_hour":
37
- return "5h" if short else "5-hour"
38
- label = "7d" if short else "7-day"
39
- suffix = key[len("seven_day"):].strip("_").replace("_", " ")
40
- return f"{label} {suffix}" if suffix else label
41
-
42
-
43
- def warning_reached(usage, threshold):
44
- """Check normalized windows and the endpoint's session and weekly limits."""
45
- values = [window['utilization'] for _, window in usage_windows(usage)]
46
- values.extend(limit.get('percent') for limit in usage['raw'].get('limits') or []
47
- if limit.get('group') in ('session', 'weekly') or limit.get('kind') == 'session'
48
- or limit.get('kind', '').startswith('weekly_'))
49
- return any(value is not None and float(value) >= threshold for value in values)
50
-
51
-
52
- def when(iso):
53
- if not iso:
54
- return "reset time unknown"
55
- t = datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone()
56
- now = datetime.now(t.tzinfo)
57
- mins = max(0, int((t - now).total_seconds() // 60))
58
- h, m = divmod(mins, 60)
59
- span = f"{h}h{m:02d}m" if h else f"{m}m"
60
- day = "" if t.date() == now.date() else t.strftime("%a ")
61
- return f"resets {day}{t:%H:%M} (in {span})"
62
-
63
-
64
- def pct(window):
65
- used = window.get("utilization")
66
- return "?" if used is None else f"{used:.0f}%"
67
-
68
-
69
- def render_plain(usage):
70
- out = []
71
- for key, window in usage_windows(usage):
72
- out.append(f"{window_label(key)}: {pct(window)} used, {when(window['resets_at'])}")
73
- if usage['source'] != 'endpoint':
74
- out.append(f"(from the {usage['source']})")
75
- return '\n'.join(out)
76
-
77
-
78
- def render_short(usage):
79
- """Render the same compact line for ``--format short`` and ``--statusline``."""
80
- model = (usage['raw'].get('model') or {}).get('display_name')
81
- parts = [model] if model else []
82
- for key, window in usage_windows(usage):
83
- if window['utilization'] is not None:
84
- parts.append(f"{window_label(key, short=True)} {pct(window)}")
85
- return ' · '.join(parts)
86
-
87
-
88
- def render_limits(usage):
89
- """Render per-limit detail and the weekly surface split, when available."""
90
- if usage['source'].startswith('status line'):
91
- return '(details not available from the status-line source)'
92
- raw = usage['raw']
93
- out = []
94
- limits = raw.get('limits') or []
95
- if limits:
96
- out.append('%-16s %7s %-10s %-7s %-12s %s' %
97
- ('kind', 'percent', 'severity', 'active', 'model', 'reset'))
98
- out.append('-' * 78)
99
- for limit in limits:
100
- model = ((limit.get('scope') or {}).get('model') or {}).get('display_name', '')
101
- out.append('%-16s %7s %-10s %-7s %-12s %s' % (
102
- limit.get('kind', '?'), pct({'utilization': limit.get('percent')}),
103
- limit.get('severity', '?'), 'active' if limit.get('is_active') else '',
104
- model, when(limit.get('resets_at')),
105
- ))
106
- rows = (raw.get('seven_day_breakdown') or {}).get('rows') or []
107
- if rows:
108
- out.append(', '.join('%s %s' % (row.get('display_name', row.get('key', '?')),
109
- pct({'utilization': row.get('percent')}))
110
- for row in sorted(rows, key=lambda row: -(row.get('percent') or 0))))
111
- return '\n'.join(out)