claude-usage-limits 0.2.0__tar.gz → 0.3.0__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.0/src/claude_usage_limits.egg-info → claude_usage_limits-0.3.0}/PKG-INFO +46 -24
  2. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/README.md +44 -22
  3. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/pyproject.toml +2 -2
  4. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage/__init__.py +1 -1
  5. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage/api.py +25 -5
  6. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage/auth.py +36 -12
  7. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage/cli.py +24 -9
  8. claude_usage_limits-0.3.0/src/claude_usage/report.py +221 -0
  9. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0/src/claude_usage_limits.egg-info}/PKG-INFO +46 -24
  10. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/tests/test_report.py +153 -38
  11. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/tests/test_sources.py +121 -2
  12. claude_usage_limits-0.2.0/src/claude_usage/report.py +0 -126
  13. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/LICENSE +0 -0
  14. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/setup.cfg +0 -0
  15. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage/__main__.py +0 -0
  16. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
  17. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
  18. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
  19. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
  20. {claude_usage_limits-0.2.0 → claude_usage_limits-0.3.0}/tests/test_auth.py +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.2.0
4
- Summary: CLI for Claude subscription weekly usage and model limits, with status-line output and warning thresholds.
3
+ Version: 0.3.0
4
+ Summary: CLI for Claude subscription usage and model limits, with status-line output 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
@@ -39,10 +39,14 @@ Dynamic: license-file
39
39
  ---
40
40
 
41
41
  Claude Code shows your subscription limits only in the interactive `/usage`
42
- screen. **`claude-usage` gives you the weekly usage and model limits from the shell** — for
42
+ screen. **`claude-usage` gives you subscription usage and model limits from the shell** — for
43
43
  scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
44
44
  login already on your machine. No API key to manage, nothing to configure.
45
45
 
46
+ The 5-hour window appears when your plan has one and the usage source reports
47
+ it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
48
+ Usage-based plans such as Enterprise show spend instead of percentages.
49
+
46
50
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
47
51
 
48
52
  ```text
@@ -52,11 +56,11 @@ $ claude-usage
52
56
 
53
57
  ## ✨ Features
54
58
 
55
- - **Weekly limits, one command** — 7-day usage, populated weekly variants, and local reset times.
56
- - **🚦 Thresholds for scripts** — `--warn [N]` checks all weekly limits; `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
59
+ - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
60
+ - **🚦 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%.
57
61
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
58
62
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
59
- - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
63
+ - **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
60
64
  - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
61
65
  - **🔋 Zero dependencies** — pure Python standard library.
62
66
  - **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
@@ -75,14 +79,17 @@ its access token fresh.
75
79
 
76
80
  | Command | What it does |
77
81
  |---|---|
78
- | `claude-usage` | Weekly usage windows and their reset times |
79
- | `claude-usage --json` | Usage JSON from whichever source answered, with retired session limits removed; alias for `--format json` |
80
- | `claude-usage --warn [N]` | Exit 1 when any weekly window or weekly model limit reaches N% (default 70) |
82
+ | `claude-usage` | Available usage windows and their reset times |
83
+ | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
84
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
81
85
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
82
86
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
83
- | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
87
+ | `claude-usage --format {plain,json,short,menubar}` | Choose output format (default plain) |
88
+ | `claude-usage --format menubar` | Print SwiftBar/xbar plugin output |
89
+ | `claude-usage --max-age SECONDS` | Set the fresh cache age (default 300, clamped to 30–3600) |
90
+ | `claude-usage --live` | Prefer a fresh status-line cache from an active Claude Code session (Pro/Max) |
84
91
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
85
- | `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
92
+ | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
86
93
  | `claude-usage -V`, `--version` | Print the version |
87
94
  | `claude-usage -h`, `--help` | Show help |
88
95
 
@@ -117,12 +124,11 @@ claude-usage --json
117
124
  The usual output is always printed. Exit codes: **0** for success, **1** when
118
125
  either threshold trips or no source answers, **2** for an argument error.
119
126
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
120
- Missing or null windows do not trigger warnings. `--warn` includes weekly model
121
- caps in `limits[]`; `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
122
- usage windows appear in plain and short output and are checked by `--warn`.
123
- JSON retains other fields from the source, but removes retired session limits
124
- from both endpoint and status-line payloads, including older cached answers.
125
- Weekly share indices are adjusted when obsolete detail entries are removed.
127
+ Missing or null windows do not trigger warnings. `--warn` includes session and
128
+ weekly entries in `limits[]`, and spend percentage when there is a spend limit.
129
+ `--warn-7d` checks only `seven_day`. Populated `seven_day_*` usage windows appear
130
+ in plain and short output and are checked by `--warn`.
131
+ JSON preserves the source payload, including null fields and weekly share indices.
126
132
 
