claude-usage-limits 0.1.0__tar.gz → 0.2.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 (19) hide show
  1. {claude_usage_limits-0.1.0/src/claude_usage_limits.egg-info → claude_usage_limits-0.2.0}/PKG-INFO +24 -18
  2. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/README.md +21 -15
  3. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/pyproject.toml +3 -3
  4. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/__init__.py +1 -1
  5. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/cli.py +8 -6
  6. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/report.py +50 -8
  7. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0/src/claude_usage_limits.egg-info}/PKG-INFO +24 -18
  8. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/tests/test_report.py +80 -30
  9. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/tests/test_sources.py +2 -4
  10. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/LICENSE +0 -0
  11. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/setup.cfg +0 -0
  12. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/__main__.py +0 -0
  13. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/api.py +0 -0
  14. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage/auth.py +0 -0
  15. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
  16. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
  17. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
  18. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
  19. {claude_usage_limits-0.1.0 → claude_usage_limits-0.2.0}/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.1.0
4
- Summary: CLI for your Claude subscription rate limits: the 5-hour and 7-day usage windows Claude Code shows in /usage, from your terminal.
3
+ Version: 0.2.0
4
+ Summary: CLI for Claude subscription weekly 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
8
8
  Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
9
- Keywords: claude,claude-code,anthropic,usage,rate-limit,cli
9
+ Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,cli
10
10
  Classifier: Development Status :: 4 - Beta
11
11
  Classifier: Environment :: Console
12
12
  Classifier: Intended Audience :: Developers
@@ -39,7 +39,7 @@ 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 same two numbers from the shell** — for
42
+ screen. **`claude-usage` gives you the weekly 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
 
@@ -47,14 +47,13 @@ login already on your machine. No API key to manage, nothing to configure.
47
47
 
48
48
  ```text
49
49
  $ claude-usage
50
- 5-hour: 25% used, resets 16:10 (in 1h39m)
51
- 7-day: 59% used, resets Sun 03:00 (in 12h29m)
50
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
52
51
  ```
53
52
 
54
53
  ## ✨ Features
55
54
 
56
- - **Two windows, one command** — 5-hour and 7-day percent used and local reset times.
57
- - **🚦 Thresholds for scripts** — `--warn [N]` and `--warn-7d [N]` exit 1 at or above N%.
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%.
58
57
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
59
58
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
60
59
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -76,9 +75,9 @@ its access token fresh.
76
75
 
77
76
  | Command | What it does |
78
77
  |---|---|
79
- | `claude-usage` | Two usage windows and their reset times |
80
- | `claude-usage --json` | Raw JSON of whichever source answered; alias for `--format json` |
81
- | `claude-usage --warn [N]` | Exit 1 at or above N% of the 5-hour window (default 70) |
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
81
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
83
82
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
84
83
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
@@ -95,11 +94,9 @@ only in plain format, keeping JSON machine-readable and short output on one line
95
94
  <summary><b>📊 Example: <code>--all</code></b></summary>
96
95
 
97
96
  ```text
98
- 5-hour: 30% used, resets 16:10 (in 1h21m)
99
- 7-day: 60% used, resets Sun 03:00 (in 12h11m)
97
+ 7-day: 60% used, resets Sun 03:00 (in 12h11m)
100
98
  kind percent severity active model reset
101
99
  ------------------------------------------------------------------------------
102
- session 30% normal resets 16:10 (in 1h21m)
103
100
  weekly_all 60% normal active resets Sun 03:00 (in 12h11m)
104
101
  weekly_scoped 9% normal Fable resets Sun 03:00 (in 12h11m)
105
102
  Claude Code 96%, Cowork 4%, Chats 0%, Other 0%
@@ -120,8 +117,12 @@ claude-usage --json
120
117
  The usual output is always printed. Exit codes: **0** for success, **1** when
121
118
  either threshold trips or no source answers, **2** for an argument error.
122
119
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
123
- A missing window counts as zero for threshold checks. JSON is the raw payload,
124
- so its shape depends on the source; plain and short output normalize both.
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.
125
126
 
126
127
  ## 📟 Claude Code status line
127
128
 
@@ -137,14 +138,14 @@ settings):
137
138
  Claude Code pipes its documented status JSON to the command on each repaint:
138
139
 
139
140
  ```text
