claude-usage-limits 0.1.0__py3-none-any.whl
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/__init__.py +3 -0
- claude_usage/__main__.py +8 -0
- claude_usage/api.py +105 -0
- claude_usage/auth.py +79 -0
- claude_usage/cli.py +75 -0
- claude_usage/report.py +84 -0
- claude_usage_limits-0.1.0.dist-info/METADATA +240 -0
- claude_usage_limits-0.1.0.dist-info/RECORD +12 -0
- claude_usage_limits-0.1.0.dist-info/WHEEL +5 -0
- claude_usage_limits-0.1.0.dist-info/entry_points.txt +2 -0
- claude_usage_limits-0.1.0.dist-info/licenses/LICENSE +21 -0
- claude_usage_limits-0.1.0.dist-info/top_level.txt +1 -0
claude_usage/__init__.py
ADDED
claude_usage/__main__.py
ADDED
claude_usage/api.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Minimal OAuth usage client with endpoint and documented status-line caches.
|
|
2
|
+
|
|
3
|
+
The undocumented endpoint is rate limited: reuse answers for five minutes,
|
|
4
|
+
make at most one live request, then accept either cache for up to an hour.
|
|
5
|
+
No retries, polling, or token refresh. All HTTP goes through ``_get_json``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .auth import config_dir, resolve_token
|
|
17
|
+
from .report import shape
|
|
18
|
+
|
|
19
|
+
URL = "https://api.anthropic.com/api/oauth/usage"
|
|
20
|
+
FRESH = 300
|
|
21
|
+
MAX_AGE = 3600
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def write_cache(path, data):
|
|
25
|
+
"""Replace a cache atomically, never exposing a partially written JSON file."""
|
|
26
|
+
path = Path(path)
|
|
27
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
tmp = path.with_name(path.name + '.tmp')
|
|
29
|
+
with tmp.open('w', encoding='utf-8') as stream:
|
|
30
|
+
json.dump(data, stream)
|
|
31
|
+
os.replace(tmp, path)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _get_json(url, headers, timeout):
|
|
35
|
+
request = urllib.request.Request(url, headers=headers)
|
|
36
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
37
|
+
return json.load(response)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def from_endpoint(config, verbose=False):
|
|
41
|
+
headers = {
|
|
42
|
+
'Authorization': 'Bearer ' + resolve_token(config, verbose=verbose),
|
|
43
|
+
'anthropic-beta': 'oauth-2025-04-20',
|
|
44
|
+
'Accept': 'application/json',
|
|
45
|
+
}
|
|
46
|
+
try:
|
|
47
|
+
data = _get_json(URL, headers, 15)
|
|
48
|
+
except urllib.error.HTTPError as exc:
|
|
49
|
+
raise RuntimeError(f'HTTP {exc.code} from {URL}') from None
|
|
50
|
+
except urllib.error.URLError as exc:
|
|
51
|
+
raise RuntimeError(str(exc.reason)) from None
|
|
52
|
+
except (ValueError, TypeError):
|
|
53
|
+
# A rejected HTTP header can appear verbatim in the library exception.
|
|
54
|
+
raise RuntimeError(f'invalid request or JSON response from {URL}') from None
|
|
55
|
+
out = shape(data, 'endpoint')
|
|
56
|
+
write_cache(Path(config) / 'last-usage.json', data)
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def from_last(config, max_age):
|
|
61
|
+
path = Path(config) / 'last-usage.json'
|
|
62
|
+
if not path.exists():
|
|
63
|
+
raise RuntimeError('no saved endpoint answer yet')
|
|
64
|
+
age = time.time() - path.stat().st_mtime
|
|
65
|
+
if age >= max_age:
|
|
66
|
+
raise RuntimeError(f'last endpoint answer is {int(age // 60)} min old')
|
|
67
|
+
with path.open(encoding='utf-8') as stream:
|
|
68
|
+
data = json.load(stream)
|
|
69
|
+
source = f'endpoint, {int(age // 60)} min ago' if age >= 60 else 'endpoint'
|
|
70
|
+
return shape(data, source)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def from_cache(config):
|
|
74
|
+
path = Path(config) / 'last-statusline.json'
|
|
75
|
+
if not path.exists():
|
|
76
|
+
raise RuntimeError('no status-line cache yet (is the status line set to `claude-usage --statusline`?)')
|
|
77
|
+
age = time.time() - path.stat().st_mtime
|
|
78
|
+
if age >= MAX_AGE:
|
|
79
|
+
raise RuntimeError(f'status-line cache is {int(age // 60)} min old')
|
|
80
|
+
with path.open(encoding='utf-8') as stream:
|
|
81
|
+
data = json.load(stream)
|
|
82
|
+
if not isinstance(data, dict) or not data.get('rate_limits'):
|
|
83
|
+
raise RuntimeError('status-line cache has no rate_limits (Pro/Max only, after the first reply)')
|
|
84
|
+
return shape(data, f'status line, {int(age // 60)} min ago')
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def usage(config=None, verbose=False):
|
|
88
|
+
"""Return the first available source or raise its distinct failure reasons."""
|
|
89
|
+
config = Path(config) if config is not None else config_dir()
|
|
90
|
+
errors = []
|
|
91
|
+
sources = (lambda: from_last(config, FRESH),
|
|
92
|
+
lambda: from_endpoint(config, verbose=verbose),
|
|
93
|
+
lambda: from_last(config, MAX_AGE),
|
|
94
|
+
lambda: from_cache(config))
|
|
95
|
+
for source in sources:
|
|
96
|
+
try:
|
|
97
|
+
out = source()
|
|
98
|
+
except (RuntimeError, OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError) as exc:
|
|
99
|
+
if str(exc) not in errors:
|
|
100
|
+
errors.append(str(exc))
|
|
101
|
+
else:
|
|
102
|
+
if verbose:
|
|
103
|
+
print('usage: ' + out['source'], file=sys.stderr)
|
|
104
|
+
return out
|
|
105
|
+
raise RuntimeError('; '.join(errors))
|
claude_usage/auth.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Resolve Claude Code's OAuth access token from local credential stores.
|
|
2
|
+
|
|
3
|
+
Priority: explicit environment override, macOS Keychain, credentials JSON.
|
|
4
|
+
Only Claude Code refreshes tokens; this tool never writes credentials. Errors
|
|
5
|
+
and verbose notes describe sources without exposing credential contents.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
KEYCHAIN_SERVICE = "Claude Code-credentials"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CredentialsNotFound(RuntimeError):
|
|
19
|
+
"""Raised when no usable Claude Code OAuth access token can be located."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def config_dir():
|
|
23
|
+
return Path(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude"))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _token_from_credentials(creds):
|
|
27
|
+
try:
|
|
28
|
+
oauth = creds.get("claudeAiOauth") or {}
|
|
29
|
+
token = oauth.get("accessToken")
|
|
30
|
+
expires = oauth.get("expiresAt")
|
|
31
|
+
expired = expires is not None and float(expires) / 1000 < time.time()
|
|
32
|
+
except (AttributeError, TypeError, ValueError):
|
|
33
|
+
raise CredentialsNotFound("could not read Claude Code credentials; run `claude` once to log in") from None
|
|
34
|
+
if not isinstance(token, str) or not token:
|
|
35
|
+
raise CredentialsNotFound("credentials hold no OAuth access token; run `claude` once to log in")
|
|
36
|
+
if expired:
|
|
37
|
+
raise CredentialsNotFound("the access token has expired; open `claude` so it refreshes")
|
|
38
|
+
return token
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _log(verbose, source):
|
|
42
|
+
if verbose:
|
|
43
|
+
print("credentials: " + source, file=sys.stderr)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def resolve_token(config=None, verbose=False):
|
|
47
|
+
"""Return an access token, trying the file if the keychain is unavailable."""
|
|
48
|
+
override = os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")
|
|
49
|
+
if override:
|
|
50
|
+
_log(verbose, "CLAUDE_CODE_OAUTH_TOKEN")
|
|
51
|
+
return override
|
|
52
|
+
|
|
53
|
+
keychain_error = None
|
|
54
|
+
if sys.platform == "darwin":
|
|
55
|
+
try:
|
|
56
|
+
out = subprocess.run(
|
|
57
|
+
["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
|
|
58
|
+
capture_output=True, text=True, timeout=15,
|
|
59
|
+
)
|
|
60
|
+
if out.returncode == 0:
|
|
61
|
+
token = _token_from_credentials(json.loads(out.stdout))
|
|
62
|
+
_log(verbose, "macOS keychain")
|
|
63
|
+
return token
|
|
64
|
+
except CredentialsNotFound as exc:
|
|
65
|
+
keychain_error = exc
|
|
66
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
path = (Path(config) if config is not None else config_dir()) / '.credentials.json'
|
|
70
|
+
try:
|
|
71
|
+
with path.open(encoding="utf-8") as stream:
|
|
72
|
+
creds = json.load(stream)
|
|
73
|
+
except (OSError, ValueError):
|
|
74
|
+
if keychain_error is not None:
|
|
75
|
+
raise keychain_error from None
|
|
76
|
+
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")
|
|
79
|
+
return token
|
claude_usage/cli.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Command-line entry point for claude-usage."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .api import usage, write_cache
|
|
9
|
+
from .auth import config_dir
|
|
10
|
+
from .report import render_limits, render_plain, render_short, shape
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_parser():
|
|
14
|
+
p = argparse.ArgumentParser(
|
|
15
|
+
prog='claude-usage',
|
|
16
|
+
description="Show Claude subscription rate limits: the 5-hour and 7-day usage windows.",
|
|
17
|
+
)
|
|
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)')
|
|
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)')
|
|
22
|
+
p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
|
|
23
|
+
help='exit 1 when the 7-day window is at or above N%% (default 70)')
|
|
24
|
+
p.add_argument('--all', action='store_true',
|
|
25
|
+
help='add per-limit details and the weekly surface breakdown (plain format)')
|
|
26
|
+
p.add_argument('--format', choices=('plain', 'json', 'short'), default='plain',
|
|
27
|
+
help='output format (default: plain)')
|
|
28
|
+
p.add_argument('--statusline', action='store_true', help=argparse.SUPPRESS)
|
|
29
|
+
p.add_argument('-v', '--verbose', action='store_true',
|
|
30
|
+
help='log credential and usage sources to stderr')
|
|
31
|
+
p.add_argument('-V', '--version', action='version', version='claude-usage %s' % __version__)
|
|
32
|
+
return p
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def statusline():
|
|
36
|
+
"""Cache Claude Code's stdin payload and print a line, silently on failure."""
|
|
37
|
+
try:
|
|
38
|
+
data = json.loads(sys.stdin.read())
|
|
39
|
+
if not isinstance(data, dict):
|
|
40
|
+
return 0
|
|
41
|
+
write_cache(config_dir() / 'last-statusline.json', data)
|
|
42
|
+
print(render_short(shape(data, 'status line, 0 min ago')))
|
|
43
|
+
except (OSError, ValueError, TypeError, AttributeError, OverflowError):
|
|
44
|
+
pass
|
|
45
|
+
return 0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def main(argv=None):
|
|
49
|
+
args = build_parser().parse_args(argv)
|
|
50
|
+
if args.statusline:
|
|
51
|
+
return statusline()
|
|
52
|
+
try:
|
|
53
|
+
out = usage(verbose=args.verbose)
|
|
54
|
+
if args.format == 'json':
|
|
55
|
+
json.dump(out['raw'], sys.stdout, indent=1)
|
|
56
|
+
print()
|
|
57
|
+
elif args.format == 'short':
|
|
58
|
+
print(render_short(out))
|
|
59
|
+
else:
|
|
60
|
+
print(render_plain(out))
|
|
61
|
+
if args.all:
|
|
62
|
+
details = render_limits(out)
|
|
63
|
+
if details:
|
|
64
|
+
print(details)
|
|
65
|
+
except (RuntimeError, OSError, ValueError, TypeError, AttributeError, OverflowError) as exc:
|
|
66
|
+
print('claude-usage: ' + str(exc), file=sys.stderr)
|
|
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:
|
|
70
|
+
return 1
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == '__main__':
|
|
75
|
+
sys.exit(main())
|
claude_usage/report.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
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 either source, retaining its untouched payload for ``--json``."""
|
|
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
|
+
for key in ("five_hour", "seven_day"):
|
|
14
|
+
window = windows.get(key) or {}
|
|
15
|
+
reset = window.get("resets_at")
|
|
16
|
+
if status and reset is not None:
|
|
17
|
+
reset = datetime.fromtimestamp(reset, timezone.utc).isoformat()
|
|
18
|
+
used = window.get("used_percentage" if status else "utilization")
|
|
19
|
+
out[key] = {"utilization": float(used) if used is not None else None,
|
|
20
|
+
"resets_at": reset}
|
|
21
|
+
return out
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def when(iso):
|
|
25
|
+
if not iso:
|
|
26
|
+
return "reset time unknown"
|
|
27
|
+
t = datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone()
|
|
28
|
+
now = datetime.now(t.tzinfo)
|
|
29
|
+
mins = max(0, int((t - now).total_seconds() // 60))
|
|
30
|
+
h, m = divmod(mins, 60)
|
|
31
|
+
span = f"{h}h{m:02d}m" if h else f"{m}m"
|
|
32
|
+
day = "" if t.date() == now.date() else t.strftime("%a ")
|
|
33
|
+
return f"resets {day}{t:%H:%M} (in {span})"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def pct(window):
|
|
37
|
+
used = window.get("utilization")
|
|
38
|
+
return "?" if used is None else f"{used:.0f}%"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def render_plain(usage):
|
|
42
|
+
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'])}")
|
|
46
|
+
if usage['source'] != 'endpoint':
|
|
47
|
+
out.append(f"(from the {usage['source']})")
|
|
48
|
+
return '\n'.join(out)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def render_short(usage):
|
|
52
|
+
"""Render the same compact line for ``--format short`` and ``--statusline``."""
|
|
53
|
+
model = (usage['raw'].get('model') or {}).get('display_name')
|
|
54
|
+
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])}")
|
|
58
|
+
return ' ยท '.join(parts)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def render_limits(usage):
|
|
62
|
+
"""Render per-limit detail and the weekly surface split, when available."""
|
|
63
|
+
if usage['source'].startswith('status line'):
|
|
64
|
+
return '(details not available from the status-line source)'
|
|
65
|
+
raw = usage['raw']
|
|
66
|
+
out = []
|
|
67
|
+
limits = raw.get('limits') or []
|
|
68
|
+
if limits:
|
|
69
|
+
out.append('%-16s %7s %-10s %-7s %-12s %s' %
|
|
70
|
+
('kind', 'percent', 'severity', 'active', 'model', 'reset'))
|
|
71
|
+
out.append('-' * 78)
|
|
72
|
+
for limit in limits:
|
|
73
|
+
model = ((limit.get('scope') or {}).get('model') or {}).get('display_name', '')
|
|
74
|
+
out.append('%-16s %7s %-10s %-7s %-12s %s' % (
|
|
75
|
+
limit.get('kind', '?'), pct({'utilization': limit.get('percent')}),
|
|
76
|
+
limit.get('severity', '?'), 'active' if limit.get('is_active') else '',
|
|
77
|
+
model, when(limit.get('resets_at')),
|
|
78
|
+
))
|
|
79
|
+
rows = (raw.get('seven_day_breakdown') or {}).get('rows') or []
|
|
80
|
+
if rows:
|
|
81
|
+
out.append(', '.join('%s %s' % (row.get('display_name', row.get('key', '?')),
|
|
82
|
+
pct({'utilization': row.get('percent')}))
|
|
83
|
+
for row in sorted(rows, key=lambda row: -(row.get('percent') or 0))))
|
|
84
|
+
return '\n'.join(out)
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
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.
|
|
5
|
+
Author: claude-usage contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/javaisbetterthanpython/claude-usage
|
|
8
|
+
Project-URL: Issues, https://github.com/javaisbetterthanpython/claude-usage/issues
|
|
9
|
+
Keywords: claude,claude-code,anthropic,usage,rate-limit,cli
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Utilities
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
<h1 align="center">๐ claude-usage</h1>
|
|
22
|
+
|
|
23
|
+
<p align="center">
|
|
24
|
+
<b>Your Claude subscription limits โ right from your terminal.</b>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
<p align="center">
|
|
28
|
+
<a href="https://pypi.org/project/claude-usage-limits/"><img alt="PyPI" src="https://img.shields.io/pypi/v/claude-usage-limits?color=blue&label=PyPI"></a>
|
|
29
|
+
<img alt="Python" src="https://img.shields.io/badge/python-3.9%2B-blue">
|
|
30
|
+
<img alt="Platforms" src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey">
|
|
31
|
+
<img alt="Dependencies" src="https://img.shields.io/badge/dependencies-zero-brightgreen">
|
|
32
|
+
<img alt="License" src="https://img.shields.io/badge/license-MIT-green">
|
|
33
|
+
</p>
|
|
34
|
+
|
|
35
|
+
<p align="center">
|
|
36
|
+
<img src="https://raw.githubusercontent.com/javaisbetterthanpython/claude-usage/main/docs/demo.gif" alt="claude-usage demo" width="760">
|
|
37
|
+
</p>
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
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
|
|
43
|
+
scripts, hooks, and AI agents deciding when to back off. It uses the Claude Code
|
|
44
|
+
login already on your machine. No API key to manage, nothing to configure.
|
|
45
|
+
|
|
46
|
+
**Install `claude-usage-limits` from PyPI; the command is `claude-usage`.**
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
$ claude-usage
|
|
50
|
+
5-hour: 25% used, resets 16:10 (in 1h39m)
|
|
51
|
+
7-day: 59% used, resets Sun 03:00 (in 12h29m)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## โจ Features
|
|
55
|
+
|
|
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%.
|
|
58
|
+
- **๐ Extra detail** โ `--all` shows per-model limits, the active window, and the weekly surface split.
|
|
59
|
+
- **๐ Status line** โ a compact model and usage line that also feeds the documented fallback source.
|
|
60
|
+
- **๐งพ Plain, JSON, or short** โ readable in a terminal and easy to use from scripts.
|
|
61
|
+
- **๐ Cross-platform** โ macOS, Linux, and Windows; Python 3.9+.
|
|
62
|
+
- **๐ Zero dependencies** โ pure Python standard library.
|
|
63
|
+
- **๐ Local & private** โ reads your existing login; no telemetry or third-party calls.
|
|
64
|
+
|
|
65
|
+
## ๐ Quickstart
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install claude-usage-limits
|
|
69
|
+
claude-usage
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Sign in with `claude` on this machine first. Any running Claude Code session keeps
|
|
73
|
+
its access token fresh.
|
|
74
|
+
|
|
75
|
+
## ๐งโ๐ป Usage
|
|
76
|
+
|
|
77
|
+
| Command | What it does |
|
|
78
|
+
|---|---|
|
|
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) |
|
|
82
|
+
| `claude-usage --warn-7d [N]` | Exit 1 at or above N% of the 7-day window (default 70) |
|
|
83
|
+
| `claude-usage --all` | Add per-limit details and weekly surface breakdown in plain format |
|
|
84
|
+
| `claude-usage --format {plain,json,short}` | Choose output format (default plain) |
|
|
85
|
+
| `claude-usage --statusline` | Read Claude Code status-line JSON on stdin, cache it, print one compact line (hidden from help) |
|
|
86
|
+
| `claude-usage -v`, `--verbose` | Print only credential and usage source notes to stderr |
|
|
87
|
+
| `claude-usage -V`, `--version` | Print the version |
|
|
88
|
+
| `claude-usage -h`, `--help` | Show help |
|
|
89
|
+
|
|
90
|
+
Flags combine: `claude-usage --format short --warn 70 --warn-7d 90`.
|
|
91
|
+
`--json` and `--format` set the same option; the last one wins. `--all` adds detail
|
|
92
|
+
only in plain format, keeping JSON machine-readable and short output on one line.
|
|
93
|
+
|
|
94
|
+
<details>
|
|
95
|
+
<summary><b>๐ Example: <code>--all</code></b></summary>
|
|
96
|
+
|
|
97
|
+
```text
|
|
98
|
+
5-hour: 30% used, resets 16:10 (in 1h21m)
|
|
99
|
+
7-day: 60% used, resets Sun 03:00 (in 12h11m)
|
|
100
|
+
kind percent severity active model reset
|
|
101
|
+
------------------------------------------------------------------------------
|
|
102
|
+
session 30% normal resets 16:10 (in 1h21m)
|
|
103
|
+
weekly_all 60% normal active resets Sun 03:00 (in 12h11m)
|
|
104
|
+
weekly_scoped 9% normal Fable resets Sun 03:00 (in 12h11m)
|
|
105
|
+
Claude Code 96%, Cowork 4%, Chats 0%, Other 0%
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Detail fields depend on the account and endpoint response. With a status-line
|
|
109
|
+
answer, this prints `(details not available from the status-line source)` instead.
|
|
110
|
+
</details>
|
|
111
|
+
|
|
112
|
+
## ๐ค Using it from scripts and agents
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
claude-usage --warn 70 || echo "back off"
|
|
116
|
+
claude-usage --warn 70 --warn-7d 90 --format short
|
|
117
|
+
claude-usage --json
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The usual output is always printed. Exit codes: **0** for success, **1** when
|
|
121
|
+
either threshold trips or no source answers, **2** for an argument error.
|
|
122
|
+
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.
|
|
125
|
+
|
|
126
|
+
## ๐ Claude Code status line
|
|
127
|
+
|
|
128
|
+
Set `statusLine` in `~/.claude/settings.json` (merge this field into your existing
|
|
129
|
+
settings):
|
|
130
|
+
|
|
131
|
+
```json
|
|
132
|
+
{
|
|
133
|
+
"statusLine": {"type": "command", "command": "claude-usage --statusline"}
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Claude Code pipes its documented status JSON to the command on each repaint:
|
|
138
|
+
|
|
139
|
+
```text
|
|
140
|
+
Fable 5.1 ยท 5h 25% ยท 7d 59%
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Missing parts are omitted. This mode never looks up credentials or makes a network
|
|
144
|
+
call. It also writes `last-statusline.json`, feeding the documented fallback when
|
|
145
|
+
the endpoint is unavailable. Invalid input produces no output and exits 0.
|
|
146
|
+
`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
|
+
|
|
149
|
+
## ๐ค How it works
|
|
150
|
+
|
|
151
|
+
Sources are tried in this order:
|
|
152
|
+
|
|
153
|
+
1. `last-usage.json` if less than **5 minutes** old.
|
|
154
|
+
2. One live `GET https://api.anthropic.com/api/oauth/usage`, saved on success.
|
|
155
|
+
3. `last-usage.json` if less than **60 minutes** old.
|
|
156
|
+
4. `last-statusline.json` if less than **60 minutes** old and it has `rate_limits`.
|
|
157
|
+
|
|
158
|
+
Both caches live in `~/.claude`, or `CLAUDE_CONFIG_DIR` when set. Cache writes are
|
|
159
|
+
atomic. Cached answers at least a minute old show their source and age, e.g.
|
|
160
|
+
`(from the endpoint, 3 min ago)`; status-line answers always show their age.
|
|
161
|
+
If every source fails, the distinct reasons appear once each on stderr.
|
|
162
|
+
|
|
163
|
+
The endpoint returns **HTTP 429 on back-to-back calls**, sometimes blocking for
|
|
164
|
+
minutes. Five-minute reuse avoids repeating requests; there are no retries or
|
|
165
|
+
polling, and the single request times out after 15 seconds.
|
|
166
|
+
|
|
167
|
+
<details>
|
|
168
|
+
<summary><b>๐ Where credentials live (per OS)</b></summary>
|
|
169
|
+
|
|
170
|
+
Resolution is local-only, in this order:
|
|
171
|
+
|
|
172
|
+
1. `CLAUDE_CODE_OAUTH_TOKEN` environment override, used as-is.
|
|
173
|
+
2. macOS Keychain service **`Claude Code-credentials`**, read with
|
|
174
|
+
`security find-generic-password -s "Claude Code-credentials" -w`.
|
|
175
|
+
3. The credentials file, including on macOS when the keychain is unavailable
|
|
176
|
+
(for example, a locked keychain over SSH).
|
|
177
|
+
|
|
178
|
+
| OS | Credentials file |
|
|
179
|
+
|---|---|
|
|
180
|
+
| macOS / Linux | `~/.claude/.credentials.json` |
|
|
181
|
+
| Windows | `%USERPROFILE%\.claude\.credentials.json` |
|
|
182
|
+
|
|
183
|
+
`CLAUDE_CONFIG_DIR` changes the credentials file directory and both cache paths.
|
|
184
|
+
The token is `claudeAiOauth.accessToken`; `expiresAt` is milliseconds since epoch.
|
|
185
|
+
An expired token is refused: open `claude` so it refreshes.
|
|
186
|
+
|
|
187
|
+
For the protocol and a recipe to rebuild the tool, see
|
|
188
|
+
**[docs/HOW_THIS_WAS_BUILT.md](docs/HOW_THIS_WAS_BUILT.md)**.
|
|
189
|
+
</details>
|
|
190
|
+
|
|
191
|
+
## ๐ Privacy & security
|
|
192
|
+
|
|
193
|
+
- Reads existing credentials only; **never refreshes or writes credentials**.
|
|
194
|
+
- Sends the token only to **`api.anthropic.com`**, with the usage request.
|
|
195
|
+
- Writes only the two local usage caches; never modifies Claude Code settings.
|
|
196
|
+
- Never prints secrets or headers, including with `-v`.
|
|
197
|
+
- **No telemetry. No third-party calls.**
|
|
198
|
+
|
|
199
|
+
## โ ๏ธ Good to know
|
|
200
|
+
|
|
201
|
+
- The OAuth usage endpoint is **undocumented and rate limited**; it may change or
|
|
202
|
+
disappear. The documented status-line path is the fallback.
|
|
203
|
+
- Status-line `rate_limits` for subscription windows is **Pro/Max only**, appears
|
|
204
|
+
after the first API response, and drops individual windows after they reset.
|
|
205
|
+
It updates only while a Claude Code session is active and repainting.
|
|
206
|
+
- The observed endpoint response came from a Max account. Fields on other plans
|
|
207
|
+
may differ; an API key is not a Claude Code OAuth login.
|
|
208
|
+
- Any running `claude` keeps the access token fresh. This tool deliberately does
|
|
209
|
+
not implement the undocumented refresh flow.
|
|
210
|
+
- Use **`/feedback` in Claude Code** to ask Anthropic for an official
|
|
211
|
+
`claude usage` command.
|
|
212
|
+
|
|
213
|
+
## ๐ ๏ธ Install options
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
pip install claude-usage-limits # from PyPI
|
|
217
|
+
pipx install claude-usage-limits # isolated command installation
|
|
218
|
+
pip install . # from a local clone
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Requires Python 3.9+. **The PyPI distribution is `claude-usage-limits`; the command and
|
|
222
|
+
GitHub repo are `claude-usage`, and the import package is `claude_usage`.**
|
|
223
|
+
The PyPI names `claude-usage`, `claude-usage-cli`, and `claude-code-usage` belong to
|
|
224
|
+
unrelated projects.
|
|
225
|
+
|
|
226
|
+
## ๐ค Contributing
|
|
227
|
+
|
|
228
|
+
Issues and PRs are welcome. After installing the local project with `pip install -e .`,
|
|
229
|
+
run the tests with:
|
|
230
|
+
|
|
231
|
+
```bash
|
|
232
|
+
pip install pytest && pytest -q
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Tests use temporary config directories and mocked HTTP; they never contact the
|
|
236
|
+
endpoint or read your real credentials.
|
|
237
|
+
|
|
238
|
+
## ๐ License
|
|
239
|
+
|
|
240
|
+
[MIT](LICENSE) โ do whatever you like.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
claude_usage/__init__.py,sha256=Uos0nbon64pdUv-1ECDhcgsz_JO8hNA32KlMQgxbraE,93
|
|
2
|
+
claude_usage/__main__.py,sha256=EZ1c06spvKVrLJ0WEh85bBnQyMW6hfHB3knmrHtnES4,140
|
|
3
|
+
claude_usage/api.py,sha256=lSRclZPgq_NwBw8ZwvXO5cJ-gdKyIxCru1O-zTGV3FI,3925
|
|
4
|
+
claude_usage/auth.py,sha256=53bm6nsB5wdQG_1WSFcTKXlXGXjh6rNZo4xjMFhtbS4,2885
|
|
5
|
+
claude_usage/cli.py,sha256=ATcNkHMralbSydzGQTu2cMaRaU8kRcs0Zml37prCqOw,2946
|
|
6
|
+
claude_usage/report.py,sha256=0ghwPGq0Oo3hdH4r8voAWtgjQ8ylT_Ry3XgGPx83BmU,3465
|
|
7
|
+
claude_usage_limits-0.1.0.dist-info/licenses/LICENSE,sha256=gcLlaU8WKAeGqyA3jlPnGrvn7XKoTjKtqYEQlkWLXHg,1082
|
|
8
|
+
claude_usage_limits-0.1.0.dist-info/METADATA,sha256=i1BXDxcxZuoXw3Zv-gMb02FCWkt0nS9-aJT26QHME3I,10073
|
|
9
|
+
claude_usage_limits-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
claude_usage_limits-0.1.0.dist-info/entry_points.txt,sha256=Rd71c-eBQgIz_da7BIfyduAWKA7xFm4jn2AebZyHNwM,55
|
|
11
|
+
claude_usage_limits-0.1.0.dist-info/top_level.txt,sha256=3lyG45_nvRw3wN6ywp-qzuuSUvq94LwGnmQcViXe84A,13
|
|
12
|
+
claude_usage_limits-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 claude-usage contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
claude_usage
|