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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/PKG-INFO +16 -15
  2. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/README.md +14 -13
  3. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/pyproject.toml +2 -2
  4. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/__init__.py +1 -1
  5. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/auth.py +36 -12
  6. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/cli.py +10 -5
  7. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/report.py +14 -29
  8. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage_limits.egg-info/PKG-INFO +16 -15
  9. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/tests/test_report.py +47 -38
  10. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/tests/test_sources.py +62 -2
  11. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/LICENSE +0 -0
  12. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/setup.cfg +0 -0
  13. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/__main__.py +0 -0
  14. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage/api.py +0 -0
  15. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
  16. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
  17. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
  18. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
  19. {claude_usage_limits-0.2.0 → claude_usage_limits-0.2.1}/tests/test_auth.py +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.2.0
4
- Summary: CLI for Claude subscription weekly usage and model limits, with status-line output and warning thresholds.
3
+ Version: 0.2.1
4
+ Summary: CLI for Claude subscription usage and model limits, with status-line output and warning thresholds.
5
5
  Author: claude-usage contributors
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
@@ -39,10 +39,13 @@ Dynamic: license-file
39
39
  ---
40
40
 
41
41
  Claude Code shows your subscription limits only in the interactive `/usage`
42
- screen. **`claude-usage` gives you the weekly usage and model limits from the shell** — for
42
+ screen. **`claude-usage` gives you subscription usage and model limits from the shell** — for
43
43
  scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
44
44
  login already on your machine. No API key to manage, nothing to configure.
45
45
 
46
+ The 5-hour window appears when your plan has one and the usage source reports
47
+ it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
48
+
46
49
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
47
50
 
48
51
  ```text
@@ -52,8 +55,8 @@ $ claude-usage
52
55
 
53
56
  ## ✨ Features
54
57
 
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
+ - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
59
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
57
60
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
58
61
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
59
62
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -75,14 +78,14 @@ its access token fresh.
75
78
 
76
79
  | Command | What it does |
77
80
  |---|---|
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) |
81
+ | `claude-usage` | Available usage windows and their reset times |
82
+ | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
83
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
81
84
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
82
85
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
83
86
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
84
87
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
85
- | `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
88
+ | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
86
89
  | `claude-usage -V`, `--version` | Print the version |
87
90
  | `claude-usage -h`, `--help` | Show help |
88
91
 
@@ -117,12 +120,10 @@ claude-usage --json
117
120
  The usual output is always printed. Exit codes: **0** for success, **1** when
118
121
  either threshold trips or no source answers, **2** for an argument error.
119
122
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
120
- Missing or null windows do not trigger warnings. `--warn` includes weekly model
121
- caps in `limits[]`; `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
123
+ Missing or null windows do not trigger warnings. `--warn` includes session and
124
+ weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
122
125
  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.
126
+ JSON preserves the source payload, including null fields and weekly share indices.
126
127
 
127
128
  ## 📟 Claude Code status line
128
129
 
@@ -138,7 +139,7 @@ settings):
138
139
  Claude Code pipes its documented status JSON to the command on each repaint:
139
140
 
140
141
  ```text
141
- Fable 5.1 · 7d 59%
142
+ Fable 5.1 · 5h 25% · 7d 59%
142
143
  ```
143
144
 
144
145
  Missing parts are omitted. This mode never looks up credentials or makes a network
@@ -19,10 +19,13 @@
19
19
  ---
20
20
 
21
21
  Claude Code shows your subscription limits only in the interactive `/usage`
22
- screen. **`claude-usage` gives you the weekly usage and model limits from the shell** — for
22
+ screen. **`claude-usage` gives you subscription usage and model limits from the shell** — for
23
23
  scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
24
24
  login already on your machine. No API key to manage, nothing to configure.
25
25
 
26
+ The 5-hour window appears when your plan has one and the usage source reports
27
+ it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
28
+
26
29
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
27
30
 
28
31
  ```text
@@ -32,8 +35,8 @@ $ claude-usage
32
35
 
33
36
  ## ✨ Features
34
37
 
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
+ - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
39
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
37
40
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
38
41
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
39
42
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -55,14 +58,14 @@ its access token fresh.
55
58
 
56
59
  | Command | What it does |