127
133
  ## 📟 Claude Code status line
128
134
 
@@ -138,7 +144,7 @@ settings):
138
144
  Claude Code pipes its documented status JSON to the command on each repaint:
139
145
 
140
146
  ```text
141
- Fable 5.1 · 7d 59%
147
+ Fable 5.1 · 5h 25% · 7d 59%
142
148
  ```
143
149
 
144
150
  Missing parts are omitted. This mode never looks up credentials or makes a network
@@ -147,15 +153,30 @@ the endpoint is unavailable. Invalid input produces no output and exits 0.
147
153
  `claude-usage --format short` gives the same compact format from the normal source
148
154
  order; endpoint answers usually have no model, so show `7d 59%`.
149
155
 
156
+ ## 🖥️ SwiftBar menu bar
157
+
158
+ Save `claude-usage.1m.sh` in your SwiftBar plugin folder and make it executable.
159
+
160
+ ```sh
161
+ #!/bin/sh
162
+ claude-usage --format menubar --live --max-age 60
163
+ ```
164
+
165
+ SwiftBar uses a minimal `PATH`, so replace `claude-usage` in the script with its
166
+ absolute path. Set up the Claude Code status line above to get live updates.
167
+
150
168
  ## 🤔 How it works
151
169
 
152
170
  Sources are tried in this order:
153
171
 
154
- 1. `last-usage.json` if less than **5 minutes** old.
172
+ 1. `last-usage.json` if less than **5 minutes** old by default.
155
173
  2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
156
174
  3. `last-usage.json` if less than **60 minutes** old.
157
175
  4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
158
176
 
177
+ `--max-age` sets the fresh cache age for step 1 and `--live`. With `--live`, a
178
+ fresh status-line cache is tried first if the endpoint cache is older or missing.
179
+
159
180
  Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
160
181
  atomic. Cached answers at least a minute old show their source and age, e.g.
161
182
  `(from the endpoint, 3 min ago)`; status-line answers always show their age.
@@ -201,11 +222,12 @@ For the protocol and a recipe to rebuild the tool, see
201
222
 
202
223
  - The OAuth usage endpoint is **undocumented and rate limited**; it may change or
203
224
  disappear. The documented status-line path is the fallback.
204
- - Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
205
- after the first API response, and drops individual windows after they reset.
206
- It updates only while a Claude Code session is active and repainting.
207
- - The observed endpoint response came from a Max account. Fields on other plans
208
- may differ; an API key is not a Claude Code OAuth login.
225
+ - Usage-based plans report spend. Subscription plans report usage percentages.
226
+ - Status-line `rate_limits`, which powers `--live`, is **Pro/Max only**. It appears
227
+ after the first API response, drops individual windows after they reset, and
228
+ updates while a Claude Code session is active and repainting.
229
+ - The observed endpoint responses came from Max and Enterprise accounts. Fields on
230
+ other plans may differ; an API key is not a Claude Code OAuth login.
209
231
  - Any running `claude` keeps the access token fresh. This tool deliberately does
210
232
  not implement the undocumented refresh flow.
211
233
  - Use **`/feedback` in Claude Code** to ask Anthropic for an official
@@ -19,10 +19,14 @@
19
19
  ---
20
20
 
21
21
  Claude Code shows your subscription limits only in the interactive `/usage`
22
- screen. **`claude-usage` gives you the weekly usage and model limits from the shell** — for
22
+ screen. **`claude-usage` gives you subscription usage and model limits from the shell** — for
23
23
  scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
24
24
  login already on your machine. No API key to manage, nothing to configure.
25
25
 
26
+ The 5-hour window appears when your plan has one and the usage source reports
27
+ it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
28
+ Usage-based plans such as Enterprise show spend instead of percentages.
29
+
26
30
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
27
31
 