140
- Fable 5.1 · 5h 25% · 7d 59%
141
+ Fable 5.1 · 7d 59%
141
142
  ```
142
143
 
143
144
  Missing parts are omitted. This mode never looks up credentials or makes a network
144
145
  call. It also writes `last-statusline.json`, feeding the documented fallback when
145
146
  the endpoint is unavailable. Invalid input produces no output and exits 0.
146
147
  `claude-usage --format short` gives the same compact format from the normal source
147
- order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
148
+ order; endpoint answers usually have no model, so show `7d 59%`.
148
149
 
149
150
  ## 🤔 How it works
150
151
 
@@ -235,6 +236,11 @@ pip install pytest && pytest -q
235
236
  Tests use temporary config directories and mocked HTTP; they never contact the
236
237
  endpoint or read your real credentials.
237
238
 
239
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
240
+ [agg](https://github.com/asciinema/agg/releases). The recorder runs the CLI against
241
+ illustrative local caches and supplies status-line JSON on stdin; it needs no
242
+ credentials or network access. The README embeds the resulting `docs/demo.gif`.
243
+
238
244
  ## 📄 License
239
245
 
240
246
  [MIT](LICENSE) — do whatever you like.
@@ -19,7 +19,7 @@
19
19
  ---
20
20
 
21
21
  Claude Code shows your subscription limits only in the interactive `/usage`
22
- screen. **`claude-usage` gives you the same two numbers from the shell** — for
22
+ screen. **`claude-usage` gives you the weekly 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
 
@@ -27,14 +27,13 @@ login already on your machine. No API key to manage, nothing to configure.
27
27
 
28
28
  ```text
29
29
  $ claude-usage
30
- 5-hour: 25% used, resets 16:10 (in 1h39m)
31
- 7-day: 59% used, resets Sun 03:00 (in 12h29m)
30
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
32
31
  ```
33
32
 
34
33
  ## ✨ Features
35
34
 
36
- - **Two windows, one command** — 5-hour and 7-day percent used and local reset times.
37
- - **🚦 Thresholds for scripts** — `--warn [N]` and `--warn-7d [N]` exit 1 at or above N%.
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%.
38
37
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
39
38
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
40
39
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -56,9 +55,9 @@ its access token fresh.
56
55
 
57
56
  | Command | What it does |
58
57
  |---|---|
59
- | `claude-usage` | Two usage windows and their reset times |
60
- | `claude-usage --json` | Raw JSON of whichever source answered; alias for `--format json` |
61
- | `claude-usage --warn [N]` | Exit 1 at or above N% of the 5-hour window (default 70) |
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
61
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
63
62
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
64
63
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
@@ -75,11 +74,9 @@ only in plain format, keeping JSON machine-readable and short output on one line
75
74
  <summary><b>📊 Example: <code>--all</code></b></summary>
76
75
 
77
76
  ```text
78
- 5-hour: 30% used, resets 16:10 (in 1h21m)
79
- 7-day: 60% used, resets Sun 03:00 (in 12h11m)
77
+ 7-day: 60% used, resets Sun 03:00 (in 12h11m)
80
78
  kind percent severity active model reset
81
79
  ------------------------------------------------------------------------------
82
- session 30% normal resets 16:10 (in 1h21m)
83
80
  weekly_all 60% normal active resets Sun 03:00 (in 12h11m)
84
81
  weekly_scoped 9% normal Fable resets Sun 03:00 (in 12h11m)
85
82
  Claude Code 96%, Cowork 4%, Chats 0%, Other 0%
@@ -100,8 +97,12 @@ claude-usage --json
100
97
  The usual output is always printed. Exit codes: **0** for success, **1** when
101
98
  either threshold trips or no source answers, **2** for an argument error.
102
99
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
103
- A missing window counts as zero for threshold checks. JSON is the raw payload,
104
- so its shape depends on the source; plain and short output normalize both.
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.
105
106
 
106
107
  ## 📟 Claude Code status line
107
108
 
@@ -117,14 +118,14 @@ settings):
117
118
  Claude Code pipes its documented status JSON to the command on each repaint:
118
119
 
119
120
  ```text
120
- Fable 5.1 · 5h 25% · 7d 59%
121
+ Fable 5.1 · 7d 59%
121
122
  ```
122
123
 
123
124
  Missing parts are omitted. This mode never looks up credentials or makes a network
124
125
  call. It also writes `last-statusline.json`, feeding the documented fallback when
125
126
  the endpoint is unavailable. Invalid input produces no output and exits 0.
126
127
  `claude-usage --format short` gives the same compact format from the normal source
127
- order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
128
+ order; endpoint answers usually have no model, so show `7d 59%`.
128
129
 
129
130
  ## 🤔 How it works
130
131
 
@@ -215,6 +216,11 @@ pip install pytest && pytest -q
215
216
  Tests use temporary config directories and mocked HTTP; they never contact the
216
217
  endpoint or read your real credentials.
217
218
 