57
60
  |---|---|
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) |
61
+ | `claude-usage` | Available usage windows and their reset times |
62
+ | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
63
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
61
64
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
62
65
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
63
66
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
64
67
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
65
- | `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
68
+ | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
66
69
  | `claude-usage -V`, `--version` | Print the version |
67
70
  | `claude-usage -h`, `--help` | Show help |
68
71
 
@@ -97,12 +100,10 @@ claude-usage --json
97
100
  The usual output is always printed. Exit codes: **0** for success, **1** when
98
101
  either threshold trips or no source answers, **2** for an argument error.
99
102
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
100
- Missing or null windows do not trigger warnings. `--warn` includes weekly model
101
- caps in `limits[]`; `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
103
+ Missing or null windows do not trigger warnings. `--warn` includes session and
104
+ weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
102
105
  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.
106
+ JSON preserves the source payload, including null fields and weekly share indices.
106
107
 
107
108
  ## 📟 Claude Code status line
108
109
 
@@ -118,7 +119,7 @@ settings):
118
119
  Claude Code pipes its documented status JSON to the command on each repaint:
119
120
 
120
121
  ```text
121
- Fable 5.1 · 7d 59%
122
+ Fable 5.1 · 5h 25% · 7d 59%
122
123
  ```
123
124
 
124
125
  Missing parts are omitted. This mode never looks up credentials or makes a network
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "claude-usage-limits"
7
- version = "0.2.0"
8
- description = "CLI for Claude subscription weekly usage and model limits, with status-line output and warning thresholds."
7
+ version = "0.2.1"
8
+ description = "CLI for Claude subscription usage and model limits, with status-line output and warning thresholds."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE"]
@@ -1,3 +1,3 @@
1
1
  """claude-usage: read your Claude subscription rate-limit windows."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.2.1"
@@ -2,7 +2,7 @@
2
2
 
3
3
  Priority: explicit environment override, macOS Keychain, credentials JSON.
4
4
  Only Claude Code refreshes tokens; this tool never writes credentials. Errors
5
- and verbose notes describe sources without exposing credential contents.
5
+ and verbose notes can identify the source and plan without exposing tokens.
6
6
  """
7
7
 
8
8
  import json
@@ -23,7 +23,7 @@ def config_dir():
23
23
  return Path(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude"))
24
24
 
25
25
 
26
- def _token_from_credentials(creds):
26
+ def _oauth_from_credentials(creds):
27
27
  try:
28
28
  oauth = creds.get("claudeAiOauth") or {}
29
29
  token = oauth.get("accessToken")
@@ -35,7 +35,7 @@ def _token_from_credentials(creds):
35
35
  raise CredentialsNotFound("credentials hold no OAuth access token; run `claude` once to log in")
36
36
  if expired:
37
37
  raise CredentialsNotFound("the access token has expired; open `claude` so it refreshes")
38
- return token
38
+ return oauth
39
39
 
40
40
 
41
41
  def _log(verbose, source):
@@ -43,12 +43,10 @@ def _log(verbose, source):
43
43
  print("credentials: " + source, file=sys.stderr)
44
44
 
45
45
 
46
- def resolve_token(config=None, verbose=False):
47
- """Return an access token, trying the file if the keychain is unavailable."""
46
+ def _resolve_credentials(config):
48
47
  override = os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")
49
48
  if override:
50
- _log(verbose, "CLAUDE_CODE_OAUTH_TOKEN")
51
- return override
49
+ return override, None, "CLAUDE_CODE_OAUTH_TOKEN"
52
50
 
53
51
  keychain_error = None
54
52
  if sys.platform == "darwin":
@@ -58,9 +56,8 @@ def resolve_token(config=None, verbose=False):
58
56
  capture_output=True, text=True, timeout=15,
59
57
  )
60
58
  if out.returncode == 0:
61
- token = _token_from_credentials(json.loads(out.stdout))
62
- _log(verbose, "macOS keychain")
63
- return token
59
+ oauth = _oauth_from_credentials(json.loads(out.stdout))
60
+ return oauth["accessToken"], oauth, "macOS keychain"
64
61
  except CredentialsNotFound as exc:
65
62
  keychain_error = exc
66
63
  except (OSError, ValueError, subprocess.SubprocessError):
@@ -74,6 +71,33 @@ def resolve_token(config=None, verbose=False):
74
71
  if keychain_error is not None:
75
72
  raise keychain_error from None