28
32
  ```text
@@ -32,11 +36,11 @@ $ claude-usage
32
36
 
33
37
  ## ✨ Features
34
38
 
35
- - **Weekly limits, one command** — 7-day usage, populated weekly variants, and local reset times.
36
- - **🚦 Thresholds for scripts** — `--warn [N]` checks all weekly limits; `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
39
+ - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
40
+ - **🚦 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%.
37
41
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
38
42
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
39
- - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
43
+ - **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
40
44
  - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
41
45
  - **🔋 Zero dependencies** — pure Python standard library.
42
46
  - **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
@@ -55,14 +59,17 @@ its access token fresh.
55
59
 
56
60
  | Command | What it does |
57
61
  |---|---|
58
- | `claude-usage` | Weekly usage windows and their reset times |
59
- | `claude-usage --json` | Usage JSON from whichever source answered, with retired session limits removed; alias for `--format json` |
60
- | `claude-usage --warn [N]` | Exit 1 when any weekly window or weekly model limit reaches N% (default 70) |
62
+ | `claude-usage` | Available usage windows and their reset times |
63
+ | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
64
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
61
65
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
62
66
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
63
- | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
67
+ | `claude-usage --format {plain,json,short,menubar}` | Choose output format (default plain) |
68
+ | `claude-usage --format menubar` | Print SwiftBar/xbar plugin output |
69
+ | `claude-usage --max-age SECONDS` | Set the fresh cache age (default 300, clamped to 30–3600) |
70
+ | `claude-usage --live` | Prefer a fresh status-line cache from an active Claude Code session (Pro/Max) |
64
71
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
65
- | `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
72
+ | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
66
73
  | `claude-usage -V`, `--version` | Print the version |
67
74
  | `claude-usage -h`, `--help` | Show help |
68
75
 
@@ -97,12 +104,11 @@ claude-usage --json
97
104
  The usual output is always printed. Exit codes: **0** for success, **1** when
98
105
  either threshold trips or no source answers, **2** for an argument error.
99
106
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
100
- Missing or null windows do not trigger warnings. `--warn` includes weekly model
101
- caps in `limits[]`; `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
102
- usage windows appear in plain and short output and are checked by `--warn`.
103
- JSON retains other fields from the source, but removes retired session limits
104
- from both endpoint and status-line payloads, including older cached answers.
105
- Weekly share indices are adjusted when obsolete detail entries are removed.
107
+ Missing or null windows do not trigger warnings. `--warn` includes session and
108
+ weekly entries in `limits[]`, and spend percentage when there is a spend limit.
109
+ `--warn-7d` checks only `seven_day`. Populated `seven_day_*` usage windows appear
110
+ in plain and short output and are checked by `--warn`.
111
+ JSON preserves the source payload, including null fields and weekly share indices.
106
112
 
107
113
  ## 📟 Claude Code status line
108
114
 
@@ -118,7 +124,7 @@ settings):
118
124
  Claude Code pipes its documented status JSON to the command on each repaint:
119
125
 
120
126
  ```text
121
- Fable 5.1 · 7d 59%
127
+ Fable 5.1 · 5h 25% · 7d 59%
122
128
  ```
123
129
 
124
130
  Missing parts are omitted. This mode never looks up credentials or makes a network
@@ -127,15 +133,30 @@ the endpoint is unavailable. Invalid input produces no output and exits 0.
127
133
  `claude-usage --format short` gives the same compact format from the normal source
128
134
  order; endpoint answers usually have no model, so show `7d 59%`.
129
135
 
136
+ ## 🖥️ SwiftBar menu bar
137
+
138
+ Save `claude-usage.1m.sh` in your SwiftBar plugin folder and make it executable.
139
+
140
+ ```sh
141
+ #!/bin/sh
142
+ claude-usage --format menubar --live --max-age 60
143
+ ```
144
+
145
+ SwiftBar uses a minimal `PATH`, so replace `claude-usage` in the script with its
146
+ absolute path. Set up the Claude Code status line above to get live updates.
147
+
130
148
  ## 🤔 How it works
131
149
 
132
150
  Sources are tried in this order:
133
151
 
134
- 1. `last-usage.json` if less than **5 minutes** old.
152
+ 1. `last-usage.json` if less than **5 minutes** old by default.
135
153
  2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
136
154
  3. `last-usage.json` if less than **60 minutes** old.
137
155
  4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
138
156
 
157
+ `--max-age` sets the fresh cache age for step 1 and `--live`. With `--live`, a
158
+ fresh status-line cache is tried first if the endpoint cache is older or missing.
159
+
139
160
  Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
