claude-usage-limits 0.2.1__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.
- {claude_usage_limits-0.2.1/src/claude_usage_limits.egg-info → claude_usage_limits-0.3.0}/PKG-INFO +34 -13
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/README.md +33 -12
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/pyproject.toml +1 -1
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage/__init__.py +1 -1
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage/api.py +25 -5
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage/cli.py +16 -6
- claude_usage_limits-0.3.0/src/claude_usage/report.py +221 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0/src/claude_usage_limits.egg-info}/PKG-INFO +34 -13
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/tests/test_report.py +107 -1
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/tests/test_sources.py +59 -0
- claude_usage_limits-0.2.1/src/claude_usage/report.py +0 -111
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/LICENSE +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/setup.cfg +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage/__main__.py +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage/auth.py +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
- {claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/tests/test_auth.py +0 -0
{claude_usage_limits-0.2.1/src/claude_usage_limits.egg-info → claude_usage_limits-0.3.0}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: claude-usage-limits
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
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
|
|
@@ -45,6 +45,7 @@ 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
|
|
|
@@ -56,10 +57,10 @@ $ claude-usage
|
|
|
56
57
|
## ✨ Features
|
|
57
58
|
|
|
58
59
|
- **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
|
|
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%.
|
|
60
61
|
- **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
|
|
61
62
|
- **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
|
|
62
|
-
- **🧾 Plain, JSON, or
|
|
63
|
+
- **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
|
|
63
64
|
- **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
|
|
64
65
|
- **🔋 Zero dependencies** — pure Python standard library.
|
|
65
66
|
- **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
|
|
@@ -80,10 +81,13 @@ its access token fresh.
|
|
|
80
81
|
|---|---|
|
|
81
82
|
| `claude-usage` | Available usage windows and their reset times |
|
|
82
83
|
| `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
|
|
84
|
+
| `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
|
|
84
85
|
| `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
|
|
85
86
|
| `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) |
|
|
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) |
|
|
87
91
|
| `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
|
|
88
92
|
| `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
|
|
89
93
|
| `claude-usage -V`, `--version` | Print the version |
|
|
@@ -121,8 +125,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
|
|
|
121
125
|
either threshold trips or no source answers, **2** for an argument error.
|
|
122
126
|
The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
|
|
123
127
|
Missing or null windows do not trigger warnings. `--warn` includes session and
|
|
124
|
-
weekly entries in `limits[]
|
|
125
|
-
|
|
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`.
|
|
126
131
|
JSON preserves the source payload, including null fields and weekly share indices.
|
|
127
132
|
|
|
128
133
|
## 📟 Claude Code status line
|
|
@@ -148,15 +153,30 @@ the endpoint is unavailable. Invalid input produces no output and exits 0.
|
|
|
148
153
|
`claude-usage --format short` gives the same compact format from the normal source
|
|
149
154
|
order; endpoint answers usually have no model, so show `7d 59%`.
|
|
150
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
|
+
|
|
151
168
|
## 🤔 How it works
|
|
152
169
|
|
|
153
170
|
Sources are tried in this order:
|
|
154
171
|
|
|
155
|
-
1. `last-usage.json` if less than **5 minutes** old.
|
|
172
|
+
1. `last-usage.json` if less than **5 minutes** old by default.
|
|
156
173
|
2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
|
|
157
174
|
3. `last-usage.json` if less than **60 minutes** old.
|
|
158
175
|
4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
|
|
159
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
|
+
|
|
160
180
|
Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
|
|
161
181
|
atomic. Cached answers at least a minute old show their source and age, e.g.
|
|
162
182
|
`(from the endpoint, 3 min ago)`; status-line answers always show their age.
|
|
@@ -202,11 +222,12 @@ For the protocol and a recipe to rebuild the tool, see
|
|
|
202
222
|
|
|
203
223
|
- The OAuth usage endpoint is **undocumented and rate limited**; it may change or
|
|
204
224
|
disappear. The documented status-line path is the fallback.
|
|
205
|
-
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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.
|
|
210
231
|
- Any running `claude` keeps the access token fresh. This tool deliberately does
|
|
211
232
|
not implement the undocumented refresh flow.
|
|
212
233
|
- Use **`/feedback` in Claude Code** to ask Anthropic for an official
|
|
@@ -25,6 +25,7 @@ login already on your machine. No API key to manage, nothing to configure.
|
|
|
25
25
|
|
|
26
26
|
The 5-hour window appears when your plan has one and the usage source reports
|
|
27
27
|
it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
|
|
28
|
+
Usage-based plans such as Enterprise show spend instead of percentages.
|
|
28
29
|
|
|
29
30
|
**Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
|
|
30
31
|
|
|
@@ -36,10 +37,10 @@ $ claude-usage
|
|
|
36
37
|
## ✨ Features
|
|
37
38
|
|
|
38
39
|
- **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
|
|
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%.
|
|
40
41
|
- **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
|
|
41
42
|
- **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
|
|
42
|
-
- **🧾 Plain, JSON, or
|
|
43
|
+
- **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
|
|
43
44
|
- **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
|
|
44
45
|
- **🔋 Zero dependencies** — pure Python standard library.
|
|
45
46
|
- **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
|
|
@@ -60,10 +61,13 @@ its access token fresh.
|
|
|
60
61
|
|---|---|
|
|
61
62
|
| `claude-usage` | Available usage windows and their reset times |
|
|
62
63
|
| `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
|
|
64
|
+
| `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
|
|
64
65
|
| `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
|
|
65
66
|
| `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) |
|
|
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) |
|
|
67
71
|
| `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
|
|
68
72
|
| `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
|
|
69
73
|
| `claude-usage -V`, `--version` | Print the version |
|
|
@@ -101,8 +105,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
|
|
|
101
105
|
either threshold trips or no source answers, **2** for an argument error.
|
|
102
106
|
The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
|
|
103
107
|
Missing or null windows do not trigger warnings. `--warn` includes session and
|
|
104
|
-
weekly entries in `limits[]
|
|
105
|
-
|
|
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`.
|
|
106
111
|
JSON preserves the source payload, including null fields and weekly share indices.
|
|
107
112
|
|
|
108
113
|
## 📟 Claude Code status line
|
|
@@ -128,15 +133,30 @@ the endpoint is unavailable. Invalid input produces no output and exits 0.
|
|
|
128
133
|
`claude-usage --format short` gives the same compact format from the normal source
|
|
129
134
|
order; endpoint answers usually have no model, so show `7d 59%`.
|
|
130
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
|
+
|
|
131
148
|
## 🤔 How it works
|
|
132
149
|
|
|
133
150
|
Sources are tried in this order:
|
|
134
151
|
|
|
135
|
-
1. `last-usage.json` if less than **5 minutes** old.
|
|
152
|
+
1. `last-usage.json` if less than **5 minutes** old by default.
|
|
136
153
|
2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
|
|
137
154
|
3. `last-usage.json` if less than **60 minutes** old.
|
|
138
155
|
4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
|
|
139
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
|
+
|
|
140
160
|
Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
|
|
141
161
|
atomic. Cached answers at least a minute old show their source and age, e.g.
|
|
142
162
|
`(from the endpoint, 3 min ago)`; status-line answers always show their age.
|
|
@@ -182,11 +202,12 @@ For the protocol and a recipe to rebuild the tool, see
|
|
|
182
202
|
|
|
183
203
|
- The OAuth usage endpoint is **undocumented and rate limited**; it may change or
|
|
184
204
|
disappear. The documented status-line path is the fallback.
|
|
185
|
-
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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.
|
|
190
211
|
- Any running `claude` keeps the access token fresh. This tool deliberately does
|
|
191
212
|
not implement the undocumented refresh flow.
|
|
192
213
|
- Use **`/feedback` in Claude Code** to ask Anthropic for an official
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "claude-usage-limits"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
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"
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
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)
|
|
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)
|
{claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0/src/claude_usage_limits.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: claude-usage-limits
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
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
|
|
@@ -45,6 +45,7 @@ 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
|
|
|
@@ -56,10 +57,10 @@ $ claude-usage
|
|
|
56
57
|
## ✨ Features
|
|
57
58
|
|
|
58
59
|
- **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
|
|
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%.
|
|
60
61
|
- **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
|
|
61
62
|
- **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
|
|
62
|
-
- **🧾 Plain, JSON, or
|
|
63
|
+
- **🧾 Plain, JSON, short, or menubar** — output for the terminal, scripts, and SwiftBar.
|
|
63
64
|
- **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.9+.
|
|
64
65
|
- **🔋 Zero dependencies** — pure Python standard library.
|
|
65
66
|
- **🔒 Local & private** — reads your existing login; no telemetry or third-party calls.
|
|
@@ -80,10 +81,13 @@ its access token fresh.
|
|
|
80
81
|
|---|---|
|
|
81
82
|
| `claude-usage` | Available usage windows and their reset times |
|
|
82
83
|
| `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
|
|
84
|
+
| `claude-usage --warn [N]` | Exit 1 when the 5-hour window, any weekly limit, or spend percentage reaches N% (default 70) |
|
|
84
85
|
| `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
|
|
85
86
|
| `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) |
|
|
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) |
|
|
87
91
|
| `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
|
|
88
92
|
| `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
|
|
89
93
|
| `claude-usage -V`, `--version` | Print the version |
|
|
@@ -121,8 +125,9 @@ The usual output is always printed. Exit codes: **0** for success, **1** when
|
|
|
121
125
|
either threshold trips or no source answers, **2** for an argument error.
|
|
122
126
|
The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
|
|
123
127
|
Missing or null windows do not trigger warnings. `--warn` includes session and
|
|
124
|
-
weekly entries in `limits[]
|
|
125
|
-
|
|
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`.
|
|
126
131
|
JSON preserves the source payload, including null fields and weekly share indices.
|
|
127
132
|
|
|
128
133
|
## 📟 Claude Code status line
|
|
@@ -148,15 +153,30 @@ the endpoint is unavailable. Invalid input produces no output and exits 0.
|
|
|
148
153
|
`claude-usage --format short` gives the same compact format from the normal source
|
|
149
154
|
order; endpoint answers usually have no model, so show `7d 59%`.
|
|
150
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
|
+
|
|
151
168
|
## 🤔 How it works
|
|
152
169
|
|
|
153
170
|
Sources are tried in this order:
|
|
154
171
|
|
|
155
|
-
1. `last-usage.json` if less than **5 minutes** old.
|
|
172
|
+
1. `last-usage.json` if less than **5 minutes** old by default.
|
|
156
173
|
2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
|
|
157
174
|
3. `last-usage.json` if less than **60 minutes** old.
|
|
158
175
|
4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
|
|
159
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
|
+
|
|
160
180
|
Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
|
|
161
181
|
atomic. Cached answers at least a minute old show their source and age, e.g.
|
|
162
182
|
`(from the endpoint, 3 min ago)`; status-line answers always show their age.
|
|
@@ -202,11 +222,12 @@ For the protocol and a recipe to rebuild the tool, see
|
|
|
202
222
|
|
|
203
223
|
- The OAuth usage endpoint is **undocumented and rate limited**; it may change or
|
|
204
224
|
disappear. The documented status-line path is the fallback.
|
|
205
|
-
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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.
|
|
210
231
|
- Any running `claude` keeps the access token fresh. This tool deliberately does
|
|
211
232
|
not implement the undocumented refresh flow.
|
|
212
233
|
- 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.
|
|
213
|
+
assert capsys.readouterr().out == "claude-usage 0.3.0\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)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{claude_usage_limits-0.2.1 → claude_usage_limits-0.3.0}/src/claude_usage_limits.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|