76
73
  raise CredentialsNotFound("no readable Claude Code credentials file; run `claude` once to log in") from None
77
- token = _token_from_credentials(creds)
78
- _log(verbose, "credentials file")
74
+ oauth = _oauth_from_credentials(creds)
75
+ return oauth["accessToken"], oauth, "credentials file"
76
+
77
+
78
+ def resolve_token(config=None, verbose=False):
79
+ """Return an access token, trying the file if the keychain is unavailable."""
80
+ token, _, source = _resolve_credentials(config)
81
+ _log(verbose, source)
79
82
  return token
83
+
84
+
85
+ def resolve_plan(config=None):
86
+ """Return the plan and optional tier for verbose diagnostics."""
87
+ try:
88
+ _, oauth, _ = _resolve_credentials(config)
89
+ if oauth is None:
90
+ return None
91
+ subscription = oauth.get("subscriptionType") or ""
92
+ tier = oauth.get("rateLimitTier") or ""
93
+ if not isinstance(subscription, str) or not isinstance(tier, str):
94
+ return None
95
+ if "max_20x" in tier:
96
+ plan = "Ultra"
97
+ elif "max_5x" in tier:
98
+ plan = "Max"
99
+ else:
100
+ plan = subscription.title() or "unknown"
101
+ return f"{plan} ({tier})" if tier else plan
102
+ except Exception:
103
+ return None
@@ -6,19 +6,20 @@ import sys
6
6
 
7
7
  from . import __version__
8
8
  from .api import usage, write_cache
9
- from .auth import config_dir
9
+ from .auth import config_dir, resolve_plan
10
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: weekly usage and model limits.",
16
+ description="Show Claude subscription rate limits, including the 5-hour window when available.",
17
17
  )
18
18
  p.add_argument('--json', action='store_const', dest='format', const='json',
19
- help='print usage JSON without retired session limits (alias for --format json)')
19
+ help='print the raw usage JSON (alias for --format json)')
20
20
  p.add_argument('--warn', type=int, nargs='?', const=70, metavar='N',
21
- help='exit 1 when any weekly limit is at or above N%% (default 70)')
21
+ help='check the 5-hour window (when your plan has one) and weekly limits, '
22
+ 'exiting 1 at or above N%% (default 70)')
22
23
  p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
23
24
  help='exit 1 when the 7-day window is at or above N%% (default 70)')
24
25
  p.add_argument('--all', action='store_true',
@@ -27,7 +28,7 @@ def build_parser():
27
28
  help='output format (default: plain)')
28
29
  p.add_argument('--statusline', action='store_true', help=argparse.SUPPRESS)
29
30
  p.add_argument('-v', '--verbose', action='store_true',
30
- help='log credential and usage sources to stderr')
31
+ help='log credential and usage sources and the plan to stderr')
31
32
  p.add_argument('-V', '--version', action='version', version='claude-usage %s' % __version__)
32
33
  return p
33
34
 
@@ -51,6 +52,10 @@ def main(argv=None):
51
52
  return statusline()
52
53
  try:
53
54
  out = usage(verbose=args.verbose)
55
+ if args.verbose:
56
+ plan = resolve_plan()
57
+ if plan is not None:
58
+ print('plan: ' + plan, file=sys.stderr)
54
59
  if args.format == 'json':
55
60
  json.dump(out['raw'], sys.stdout, indent=1)
56
61
  print()
@@ -3,36 +3,18 @@
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
-
25
6
  def shape(data, source):
26
- """Normalize weekly windows and retain other fields for JSON/detail output."""
7
+ """Normalize usage windows and retain the untouched payload for JSON output."""
27
8
  if not isinstance(data, dict):
28
9
  raise ValueError("usage data is not a JSON object")
29
- data = current_payload(data)
30
10
  out = {"source": source, "raw": data}
31
11
  status = source.startswith("status line")
32
12
  windows = (data.get("rate_limits") or {}) if status else data
33
13
  keys = ["seven_day"] + sorted(key for key, value in windows.items()
34
14
  if key.startswith("seven_day_") and isinstance(value, dict)
35
15
  and ("utilization" in value or "used_percentage" in value))
16
+ if isinstance(windows.get("five_hour"), dict):
17
+ keys.insert(0, "five_hour")
36
18
  for key in keys:
37
19
  window = windows.get(key) or {}
38
20
  reset = window.get("resets_at")
@@ -44,23 +26,26 @@ def shape(data, source):
44
26
  return out
45
27
 
46
28
 
47
- def weekly_windows(usage):
48
- """Yield normalized weekly windows in display order."""
29
+ def usage_windows(usage):
30
+ """Yield normalized usage windows in display order."""
49
31
  return ((key, window) for key, window in usage.items()
50
- if key == "seven_day" or key.startswith("seven_day_"))
32
+ if key in ("five_hour", "seven_day") or key.startswith("seven_day_"))
51
33
 
52
34
 
53
35
  def window_label(key, short=False):
36
+ if key == "five_hour":
37
+ return "5h" if short else "5-hour"
54
38
  label = "7d" if short else "7-day"
55
39
  suffix = key[len("seven_day"):].strip("_").replace("_", " ")
56
40
  return f"{label} {suffix}" if suffix else label
57
41
 
58
42
 
59
43
  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)]
44
+ """Check normalized windows and the endpoint's session and weekly limits."""
45
+ values = [window['utilization'] for _, window in usage_windows(usage)]
62
46
  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_'))
47
+ if limit.get('group') in ('session', 'weekly') or limit.get('kind') == 'session'
48
+ or limit.get('kind', '').startswith('weekly_'))
64
49
  return any(value is not None and float(value) >= threshold for value in values)
65
50
 
66
51
 
@@ -83,7 +68,7 @@ def pct(window):
83
68
 
84
69
  def render_plain(usage):
85
70
  out = []
86
- for key, window in weekly_windows(usage):
71
+ for key, window in usage_windows(usage):
87
72
  out.append(f"{window_label(key)}: {pct(window)} used, {when(window['resets_at'])}")
88
73
  if usage['source'] != 'endpoint':
89
74
  out.append(f"(from the {usage['source']})")
@@ -94,7 +79,7 @@ def render_short(usage):
94
79
  """Render the same compact line for ``--format short`` and ``--statusline``."""
95
80
  model = (usage['raw'].get('model') or {}).get('display_name')
96
81
  parts = [model] if model else []
97
- for key, window in weekly_windows(usage):
82
+ for key, window in usage_windows(usage):
98
83
  if window['utilization'] is not None:
99
84
  parts.append(f"{window_label(key, short=True)} {pct(window)}")
100
85
  return ' · '.join(parts)
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.2.0
4
- Summary: CLI for Claude subscription weekly usage and model limits, with status-line output and warning thresholds.
3
+ Version: 0.2.1
4
+ Summary: CLI for Claude subscription usage and model limits, with status-line output and warning thresholds.
5
5
  Author: claude-usage contributors
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
@@ -39,10 +39,13 @@ Dynamic: license-file
39
39
  ---
40
40
 
41
41
  Claude Code shows your subscription limits only in the interactive `/usage`
42
- screen. **`claude-usage` gives you the weekly usage and model limits from the shell** — for
42
+ screen. **`claude-usage` gives you subscription usage and model limits from the shell** — for
43
43
  scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
44
44
  login already on your machine. No API key to manage, nothing to configure.
45
45
 
46
+ The 5-hour window appears when your plan has one and the usage source reports
47
+ it. Verified Ultra (formerly Max 20x) accounts have weekly limits only.
48
+
46
49
  **Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
47
50
 
48
51
  ```text
@@ -52,8 +55,8 @@ $ claude-usage
52
55
 
53
56
  ## ✨ Features
54
57
 
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
+ - **Usage windows** — 5-hour usage when available, 7-day usage, populated weekly variants, and local reset times.
59
+ - **🚦 Thresholds for scripts** — `--warn [N]` checks the 5-hour window when available and all weekly limits. `--warn-7d [N]` checks overall weekly usage. Both exit 1 at or above N%.
57
60
  - **📊 Extra detail** — `--all` shows per-model limits, the active window, and the weekly surface split.
58
61
  - **📟 Status line** — a compact model and usage line that also feeds the documented fallback source.
59
62
  - **🧾 Plain, JSON, or short** — readable in a terminal and easy to use from scripts.
@@ -75,14 +78,14 @@ its access token fresh.
75
78
 
76
79
  | Command | What it does |
77
80
  |---|---|
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) |
81
+ | `claude-usage` | Available usage windows and their reset times |
82
+ | `claude-usage --json` | Raw usage JSON from whichever source answered (alias for `--format json`) |
83
+ | `claude-usage --warn [N]` | Exit 1 when the 5-hour window or any weekly limit reaches N% (default 70) |
81
84
  | `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