140
161
  atomic. Cached answers at least a minute old show their source and age, e.g.
141
162
  `(from the endpoint, 3 min ago)`; status-line answers always show their age.
@@ -181,11 +202,12 @@ For the protocol and a recipe to rebuild the tool, see
181
202
 
182
203
  - The OAuth usage endpoint is **undocumented and rate limited**; it may change or
183
204
  disappear. The documented status-line path is the fallback.
184
- - Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
185
- after the first API response, and drops individual windows after they reset.
186
- It updates only while a Claude Code session is active and repainting.
187
- - The observed endpoint response came from a Max account. Fields on other plans
188
- may differ; an API key is not a Claude Code OAuth login.
205
+ - Usage-based plans report spend. Subscription plans report usage percentages.
206
+ - Status-line `rate_limits`, which powers `--live`, is **Pro/Max only**. It appears
207
+ after the first API response, drops individual windows after they reset, and
208
+ updates while a Claude Code session is active and repainting.
209
+ - The observed endpoint responses came from Max and Enterprise accounts. Fields on
210
+ other plans may differ; an API key is not a Claude Code OAuth login.
189
211
  - Any running `claude` keeps the access token fresh. This tool deliberately does
190
212
  not implement the undocumented refresh flow.
191
213
  - Use **`/feedback` in Claude Code** to ask Anthropic for an official
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "claude-usage-limits"
7
- version = "0.2.0"
8
- description = "CLI for Claude subscription weekly usage and model limits, with status-line output and warning thresholds."
7
+ version = "0.3.0"
8
+ description = "CLI for Claude subscription usage and model limits, with status-line output and warning thresholds."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE"]
@@ -1,3 +1,3 @@
1
1
  """claude-usage: read your Claude subscription rate-limit windows."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
@@ -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:
@@ -2,7 +2,7 @@
2
2
 
3
3
  Priority: explicit environment override, macOS Keychain, credentials JSON.
4
4
  Only Claude Code refreshes tokens; this tool never writes credentials. Errors
5
- and verbose notes describe sources without exposing credential contents.
5
+ and verbose notes can identify the source and plan without exposing tokens.
6
6
  """
7
7
 
8
8
  import json
@@ -23,7 +23,7 @@ def config_dir():
23
23
  return Path(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude"))
24
24
 
25
25
 
26
- def _token_from_credentials(creds):
26
+ def _oauth_from_credentials(creds):
27
27
  try:
28
28
  oauth = creds.get("claudeAiOauth") or {}
29
29
  token = oauth.get("accessToken")
@@ -35,7 +35,7 @@ def _token_from_credentials(creds):
35
35
  raise CredentialsNotFound("credentials hold no OAuth access token; run `claude` once to log in")
36
36
  if expired:
37
37
  raise CredentialsNotFound("the access token has expired; open `claude` so it refreshes")
38
- return token
38
+ return oauth
39
39
 
40
40
 
41
41
  def _log(verbose, source):
@@ -43,12 +43,10 @@ def _log(verbose, source):
43
43
  print("credentials: " + source, file=sys.stderr)
44
44
 
45
45
 
46
- def resolve_token(config=None, verbose=False):
47
- """Return an access token, trying the file if the keychain is unavailable."""
46
+ def _resolve_credentials(config):
48
47
  override = os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")
49
48
  if override:
50
- _log(verbose, "CLAUDE_CODE_OAUTH_TOKEN")
51
- return override
49
+ return override, None, "CLAUDE_CODE_OAUTH_TOKEN"
52
50
 
53
51
  keychain_error = None
54
52
  if sys.platform == "darwin":
@@ -58,9 +56,8 @@ def resolve_token(config=None, verbose=False):
58
56
  capture_output=True, text=True, timeout=15,
59
57
  )
60
58
  if out.returncode == 0:
61
- token = _token_from_credentials(json.loads(out.stdout))
62
- _log(verbose, "macOS keychain")
63
- return token
59
+ oauth = _oauth_from_credentials(json.loads(out.stdout))
60
+ return oauth["accessToken"], oauth, "macOS keychain"
64
61
  except CredentialsNotFound as exc:
65
62
  keychain_error = exc
66
63
  except (OSError, ValueError, subprocess.SubprocessError):
@@ -74,6 +71,33 @@ def resolve_token(config=None, verbose=False):
74
71
  if keychain_error is not None:
75
72
  raise keychain_error from None