219
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
220
+ [agg](https://github.com/asciinema/agg/releases). The recorder runs the CLI against
221
+ illustrative local caches and supplies status-line JSON on stdin; it needs no
222
+ credentials or network access. The README embeds the resulting `docs/demo.gif`.
223
+
218
224
  ## 📄 License
219
225
 
220
226
  [MIT](LICENSE) — do whatever you like.
@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "claude-usage-limits"
7
- version = "0.1.0"
8
- description = "CLI for your Claude subscription rate limits: the 5-hour and 7-day usage windows Claude Code shows in /usage, from your terminal."
7
+ version = "0.2.0"
8
+ description = "CLI for Claude subscription weekly 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"]
12
12
  requires-python = ">=3.9"
13
13
  authors = [{ name = "claude-usage contributors" }]
14
- keywords = ["claude", "claude-code", "anthropic", "usage", "rate-limit", "cli"]
14
+ keywords = ["claude", "claude-code", "anthropic", "usage", "rate-limit", "weekly-usage", "subscription", "statusline", "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.1.0"
3
+ __version__ = "0.2.0"
@@ -7,18 +7,18 @@ import sys
7
7
  from . import __version__
8
8
  from .api import usage, write_cache
9
9
  from .auth import config_dir
10
- from .report import render_limits, render_plain, render_short, shape
10
+ from .report import render_limits, render_plain, render_short, shape, warning_reached
11
11
 
12
12
 
13
13
  def build_parser():
14
14
  p = argparse.ArgumentParser(
15
15
  prog='claude-usage',
16
- description="Show Claude subscription rate limits: the 5-hour and 7-day usage windows.",
16
+ description="Show Claude subscription rate limits: weekly usage and model limits.",
17
17
  )
18
18
  p.add_argument('--json', action='store_const', dest='format', const='json',
19
- help='print the raw JSON that was used (alias for --format json)')
19
+ help='print usage JSON without retired session limits (alias for --format json)')
20
20
  p.add_argument('--warn', type=int, nargs='?', const=70, metavar='N',
21
- help='exit 1 when the 5-hour window is at or above N%% (default 70)')
21
+ help='exit 1 when any weekly limit is at or above N%% (default 70)')
22
22
  p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
23
23
  help='exit 1 when the 7-day window is at or above N%% (default 70)')