82
85
  | `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
83
86
  | `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
84
87
  | `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
85
- | `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
88
+ | `claude-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
86
89
  | `claude-usage -V`, `--version` | Print the version |
87
90
  | `claude-usage -h`, `--help` | Show help |
88
91
 
@@ -117,12 +120,10 @@ claude-usage --json
117
120
  The usual output is always printed. Exit codes: **0** for success, **1** when
118
121
  either threshold trips or no source answers, **2** for an argument error.
119
122
  The threshold is inclusive: `--warn` exits 1 at 70%, including exactly 70%.
120
- Missing or null windows do not trigger warnings. `--warn` includes weekly model
121
- caps in `limits[]`; `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
123
+ Missing or null windows do not trigger warnings. `--warn` includes session and
124
+ weekly entries in `limits[]`. `--warn-7d` checks only `seven_day`. Populated `seven_day_*`
122
125
  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.
126
+ JSON preserves the source payload, including null fields and weekly share indices.
126
127
 
127
128
  ## 📟 Claude Code status line
128
129
 
@@ -138,7 +139,7 @@ settings):
138
139
  Claude Code pipes its documented status JSON to the command on each repaint:
139
140
 
140
141
  ```text
141
- Fable 5.1 · 7d 59%
142
+ Fable 5.1 · 5h 25% · 7d 59%
142
143
  ```
143
144
 
144
145
  Missing parts are omitted. This mode never looks up credentials or makes a network
@@ -6,8 +6,9 @@ import pytest
6
6
 
7
7
  from claude_usage import cli, report
8
8
 
9
- # Representative weekly payload based on the live response; values are illustrative.
9
+ # Representative payload without a 5-hour window; values are illustrative.
10
10
  ENDPOINT = {
11
+ "five_hour": None,
11
12
  "seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00",
12
13
  "limit_dollars": None, "used_dollars": None, "remaining_dollars": None, "locked_reason": None},
13
14
  "seven_day_oauth_apps": None, "seven_day_opus": None, "seven_day_sonnet": None,
@@ -34,7 +35,15 @@ ENDPOINT = {
34
35
  ]},
35
36
  "weekly_scoped_shares": [{"limit_index": 1, "used_percent_of_weekly": 3, "allowance_percent_of_weekly": 50}],
36
37
  }
38
+ FIVE_HOUR = {"utilization": 23.0, "resets_at": "2026-10-24T20:10:00.886739+00:00"}
39
+ WITH_SESSION = dict(
40
+ ENDPOINT, five_hour=FIVE_HOUR,
41
+ limits=[{"kind": "session", "group": "session", "percent": 23, "severity": "normal",
42
+ "resets_at": FIVE_HOUR["resets_at"], "scope": None, "is_active": False}] + ENDPOINT["limits"],
43
+ weekly_scoped_shares=[dict(ENDPOINT["weekly_scoped_shares"][0], limit_index=2)],
44
+ )
37
45
  STATUS = {"model": {"display_name": "Fable 5.1"}, "rate_limits": {
46
+ "five_hour": {"used_percentage": 25, "resets_at": 1792000000},
38
47
  "seven_day": {"used_percentage": 59, "resets_at": 1792100000},
39
48
  }}
40
49
 
@@ -49,11 +58,13 @@ def test_shape_endpoint():
49
58
  out = report.shape(ENDPOINT, "endpoint")
50
59
  assert out == {"seven_day": {"utilization": 59.0, "resets_at": ENDPOINT['seven_day']['resets_at']},
51
60
  "source": "endpoint", "raw": ENDPOINT}
61
+ assert report.shape(WITH_SESSION, "endpoint")["five_hour"] == FIVE_HOUR
52
62
  assert report.shape({}, "endpoint")['seven_day'] == {"utilization": None, "resets_at": None}
53
63
 
54
64
 
55
65
  def test_shape_status_line():
56
66
  out = report.shape(STATUS, "status line, 12 min ago")