76
73
  raise CredentialsNotFound("no readable Claude Code credentials file; run `claude` once to log in") from None
77
- token = _token_from_credentials(creds)
78
- _log(verbose, "credentials file")
74
+ oauth = _oauth_from_credentials(creds)
75
+ return oauth["accessToken"], oauth, "credentials file"
76
+
77
+
78
+ def resolve_token(config=None, verbose=False):
79
+ """Return an access token, trying the file if the keychain is unavailable."""
80
+ token, _, source = _resolve_credentials(config)
81
+ _log(verbose, source)
79
82
  return token
83
+
84
+
85
+ def resolve_plan(config=None):
86
+ """Return the plan and optional tier for verbose diagnostics."""
87
+ try:
88
+ _, oauth, _ = _resolve_credentials(config)
89
+ if oauth is None:
90
+ return None
91
+ subscription = oauth.get("subscriptionType") or ""
92
+ tier = oauth.get("rateLimitTier") or ""
93
+ if not isinstance(subscription, str) or not isinstance(tier, str):
94
+ return None
95
+ if "max_20x" in tier:
96
+ plan = "Ultra"
97
+ elif "max_5x" in tier:
98
+ plan = "Max"
99
+ else:
100
+ plan = subscription.title() or "unknown"
101
+ return f"{plan} ({tier})" if tier else plan
102
+ except Exception:
103
+ return None
@@ -5,29 +5,36 @@ import json
5
5
  import sys
6
6
 
7
7
  from . import __version__
8
- from .api import usage, write_cache
9
- from .auth import config_dir
10
- from .report import render_limits, render_plain, render_short, shape, warning_reached
8
+ from .api import FRESH, MAX_AGE, MIN_FRESH, usage, write_cache
9
+ from .auth import config_dir, resolve_plan
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():
14
15
  p = argparse.ArgumentParser(
15
16
  prog='claude-usage',
16
- description="Show Claude subscription rate limits: weekly usage and model limits.",
17
+ description="Show Claude subscription rate limits, including the 5-hour window when available.",
17
18
  )
18
19
  p.add_argument('--json', action='store_const', dest='format', const='json',
19
- help='print usage JSON without retired session limits (alias for --format json)')
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='exit 1 when any weekly limit is 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)')
22
24
  p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
23
25
  help='exit 1 when the 7-day window is at or above N%% (default 70)')
24
26
  p.add_argument('--all', action='store_true',
25
27
  help='add per-limit details and the weekly surface breakdown (plain format)')
26
- p.add_argument('--format', choices=('plain', 'json', 'short'), default='plain',
28
+ p.add_argument('--format', choices=('plain', 'json', 'short', 'menubar'), default='plain',
27
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)')
28
35
  p.add_argument('--statusline', action='store_true', help=argparse.SUPPRESS)
29
36
  p.add_argument('-v', '--verbose', action='store_true',
30
- help='log credential and usage sources to stderr')
37
+ help='log credential and usage sources and the plan to stderr')
31
38
  p.add_argument('-V', '--version', action='version', version='claude-usage %s' % __version__)
32
39
  return p
33
40
 
@@ -50,12 +57,18 @@ def main(argv=None):
50
57
  if args.statusline:
51
58
  return statusline()
52
59
  try:
53
- out = usage(verbose=args.verbose)
60
+ out = usage(verbose=args.verbose, fresh=args.max_age, live=args.live)
61
+ if args.verbose:
62
+ plan = resolve_plan()
63
+ if plan is not None:
64
+ print('plan: ' + plan, file=sys.stderr)
54
65
  if args.format == 'json':
55
66
  json.dump(out['raw'], sys.stdout, indent=1)
56
67
  print()
57
68
  elif args.format == 'short':
58
69
  print(render_short(out))
70
+ elif args.format == 'menubar':
71
+ print(render_menubar(out))
59
72
  else:
60
73
  print(render_plain(out))
61
74
  if args.all:
@@ -63,6 +76,8 @@ def main(argv=None):
63
76
  if details:
64
77
  print(details)
65
78
  except (RuntimeError, OSError, ValueError, TypeError, AttributeError, OverflowError) as exc:
79
+ if args.format == 'menubar':
80
+ print(render_menubar_error(str(exc)))
66
81
  print('claude-usage: ' + str(exc), file=sys.stderr)
67
82
  return 1
68
83
  if args.warn is not None and warning_reached(out, args.warn):