24
24
  p.add_argument('--all', action='store_true',
@@ -65,8 +65,10 @@ def main(argv=None):
65
65
  except (RuntimeError, OSError, ValueError, TypeError, AttributeError, OverflowError) as exc:
66
66
  print('claude-usage: ' + str(exc), file=sys.stderr)
67
67
  return 1
68
- for threshold, key in ((args.warn, 'five_hour'), (args.warn_7d, 'seven_day')):
69
- if threshold is not None and (out[key]['utilization'] or 0) >= threshold:
68
+ if args.warn is not None and warning_reached(out, args.warn):
69
+ return 1
70
+ if args.warn_7d is not None and out['seven_day']['utilization'] is not None:
71
+ if out['seven_day']['utilization'] >= args.warn_7d:
70
72
  return 1
71
73
  return 0
72
74
 
@@ -3,14 +3,37 @@
3
3
  from datetime import datetime, timezone
4
4
 
5
5
 
6
+ def current_payload(data):
7
+ """Copy a payload without retired session limits, including old cache data."""
8
+ out = {key: value for key, value in data.items() if key != "five_hour"}
9
+ if isinstance(out.get("rate_limits"), dict):
10
+ out["rate_limits"] = {key: value for key, value in out["rate_limits"].items()
11
+ if key != "five_hour"}
12
+ if isinstance(out.get("limits"), list):
13
+ kept = [(index, limit) for index, limit in enumerate(out["limits"])
14
+ if limit.get("kind") != "session" and limit.get("group") != "session"]
15
+ out["limits"] = [limit for _, limit in kept]
16
+ # Shares refer to positions in limits; preserve those references when filtering.
17
+ if len(kept) != len(data["limits"]) and isinstance(out.get("weekly_scoped_shares"), list):
18
+ indices = {old: new for new, (old, _) in enumerate(kept)}
19
+ out["weekly_scoped_shares"] = [dict(share, limit_index=indices[share["limit_index"]])
20
+ for share in out["weekly_scoped_shares"]
21
+ if share.get("limit_index") in indices]
22
+ return out
23
+
24
+
6
25
  def shape(data, source):
7
- """Normalize either source, retaining its untouched payload for ``--json``."""
26
+ """Normalize weekly windows and retain other fields for JSON/detail output."""
8
27
  if not isinstance(data, dict):
9
28
  raise ValueError("usage data is not a JSON object")
29
+ data = current_payload(data)
10
30
  out = {"source": source, "raw": data}
11
31
  status = source.startswith("status line")
12
32
  windows = (data.get("rate_limits") or {}) if status else data
13
- for key in ("five_hour", "seven_day"):
33
+ keys = ["seven_day"] + sorted(key for key, value in windows.items()
34
+ if key.startswith("seven_day_") and isinstance(value, dict)
35
+ and ("utilization" in value or "used_percentage" in value))
36
+ for key in keys:
14
37
  window = windows.get(key) or {}
15
38
  reset = window.get("resets_at")
16
39
  if status and reset is not None:
@@ -21,6 +44,26 @@ def shape(data, source):
21
44
  return out
22
45
 
23
46
 
47
+ def weekly_windows(usage):
48
+ """Yield normalized weekly windows in display order."""
49
+ return ((key, window) for key, window in usage.items()
50
+ if key == "seven_day" or key.startswith("seven_day_"))
51
+
52
+
53
+ def window_label(key, short=False):
54
+ label = "7d" if short else "7-day"
55
+ suffix = key[len("seven_day"):].strip("_").replace("_", " ")
56
+ return f"{label} {suffix}" if suffix else label
57
+
58
+
59
+ def warning_reached(usage, threshold):
60
+ """Check weekly windows and the endpoint's per-model weekly caps."""
61
+ values = [window['utilization'] for _, window in weekly_windows(usage)]
62
+ values.extend(limit.get('percent') for limit in usage['raw'].get('limits') or []
63
+ if limit.get('group') == 'weekly' or limit.get('kind', '').startswith('weekly_'))
64
+ return any(value is not None and float(value) >= threshold for value in values)
65
+
66
+
24
67
  def when(iso):
25
68
  if not iso:
26
69
  return "reset time unknown"
@@ -40,9 +83,8 @@ def pct(window):
40
83
 
41
84
  def render_plain(usage):
42
85
  out = []
43
- for label, key in (("5-hour:", "five_hour"), ("7-day: ", "seven_day")):
44
- window = usage[key]
45
- out.append(f"{label} {pct(window)} used, {when(window['resets_at'])}")
86
+ for key, window in weekly_windows(usage):
87
+ out.append(f"{window_label(key)}: {pct(window)} used, {when(window['resets_at'])}")
46
88
  if usage['source'] != 'endpoint':
47
89
  out.append(f"(from the {usage['source']})")
48
90
  return '\n'.join(out)
@@ -52,9 +94,9 @@ def render_short(usage):
52
94
  """Render the same compact line for ``--format short`` and ``--statusline``."""
53
95
  model = (usage['raw'].get('model') or {}).get('display_name')
54
96
  parts = [model] if model else []
55
- for label, key in (("5h", "five_hour"), ("7d", "seven_day")):
56
- if usage[key]['utilization'] is not None:
57
- parts.append(f"{label} {pct(usage[key])}")
97
+ for key, window in weekly_windows(usage):
98
+ if window['utilization'] is not None:
99
+ parts.append(f"{window_label(key, short=True)} {pct(window)}")
58
100
  return ' · '.join(parts)
59
101
 
60
102
 
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.1.0
4
- Summary: CLI for your Claude subscription rate limits: the 5-hour and 7-day usage windows Claude Code shows in /usage, from your terminal.
3
+ Version: 0.2.0
4
+ Summary: CLI for Claude subscription weekly 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
8
8
  Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
9
- Keywords: claude,claude-code,anthropic,usage,rate-limit,cli
9
+ Keywords: claude,claude-code,anthropic,usage,rate-limit,weekly-usage,subscription,statusline,cli
10
10
  Classifier: Development Status :: 4 - Beta
11
11
  Classifier: Environment :: Console
12
12
  Classifier: Intended Audience :: Developers
@@ -39,7 +39,7 @@ 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 same two numbers from the shell** — for
42
+ screen. **`claude-usage` gives you the weekly 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
 
@@ -47,14 +47,13 @@ login already on your machine. No API key to manage, nothing to configure.
47
47
 
48
48
  ```text
49
49
  $ claude-usage
50
- 5-hour: 25% used, resets 16:10 (in 1h39m)
51
- 7-day: 59% used, resets Sun 03:00 (in 12h29m)
50
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
52
51
  ```
53
52
 
54
53
  ## ✨ Features
55
54
 
56
- - **Two windows, one command** — 5-hour and 7-day percent used and local reset times.
57
- - **🚦 Thresholds for scripts** — `--warn [N]` and `--warn-7d [N]` exit 1 at or above N%.
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%.
58
57
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
59
58
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
60
59
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -76,9 +75,9 @@ its access token fresh.
76
75
 
77
76
  | Command | What it does |
78
77
  |---|---|
79
- | `claude-usage` | Two usage windows and their reset times |
80
- | `claude-usage --json` | Raw JSON of whichever source answered; alias for `--format json` |
81
- | `claude-usage --warn [N]` | Exit 1 at or above N% of the 5-hour window (default 70) |
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
81
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
83
82
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
84
83
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
@@ -95,11 +94,9 @@ only in plain format, keeping JSON machine-readable and short output on one line
95
94
  <summary><b>📊 Example: <code>--all</code></b></summary>
96
95
 
97
96
  ```text
98
- 5-hour: 30% used, resets 16:10 (in 1h21m)
99
- 7-day: 60% used, resets Sun 03:00 (in 12h11m)
97
+ 7-day: 60% used, resets Sun 03:00 (in 12h11m)
100
98
  kind percent severity active model reset
101
99
  ------------------------------------------------------------------------------
102
- session 30% normal resets 16:10 (in 1h21m)
103
100
  weekly_all 60% normal active resets Sun 03:00 (in 12h11m)
104
101
  weekly_scoped 9% normal Fable resets Sun 03:00 (in 12h11m)
105
102
  Claude Code 96%, Cowork 4%, Chats 0%, Other 0%
@@ -120,8 +117,12 @@ claude-usage --json
120
117
  The usual output is always printed. Exit codes: **0** for success, **1** when
121
118
  either threshold trips or no source answers, **2** for an argument error.
122
119
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
123
- A missing window counts as zero for threshold checks. JSON is the raw payload,
124
- so its shape depends on the source; plain and short output normalize both.
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.
125
126
 
126
127
  ## 📟 Claude Code status line
127
128
 
@@ -137,14 +138,14 @@ settings):
137
138
  Claude Code pipes its documented status JSON to the command on each repaint:
138
139
 
139
140
  ```text
140
- Fable 5.1 · 5h 25% · 7d 59%
141
+ Fable 5.1 · 7d 59%
141
142
  ```
142
143
 
143
144
  Missing parts are omitted. This mode never looks up credentials or makes a network
144
145
  call. It also writes `last-statusline.json`, feeding the documented fallback when
145
146
  the endpoint is unavailable. Invalid input produces no output and exits 0.
146
147
  `claude-usage --format short` gives the same compact format from the normal source
147
- order; endpoint answers usually have no model, so show `5h 23% · 7d 59%`.
148
+ order; endpoint answers usually have no model, so show `7d 59%`.
148
149
 
149
150
  ## 🤔 How it works
150
151
 
@@ -235,6 +236,11 @@ pip install pytest && pytest -q
235
236
  Tests use temporary config directories and mocked HTTP; they never contact the
236
237
  endpoint or read your real credentials.
237
238
 
239
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
240
+ [agg](https://github.com/asciinema/agg/releases). The recorder runs the CLI against
241
+ illustrative local caches and supplies status-line JSON on stdin; it needs no
242
+ credentials or network access. The README embeds the resulting `docs/demo.gif`.
243
+
238
244
  ## 📄 License
239
245
 
240
246
  [MIT](LICENSE) — do whatever you like.
@@ -6,21 +6,17 @@ import pytest
6
6
 
7
7
  from claude_usage import cli, report
8
8
 
9
- # Explicit fields from the redacted handoff; its ellipses are not JSON fields.
9
+ # Representative weekly payload based on the live response; values are illustrative.
10
10
  ENDPOINT = {
11
- "five_hour": {"utilization": 23.0, "resets_at": "2026-10-24T20:10:00.886739+00:00",
12
- "limit_dollars": None, "used_dollars": None, "remaining_dollars": None, "locked_reason": None},
13
11
  "seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00",
14
12
  "limit_dollars": None, "used_dollars": None, "remaining_dollars": None, "locked_reason": None},
15
13
  "seven_day_oauth_apps": None, "seven_day_opus": None, "seven_day_sonnet": None,
16
- "seven_day_cowork": None, "pace": None,
14
+ "seven_day_cowork": None, "seven_day_omelette": None, "pace": None,
17
15
  "extra_usage": {"is_enabled": False, "monthly_limit": None, "used_credits": None,
18
16
  "utilization": None, "currency": None, "decimal_places": None,
19
17
  "disabled_reason": None, "user_disabled": True, "spend_limit_reached": False,
20
18
  "credits_ever_enabled": True, "daily": None, "weekly": None},
21
19
  "limits": [
22
- {"kind": "session", "group": "session", "percent": 23, "severity": "normal",
23
- "resets_at": "2026-10-24T20:10:00.886739+00:00", "scope": None, "is_active": False},
24
20
  {"kind": "weekly_all", "group": "weekly", "percent": 59, "severity": "normal",
25
21
  "resets_at": "2026-10-25T07:00:00.886762+00:00", "scope": None, "is_active": True},
26
22
  {"kind": "weekly_scoped", "group": "weekly", "percent": 6, "severity": "normal",
@@ -36,10 +32,9 @@ ENDPOINT = {
36
32
  {"key": "cowork", "display_name": "Cowork", "percent": 4},
37
33
  {"key": "other", "display_name": "Other", "percent": 0},
38
34
  ]},
39
- "weekly_scoped_shares": [{"limit_index": 2, "used_percent_of_weekly": 3, "allowance_percent_of_weekly": 50}],
35
+ "weekly_scoped_shares": [{"limit_index": 1, "used_percent_of_weekly": 3, "allowance_percent_of_weekly": 50}],
40
36
  }
41
37
  STATUS = {"model": {"display_name": "Fable 5.1"}, "rate_limits": {
42
- "five_hour": {"used_percentage": 25, "resets_at": 1792000000},
43
38
  "seven_day": {"used_percentage": 59, "resets_at": 1792100000},
44
39
  }}
45
40
 
@@ -52,22 +47,21 @@ def local_only(monkeypatch, tmp_path):
52
47
 
53
48
  def test_shape_endpoint():
54
49
  out = report.shape(ENDPOINT, "endpoint")
55
- assert out == {"five_hour": {"utilization": 23.0, "resets_at": ENDPOINT['five_hour']['resets_at']},
56
- "seven_day": {"utilization": 59.0, "resets_at": ENDPOINT['seven_day']['resets_at']},
50
+ assert out == {"seven_day": {"utilization": 59.0, "resets_at": ENDPOINT['seven_day']['resets_at']},
57
51
  "source": "endpoint", "raw": ENDPOINT}
58
- assert report.shape({}, "endpoint")['five_hour'] == {"utilization": None, "resets_at": None}
52
+ assert report.shape({}, "endpoint")['seven_day'] == {"utilization": None, "resets_at": None}
59
53
 
60
54
 
61
55
  def test_shape_status_line():
62
56
  out = report.shape(STATUS, "status line, 12 min ago")
63
- assert out['five_hour'] == {"utilization": 25.0, "resets_at": datetime.fromtimestamp(1792000000, timezone.utc).isoformat()}
57
+ assert out['seven_day'] == {"utilization": 59.0, "resets_at": datetime.fromtimestamp(1792100000, timezone.utc).isoformat()}
64
58
  assert out['seven_day']['utilization'] == 59.0
65
59
  assert out['raw'] == STATUS
66
60
  assert report.shape({"rate_limits": {}}, "status line, 0 min ago")['seven_day']['resets_at'] is None
67
61
 
68
62
 
69
63
  def test_when(monkeypatch):
70
- local_tz = datetime.now().astimezone().tzinfo
64
+ local_tz = datetime(2026, 10, 24).astimezone().tzinfo
71
65
  now = datetime(2026, 10, 24, 14, 31, tzinfo=local_tz)
72
66
  class Clock(datetime):
73
67
  @classmethod
@@ -90,8 +84,7 @@ def test_pct(value, expected):
90
84
  def test_plain_exact_layout(monkeypatch):
91
85
  monkeypatch.setattr(report, "when", lambda iso: "reset time unknown")
92
86
  out = report.render_plain(report.shape(ENDPOINT, "endpoint, 3 min ago"))
93
- assert out == ("5-hour: 23% used, reset time unknown\n"
94
- "7-day: 59% used, reset time unknown\n"
87
+ assert out == ("7-day: 59% used, reset time unknown\n"
95
88
  "(from the endpoint, 3 min ago)")
96
89
 
97
90
 
@@ -99,23 +92,21 @@ def test_all_details(monkeypatch):
99
92
  monkeypatch.setattr(report, "when", lambda iso: "resets 16:10 (in 1h39m)")
100
93
  out = report.render_limits(report.shape(ENDPOINT, "endpoint"))
101
94
  assert "kind" in out and "severity" in out and "model" in out
102
- assert "session" in out and "23%" in out
103
95
  assert "weekly_all" in out and "59%" in out
104
96
  assert "weekly_scoped" in out and "6%" in out and "Fable" in out
105
97
  active = next(line for line in out.splitlines() if "weekly_all" in line)
106
98
  assert "active" in active
107
- assert "active" not in next(line for line in out.splitlines() if line.startswith("session"))
108
- assert out.count("resets 16:10 (in 1h39m)") == 3
99
+ assert out.count("resets 16:10 (in 1h39m)") == 2
109
100
  assert out.endswith("Claude Code 96%, Cowork 4%, Chats 0%, Other 0%")
110
101
  assert report.render_limits(report.shape(STATUS, "status line, 0 min ago")) == "(details not available from the status-line source)"
111
102
  assert report.render_limits(report.shape({}, "endpoint")) == ""
112
103
 
113
104
 
114
105
  @pytest.mark.parametrize("raw,source,expected", [
115
- (ENDPOINT, "endpoint", "5h 23% · 7d 59%"),
116
- (STATUS, "status line, 0 min ago", "Fable 5.1 · 5h 25% · 7d 59%"),
106
+ (ENDPOINT, "endpoint", "7d 59%"),
107
+ (STATUS, "status line, 0 min ago", "Fable 5.1 · 7d 59%"),
117
108
  ({"model": {"display_name": "Fable"}}, "status line, 0 min ago", "Fable"),
118
- ({"rate_limits": {"five_hour": {"used_percentage": 0}}}, "status line, 0 min ago", "5h 0%"),
109
+ ({"rate_limits": {"seven_day": {"used_percentage": 0}}}, "status line, 0 min ago", "7d 0%"),
119
110
  ({}, "endpoint", ""),
120
111
  ])
121
112
  def test_short(raw, source, expected):
@@ -123,20 +114,20 @@ def test_short(raw, source, expected):
123
114
 
124
115
 
125
116
  @pytest.mark.parametrize("value,code", [(69, 0), (70, 1), (71, 1), (None, 0)])
126
- @pytest.mark.parametrize("flag,key", [("--warn", "five_hour"), ("--warn-7d", "seven_day")])
117
+ @pytest.mark.parametrize("flag,key", [("--warn", "seven_day"), ("--warn-7d", "seven_day")])
127
118
  def test_warn_default(monkeypatch, capsys, value, code, flag, key):
128
119
  raw = {key: {"utilization": value}}
129
120
  monkeypatch.setattr(cli, "usage", lambda **kwargs: report.shape(raw, "endpoint"))
130
121
  assert cli.main([flag]) == code
131
- assert "5-hour:" in capsys.readouterr().out
122
+ assert "7-day:" in capsys.readouterr().out
132
123
 
133
124
 
134
125
  def test_thresholds_combine_and_json(monkeypatch, capsys):
135
- assert cli.main(["--warn", "24", "--warn-7d", "59", "--json"]) == 1
126
+ assert cli.main(["--warn", "60", "--warn-7d", "59", "--json"]) == 1
136
127
  assert json.loads(capsys.readouterr().out) == ENDPOINT
137
- assert cli.main(["--warn", "23", "--warn-7d", "60", "--format", "short"]) == 1
138
- assert capsys.readouterr().out == "5h 23% · 7d 59%\n"
139
- assert cli.main(["--warn", "24", "--warn-7d", "60"]) == 0
128
+ assert cli.main(["--warn", "59", "--warn-7d", "60", "--format", "short"]) == 1
129
+ assert capsys.readouterr().out == "7d 59%\n"
130
+ assert cli.main(["--warn", "60", "--warn-7d", "60"]) == 0
140
131
 
141
132
 
142
133
  @pytest.mark.parametrize("args", [["--json"], ["--format", "json"], ["--all", "--json"]])
@@ -148,7 +139,7 @@ def test_json_raw_roundtrip(args, capsys):
148
139
  def test_cli_all(capsys):
149
140
  assert cli.main(["--all"]) == 0
150
141
  out = capsys.readouterr().out
151
- assert out.startswith("5-hour: 23% used,")
142
+ assert out.startswith("7-day: 59% used,")
152
143
  assert "weekly_scoped" in out and "Claude Code 96%" in out
153
144
 
154
145
 
@@ -165,7 +156,7 @@ def test_statusline_cache_and_line(monkeypatch, capsys, tmp_path):
165
156
  monkeypatch.setattr(cli.sys, "stdin", io.StringIO(json.dumps(STATUS)))
166
157
  monkeypatch.setattr(cli, "usage", lambda **k: pytest.fail("looked up usage"))
167
158
  assert cli.main(["--statusline"]) == 0
168
- assert capsys.readouterr().out == "Fable 5.1 · 5h 25% · 7d 59%\n"
159
+ assert capsys.readouterr().out == "Fable 5.1 · 7d 59%\n"
169
160
  assert json.loads((tmp_path / 'last-statusline.json').read_text()) == STATUS
170
161
  assert not (tmp_path / 'last-statusline.json.tmp').exists()
171
162
 
@@ -191,7 +182,7 @@ def test_version(capsys):
191
182
  with pytest.raises(SystemExit) as exc:
192
183
  cli.main(["--version"])
193
184
  assert exc.value.code == 0
194
- assert capsys.readouterr().out == "claude-usage 0.1.0\n"
185
+ assert capsys.readouterr().out == "claude-usage 0.2.0\n"
195
186
 
196
187
 
197
188
  def test_help_hides_statusline(capsys):
@@ -208,3 +199,62 @@ def test_argparse_error(capsys):
208
199
  with pytest.raises(SystemExit) as exc:
209
200
  cli.main(["--format", "bad"])
210
201
  assert exc.value.code == 2
202
+
203
+
204
+ @pytest.mark.parametrize('legacy', [None, {'utilization': 99, 'resets_at': 'bad date'}])
205
+ @pytest.mark.parametrize('source', ['endpoint', 'status line, 0 min ago'])
206
+ def test_retired_window_ignored_and_removed_from_json(monkeypatch, capsys, legacy, source):
207
+ windows = {'five_hour': legacy, 'seven_day': None}
208
+ raw = {'rate_limits': windows} if source.startswith('status line') else windows
209
+ shaped = report.shape(raw, source)
210
+ assert 'five_hour' not in shaped
211
+ assert 'five_hour' not in json.dumps(shaped['raw'])
212
+ assert raw.get('rate_limits', raw)['five_hour'] == legacy # Never mutate the cache/feed.
213
+ assert report.render_short(shaped) == ''
214
+ assert report.render_plain(shaped).startswith('7-day: ? used, reset time unknown')
215
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: shaped)
216
+ assert cli.main(['--json', '--warn']) == 0
217
+ assert 'five_hour' not in capsys.readouterr().out
218
+
219
+
220
+ def test_legacy_session_details_and_share_indices(monkeypatch, capsys):
221
+ raw = dict(ENDPOINT, five_hour={'utilization': 99})
222
+ raw['limits'] = [{'kind': 'session', 'group': 'session', 'percent': 99}] + ENDPOINT['limits']
223
+ raw['weekly_scoped_shares'] = [dict(ENDPOINT['weekly_scoped_shares'][0], limit_index=2)]
224
+ shaped = report.shape(raw, 'endpoint')
225
+ assert shaped['raw'] == ENDPOINT
226
+ assert raw['weekly_scoped_shares'][0]['limit_index'] == 2
227
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: shaped)
228
+ assert cli.main(['--all', '--warn']) == 0
229
+ assert 'session' not in capsys.readouterr().out
230
+
231
+
232
+ @pytest.mark.parametrize('source', ['endpoint', 'status line, 0 min ago'])
233
+ def test_populated_weekly_variants(monkeypatch, capsys, source):
234
+ status = source.startswith('status line')
235
+ field = 'used_percentage' if status else 'utilization'
236
+ windows = {'seven_day': {field: 10}, 'seven_day_opus': {field: 70},
237
+ 'seven_day_omelette': {field: 20}, 'seven_day_sonnet': None,
238
+ 'seven_day_breakdown': {'rows': []}}
239
+ raw = {'rate_limits': windows} if status else windows
240
+ shaped = report.shape(raw, source)
241
+ assert report.render_short(shaped) == '7d 10% · 7d omelette 20% · 7d opus 70%'
242
+ assert '7-day opus: 70% used' in report.render_plain(shaped)
243
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: shaped)
244
+ assert cli.main(['--warn']) == 1
245
+ assert cli.main(['--warn-7d']) == 0
246
+ assert cli.main(['--warn', '71']) == 0
247
+
248
+
249
+ @pytest.mark.parametrize('percent,code', [(69, 0), (70, 1), (71, 1), (None, 0)])
250
+ def test_weekly_scoped_limit_warning(monkeypatch, percent, code):
251
+ raw = {'seven_day': {'utilization': 10},
252
+ 'limits': [{'kind': 'weekly_scoped', 'group': 'weekly', 'percent': percent}]}
253
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: report.shape(raw, 'endpoint'))
254
+ assert cli.main(['--warn']) == code
255
+ assert cli.main(['--warn-7d']) == 0
256
+
257
+
258
+ def test_missing_weekly_window_does_not_warn_at_zero(monkeypatch):
259
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: report.shape({}, 'endpoint'))
260
+ assert cli.main(['--warn', '0', '--warn-7d', '0']) == 0
@@ -7,10 +7,8 @@ import pytest
7
7
 
8
8
  from claude_usage import api, cli
9
9
 
10
- ENDPOINT = {"five_hour": {"utilization": 23.0, "resets_at": "2026-10-24T20:10:00.886739+00:00"},
11
- "seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00"}}
10
+ ENDPOINT = {"seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00"}}
12
11
  STATUS = {"model": {"display_name": "Fable 5.1"}, "rate_limits": {
13
- "five_hour": {"used_percentage": 25, "resets_at": 1792000000},
14
12
  "seven_day": {"used_percentage": 59, "resets_at": 1792100000}}}
15
13
 
16
14
 
@@ -76,7 +74,7 @@ def test_429_uses_statusline(monkeypatch, tmp_path):
76
74
  monkeypatch.setattr(api, '_get_json', rate_limited)
77
75
  out = api.usage()
78
76
  assert out['source'] == 'status line, 12 min ago'
79
- assert out['five_hour']['utilization'] == 25
77
+ assert out['seven_day']['utilization'] == 59
80
78
  assert out['raw'] == STATUS
81
79
 
82
80