67
+ assert out['five_hour'] == {"utilization": 25.0, "resets_at": datetime.fromtimestamp(1792000000, timezone.utc).isoformat()}
57
68
  assert out['seven_day'] == {"utilization": 59.0, "resets_at": datetime.fromtimestamp(1792100000, timezone.utc).isoformat()}
58
69
  assert out['seven_day']['utilization'] == 59.0
59
70
  assert out['raw'] == STATUS
@@ -81,10 +92,14 @@ def test_pct(value, expected):
81
92
  assert report.pct({}) == "?"
82
93
 
83
94
 
84
- def test_plain_exact_layout(monkeypatch):
95
+ @pytest.mark.parametrize("raw,first_line", [
96
+ (ENDPOINT, ""),
97
+ (WITH_SESSION, "5-hour: 23% used, reset time unknown\n"),
98
+ ])
99
+ def test_plain_exact_layout(monkeypatch, raw, first_line):
85
100
  monkeypatch.setattr(report, "when", lambda iso: "reset time unknown")
86
- out = report.render_plain(report.shape(ENDPOINT, "endpoint, 3 min ago"))
87
- assert out == ("7-day: 59% used, reset time unknown\n"
101
+ out = report.render_plain(report.shape(raw, "endpoint, 3 min ago"))
102
+ assert out == (first_line + "7-day: 59% used, reset time unknown\n"
88
103
  "(from the endpoint, 3 min ago)")
89
104
 
90
105
 
@@ -104,7 +119,10 @@ def test_all_details(monkeypatch):
104
119
 
105
120
  @pytest.mark.parametrize("raw,source,expected", [
106
121
  (ENDPOINT, "endpoint", "7d 59%"),
107
- (STATUS, "status line, 0 min ago", "Fable 5.1 · 7d 59%"),
122
+ (WITH_SESSION, "endpoint", "5h 23% · 7d 59%"),
123
+ (STATUS, "status line, 0 min ago", "Fable 5.1 · 5h 25% · 7d 59%"),
124
+ ({"rate_limits": {"five_hour": None, "seven_day": {"used_percentage": 59}}},
125
+ "status line, 0 min ago", "7d 59%"),
108
126
  ({"model": {"display_name": "Fable"}}, "status line, 0 min ago", "Fable"),
109
127
  ({"rate_limits": {"seven_day": {"used_percentage": 0}}}, "status line, 0 min ago", "7d 0%"),
110
128
  ({}, "endpoint", ""),
@@ -114,7 +132,9 @@ def test_short(raw, source, expected):
114
132
 
115
133
 
116
134
  @pytest.mark.parametrize("value,code", [(69, 0), (70, 1), (71, 1), (None, 0)])
117
- @pytest.mark.parametrize("flag,key", [("--warn", "seven_day"), ("--warn-7d", "seven_day")])
135
+ @pytest.mark.parametrize("flag,key", [
136
+ ("--warn", "five_hour"), ("--warn", "seven_day"), ("--warn-7d", "seven_day"),
137
+ ])
118
138
  def test_warn_default(monkeypatch, capsys, value, code, flag, key):
119
139
  raw = {key: {"utilization": value}}
120
140
  monkeypatch.setattr(cli, "usage", lambda **kwargs: report.shape(raw, "endpoint"))
@@ -131,15 +151,23 @@ def test_thresholds_combine_and_json(monkeypatch, capsys):
131
151
 
132
152
 
133
153
  @pytest.mark.parametrize("args", [["--json"], ["--format", "json"], ["--all", "--json"]])
134
- def test_json_raw_roundtrip(args, capsys):
154
+ @pytest.mark.parametrize("raw", [ENDPOINT, WITH_SESSION])
155
+ def test_json_raw_roundtrip(args, raw, monkeypatch, capsys):
156
+ monkeypatch.setattr(cli, "usage", lambda **kwargs: report.shape(raw, "endpoint"))
135
157
  assert cli.main(args) == 0
136
- assert capsys.readouterr().out == json.dumps(ENDPOINT, indent=1) + '\n'
158
+ assert capsys.readouterr().out == json.dumps(raw, indent=1) + '\n'
137
159
 
138
160
 
139
- def test_cli_all(capsys):
161
+ @pytest.mark.parametrize("raw,has_session", [(ENDPOINT, False), (WITH_SESSION, True)])
162
+ def test_cli_all(raw, has_session, monkeypatch, capsys):
163
+ monkeypatch.setattr(cli, "usage", lambda **kwargs: report.shape(raw, "endpoint"))
140
164
  assert cli.main(["--all"]) == 0
141
165
  out = capsys.readouterr().out
142
- assert out.startswith("7-day: 59% used,")
166
+ assert out.startswith("5-hour: 23% used," if has_session else "7-day: 59% used,")
167
+ session_rows = [line for line in out.splitlines() if line.startswith("session ")]
168
+ assert len(session_rows) == int(has_session)
169
+ if has_session:
170
+ assert session_rows[0].split()[:3] == ["session", "23%", "normal"]
143
171
  assert "weekly_scoped" in out and "Claude Code 96%" in out
144
172
 
145
173
 
@@ -156,7 +184,7 @@ def test_statusline_cache_and_line(monkeypatch, capsys, tmp_path):
156
184
  monkeypatch.setattr(cli.sys, "stdin", io.StringIO(json.dumps(STATUS)))
157
185
  monkeypatch.setattr(cli, "usage", lambda **k: pytest.fail("looked up usage"))
158
186
  assert cli.main(["--statusline"]) == 0
159
- assert capsys.readouterr().out == "Fable 5.1 · 7d 59%\n"
187
+ assert capsys.readouterr().out == "Fable 5.1 · 5h 25% · 7d 59%\n"
160
188
  assert json.loads((tmp_path / 'last-statusline.json').read_text()) == STATUS
161
189
  assert not (tmp_path / 'last-statusline.json.tmp').exists()
162
190
 
@@ -182,7 +210,7 @@ def test_version(capsys):
182
210
  with pytest.raises(SystemExit) as exc:
183
211
  cli.main(["--version"])
184
212
  assert exc.value.code == 0
185
- assert capsys.readouterr().out == "claude-usage 0.2.0\n"
213
+ assert capsys.readouterr().out == "claude-usage 0.2.1\n"
186
214
 
187
215
 
188
216
  def test_help_hides_statusline(capsys):
@@ -201,32 +229,13 @@ def test_argparse_error(capsys):
201
229
  assert exc.value.code == 2
202
230
 
203
231
 
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
232
+ @pytest.mark.parametrize('field', ['kind', 'group'])
233
+ def test_session_limit_warning(monkeypatch, field):
234
+ raw = dict(ENDPOINT, limits=[{field: 'session', 'percent': 70}])
235
+ monkeypatch.setattr(cli, 'usage', lambda **kwargs: report.shape(raw, 'endpoint'))
236
+ assert cli.main(['--warn']) == 1
237
+ assert cli.main(['--warn', '71']) == 0
238
+ assert cli.main(['--warn-7d']) == 0
230
239
 
231
240
 
232
241
  @pytest.mark.parametrize('source', ['endpoint', 'status line, 0 min ago'])
@@ -2,13 +2,16 @@ import json
2
2
  import os
3
3
  import time
4
4
  import urllib.error
5
+ from types import SimpleNamespace
5
6
 
6
7
  import pytest
7
8
 
8
- from claude_usage import api, cli
9
+ from claude_usage import api, auth, cli
9
10
 
10
- ENDPOINT = {"seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00"}}
11
+ ENDPOINT = {"five_hour": None,
12
+ "seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00"}}
11
13
  STATUS = {"model": {"display_name": "Fable 5.1"}, "rate_limits": {
14
+ "five_hour": {"used_percentage": 25, "resets_at": 1792000000},
12
15
  "seven_day": {"used_percentage": 59, "resets_at": 1792100000}}}
13
16
 
14
17
 
@@ -74,6 +77,7 @@ def test_429_uses_statusline(monkeypatch, tmp_path):
74
77
  monkeypatch.setattr(api, '_get_json', rate_limited)
75
78
  out = api.usage()
76
79
  assert out['source'] == 'status line, 12 min ago'
80
+ assert out['five_hour']['utilization'] == 25
77
81
  assert out['seven_day']['utilization'] == 59
78
82
  assert out['raw'] == STATUS
79
83
 
@@ -126,6 +130,7 @@ def test_cli_status_source_details_and_raw(monkeypatch, tmp_path, capsys):
126
130
  monkeypatch.setattr(api, '_get_json', rate_limited)
127
131
  assert cli.main(['--all']) == 0
128
132
  out = capsys.readouterr().out
133
+ assert out.startswith('5-hour: 25% used,')
129
134
  assert '(from the status line, 0 min ago)' in out
130
135
  assert '(details not available from the status-line source)' in out
131
136
  assert cli.main(['--json']) == 0
@@ -154,3 +159,58 @@ def test_request_errors_never_print_credentials(monkeypatch, capsys):
154
159
  assert 'PRIVATE-TOKEN' not in captured.out + captured.err
155
160
  assert 'Bearer' not in captured.err
156
161
  assert 'invalid request or JSON response' in captured.err
162
+
163
+
164
+ @pytest.mark.parametrize('subscription,tier,expected', [
165
+ ('max', 'default_claude_max_20x', 'Ultra (default_claude_max_20x)'),
166
+ ('max', 'default_claude_max_5x', 'Max (default_claude_max_5x)'),
167
+ ('pro', 'default_claude_pro', 'Pro (default_claude_pro)'),
168
+ ('team', None, 'Team'),
169
+ (None, None, 'unknown'),
170
+ ])
171
+ def test_resolve_plan_from_file(monkeypatch, tmp_path, subscription, tier, expected):
172
+ monkeypatch.delenv('CLAUDE_CODE_OAUTH_TOKEN')
173
+ monkeypatch.setattr(auth.sys, 'platform', 'linux')
174
+ save(tmp_path, '.credentials.json', {'claudeAiOauth': {
175
+ 'accessToken': 'FILE-TOKEN', 'subscriptionType': subscription, 'rateLimitTier': tier,
176
+ }})
177
+ assert auth.resolve_plan() == expected
178
+
179
+
180
+ def test_verbose_plan_from_keychain(monkeypatch, tmp_path, capsys):
181
+ monkeypatch.delenv('CLAUDE_CODE_OAUTH_TOKEN')
182
+ monkeypatch.setattr(auth.sys, 'platform', 'darwin')
183
+ save(tmp_path, '.credentials.json', {'claudeAiOauth': {
184
+ 'accessToken': 'FILE-TOKEN', 'subscriptionType': 'pro',
185
+ }})
186
+ oauth = {'accessToken': 'KEYCHAIN-TOKEN', 'refreshToken': 'KEYCHAIN-REFRESH',
187
+ 'subscriptionType': 'max', 'rateLimitTier': 'default_claude_max_20x'}
188
+ monkeypatch.setattr(auth.subprocess, 'run', lambda *args, **kwargs: SimpleNamespace(
189
+ returncode=0, stdout=json.dumps({'claudeAiOauth': oauth}),
190
+ ))
191
+ # An Ultra account can still receive a 5-hour window.
192
+ raw = dict(ENDPOINT, five_hour={'utilization': 25})
193
+ monkeypatch.setattr(api, '_get_json', lambda *args: raw)
194
+ assert cli.main(['-v']) == 0
195
+ out, err = capsys.readouterr()
196
+ assert out.startswith('5-hour: 25% used,')
197
+ assert err == ('credentials: macOS keychain\nusage: endpoint\n'
198
+ 'plan: Ultra (default_claude_max_20x)\n')
199
+ for secret in ('FILE-TOKEN', 'KEYCHAIN-TOKEN', 'KEYCHAIN-REFRESH'):
200
+ assert secret not in out + err
201
+
202
+
203
+ def test_plan_skips_credentials_for_override(monkeypatch):
204
+ monkeypatch.setattr(auth.sys, 'platform', 'darwin')
205
+ monkeypatch.setattr(auth.subprocess, 'run', lambda *args, **kwargs: pytest.fail('keychain called'))
206
+ assert auth.resolve_plan() is None
207
+
208
+
209
+ def test_unreadable_plan_is_ignored(monkeypatch, tmp_path, capsys):
210
+ monkeypatch.delenv('CLAUDE_CODE_OAUTH_TOKEN')
211
+ monkeypatch.setattr(auth.sys, 'platform', 'linux')
212
+ (tmp_path / '.credentials.json').write_text('malformed PRIVATE-TOKEN')
213
+ save(tmp_path, 'last-usage.json', ENDPOINT)
214
+ assert auth.resolve_plan() is None
215
+ assert cli.main(['-v']) == 0
216
+ assert capsys.readouterr().err == 'usage: endpoint\n'