codex-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.
@@ -0,0 +1,3 @@
1
+ """codex-usage: read your Codex plan rate-limit windows."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ """Run codex-usage with ``python -m codex_usage``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == '__main__':
8
+ sys.exit(main())
codex_usage/api.py ADDED
@@ -0,0 +1,167 @@
1
+ """Minimal Codex usage client with endpoint caching and a session-log fallback.
2
+
3
+ Reuse endpoint answers for five minutes, make at most one live request, then
4
+ accept a saved answer or a session event for up to an hour. All HTTP goes
5
+ through ``_get_json``.
6
+ """
7
+
8
+ import http.client
9
+ import json
10
+ import os
11
+ import stat
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from pathlib import Path
18
+
19
+ from . import __version__
20
+ from .auth import config_dir, resolve_credentials
21
+ from .report import session_timestamp, shape
22
+
23
+ URL = "https://chatgpt.com/backend-api/wham/usage"
24
+ FRESH = 300
25
+ MAX_AGE = 3600
26
+
27
+
28
+ def write_cache(path, data):
29
+ """Replace a cache atomically, never exposing a partially written JSON file."""
30
+ path = Path(path)
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ tmp = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
33
+ prefix=path.name + '.', suffix='.tmp', delete=False)
34
+ try:
35
+ with tmp:
36
+ json.dump(data, tmp)
37
+ os.replace(tmp.name, path)
38
+ finally:
39
+ Path(tmp.name).unlink(missing_ok=True)
40
+
41
+
42
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
43
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
44
+ # urllib otherwise forwards the Authorization header to redirect targets.
45
+ return None
46
+
47
+
48
+ def _get_json(url, headers, timeout):
49
+ request = urllib.request.Request(url, headers=headers)
50
+ opener = urllib.request.build_opener(_NoRedirect())
51
+ with opener.open(request, timeout=timeout) as response:
52
+ return json.load(response)
53
+
54
+
55
+ def from_endpoint(config, verbose=False):
56
+ token, account_id, _ = resolve_credentials(config, verbose=verbose)
57
+ headers = {
58
+ 'Authorization': 'Bearer ' + token,
59
+ 'Accept': 'application/json',
60
+ 'User-Agent': f'codex-usage/{__version__}',
61
+ }
62
+ if account_id:
63
+ headers['ChatGPT-Account-Id'] = account_id
64
+ try:
65
+ data = _get_json(URL, headers, 15)
66
+ except urllib.error.HTTPError as exc:
67
+ raise RuntimeError(f'HTTP {exc.code} from {URL}') from None
68
+ except (OSError, http.client.HTTPException):
69
+ raise RuntimeError(f'could not reach {URL}') from None
70
+ except (ValueError, TypeError):
71
+ # A rejected HTTP header can appear verbatim in the library exception.
72
+ raise RuntimeError(f'invalid request or JSON response from {URL}') from None
73
+ out = shape(data, 'endpoint')
74
+ write_cache(Path(config) / 'last-usage.json', out['raw'])
75
+ return out
76
+
77
+
78
+ def from_last(config, max_age):
79
+ path = Path(config) / 'last-usage.json'
80
+ try:
81
+ age = time.time() - path.stat().st_mtime
82
+ if age >= max_age:
83
+ raise RuntimeError(f'last endpoint answer is {int(age // 60)} min old')
84
+ with path.open(encoding='utf-8') as stream:
85
+ data = json.load(stream)
86
+ except FileNotFoundError:
87
+ raise RuntimeError('no saved endpoint answer yet') from None
88
+ source = f'endpoint, {int(age // 60)} min ago' if age >= 60 else 'endpoint'
89
+ return shape(data, source)
90
+
91
+
92
+ def _newest_session(config):
93
+ sessions = Path(config) / 'sessions'
94
+ days = sorted(sessions.glob('[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]'), reverse=True)
95
+ newest, latest_mtime = None, float('-inf')
96
+ for day in days:
97
+ for path in day.glob('rollout-*.jsonl'):
98
+ try:
99
+ info = path.stat()
100
+ except FileNotFoundError:
101
+ continue
102
+ if stat.S_ISREG(info.st_mode) and info.st_mtime_ns > latest_mtime:
103
+ newest, latest_mtime = path, info.st_mtime_ns
104
+ return newest
105
+
106
+
107
+ def _session_snapshot(path):
108
+ model, snapshot, stamp = None, None, None
109
+ with path.open('rb') as stream:
110
+ for line in stream:
111
+ try:
112
+ event = json.loads(line)
113
+ payload = event.get('payload')
114
+ if not isinstance(payload, dict):
115
+ continue
116
+ if event.get('type') == 'turn_context' and isinstance(payload.get('model'), str):
117
+ model = payload['model']
118
+ if event.get('type') != 'event_msg' or payload.get('type') != 'token_count':
119
+ continue
120
+ limits = payload.get('rate_limits')
121
+ if (isinstance(limits, dict) and limits.get('limit_id', 'codex') == 'codex'
122
+ and any(isinstance(limits.get(key), dict) and limits[key]
123
+ for key in ('primary', 'secondary'))):
124
+ stamp = session_timestamp(event['timestamp'])
125
+ snapshot = dict(limits, timestamp=event['timestamp'])
126
+ except (ValueError, TypeError, AttributeError, KeyError, OverflowError):
127
+ continue
128
+ if snapshot is None:
129
+ raise RuntimeError('newest Codex session log has no Codex rate limits')
130
+ if model:
131
+ snapshot['model'] = model
132
+ return snapshot, stamp
133
+
134
+
135
+ def from_session(config):
136
+ path = _newest_session(config)
137
+ if path is None:
138
+ raise RuntimeError('no Codex session log yet')
139
+ data, stamp = _session_snapshot(path)
140
+ age = max(0, time.time() - stamp)
141
+ if age >= MAX_AGE:
142
+ raise RuntimeError(f'Codex session log usage is {int(age // 60)} min old')
143
+ out = shape(data, f'session log, {int(age // 60)} min ago')
144
+ if not out['windows']:
145
+ raise RuntimeError('all Codex session log rate limits have reset')
146
+ return out
147
+
148
+
149
+ def usage(config=None, verbose=False):
150
+ """Return the first available source or raise its distinct failure reasons."""
151
+ config = Path(config) if config is not None else config_dir()
152
+ errors = []
153
+ sources = (lambda: from_last(config, FRESH),
154
+ lambda: from_endpoint(config, verbose=verbose),
155
+ lambda: from_last(config, MAX_AGE),
156
+ lambda: from_session(config))
157
+ for source in sources:
158
+ try:
159
+ out = source()
160
+ except (RuntimeError, OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError) as exc:
161
+ if str(exc) not in errors:
162
+ errors.append(str(exc))
163
+ else:
164
+ if verbose:
165
+ print('usage: ' + out['source'], file=sys.stderr)
166
+ return out
167
+ raise RuntimeError('; '.join(errors))
codex_usage/auth.py ADDED
@@ -0,0 +1,110 @@
1
+ """Resolve Codex's ChatGPT access token from local credential stores.
2
+
3
+ Priority: explicit environment override, auth.json, macOS Keychain.
4
+ Only Codex refreshes tokens. Errors and verbose notes never include secrets.
5
+ """
6
+
7
+ import base64
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ KEYCHAIN_SERVICE = "Codex Auth"
16
+ AUTH_CLAIM = "https://api.openai.com/auth"
17
+ LOGIN_HELP = "run `codex login` to sign in with ChatGPT"
18
+
19
+
20
+ class CredentialsNotFound(RuntimeError):
21
+ """Raised when no usable Codex ChatGPT access token can be located."""
22
+
23
+
24
+ def config_dir():
25
+ return Path(os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
26
+
27
+
28
+ def _claims(token):
29
+ try:
30
+ _, payload, _ = token.split('.')
31
+ data = json.loads(base64.urlsafe_b64decode(payload + '=' * (-len(payload) % 4)))
32
+ except (ValueError, TypeError):
33
+ return {}
34
+ return data if isinstance(data, dict) else {}
35
+
36
+
37
+ def _credentials(token, account_id):
38
+ claims = _claims(token)
39
+ expires = claims.get("exp")
40
+ if isinstance(expires, (int, float)) and expires < time.time():
41
+ raise CredentialsNotFound("the access token has expired; open `codex` so it refreshes")
42
+ auth = claims.get(AUTH_CLAIM)
43
+ if not isinstance(auth, dict):
44
+ auth = {}
45
+ if not isinstance(account_id, str) or not account_id:
46
+ account_id = auth.get("chatgpt_account_id")
47
+ plan = auth.get("chatgpt_plan_type")
48
+ return token, account_id if isinstance(account_id, str) else None, plan if isinstance(plan, str) else None
49
+
50
+
51
+ def _from_credentials(creds):
52
+ if not isinstance(creds, dict):
53
+ raise CredentialsNotFound("could not read Codex credentials; " + LOGIN_HELP)
54
+ tokens = creds.get("tokens")
55
+ if not tokens and (creds.get("OPENAI_API_KEY") or creds.get("auth_mode") == "apikey"):
56
+ raise CredentialsNotFound("an API-key login has no ChatGPT plan limits; " + LOGIN_HELP)
57
+ token = tokens.get("access_token") if isinstance(tokens, dict) else None
58
+ if not isinstance(token, str) or not token:
59
+ raise CredentialsNotFound("credentials hold no ChatGPT access token; " + LOGIN_HELP)
60
+ return _credentials(token, tokens.get("account_id"))
61
+
62
+
63
+ def _from_keychain():
64
+ try:
65
+ out = subprocess.run(
66
+ ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
67
+ capture_output=True, text=True, timeout=15,
68
+ )
69
+ if out.returncode == 0:
70
+ return _from_credentials(json.loads(out.stdout))
71
+ except (OSError, ValueError, subprocess.SubprocessError):
72
+ pass
73
+ return None
74
+
75
+
76
+ def _resolve_credentials(config):
77
+ override = os.environ.get("CODEX_ACCESS_TOKEN")
78
+ if override:
79
+ return _credentials(override, os.environ.get("CODEX_ACCOUNT_ID")), "CODEX_ACCESS_TOKEN"
80
+
81
+ path = (Path(config) if config is not None else config_dir()) / 'auth.json'
82
+ try:
83
+ with path.open(encoding="utf-8") as stream:
84
+ creds = json.load(stream)
85
+ except FileNotFoundError:
86
+ if sys.platform == "darwin":
87
+ keychain = _from_keychain()
88
+ if keychain is not None:
89
+ return keychain, "macOS keychain"
90
+ raise CredentialsNotFound("no readable Codex auth.json; " + LOGIN_HELP) from None
91
+ except (OSError, ValueError):
92
+ raise CredentialsNotFound("could not read Codex auth.json; " + LOGIN_HELP) from None
93
+ return _from_credentials(creds), "credentials file"
94
+
95
+
96
+ def resolve_credentials(config=None, verbose=False):
97
+ """Return the access token, optional account ID, and optional plan."""
98
+ credentials, source = _resolve_credentials(config)
99
+ if verbose:
100
+ print("credentials: " + source, file=sys.stderr)
101
+ return credentials
102
+
103
+
104
+ def resolve_plan(config=None):
105
+ """Return the raw plan from the selected credential's JWT when available."""
106
+ try:
107
+ _, _, plan = resolve_credentials(config)
108
+ except CredentialsNotFound:
109
+ return None
110
+ return plan
codex_usage/cli.py ADDED
@@ -0,0 +1,66 @@
1
+ """Command-line entry point for codex-usage."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .api import usage
9
+ from .auth import resolve_plan
10
+ from .report import render_limits, render_plain, render_short, warning_reached
11
+
12
+
13
+ def build_parser():
14
+ p = argparse.ArgumentParser(
15
+ prog='codex-usage',
16
+ description="Show Codex plan rate limits, including the 5-hour window when available.",
17
+ )
18
+ p.add_argument('--json', action='store_const', dest='format', const='json',
19
+ help='print the raw usage JSON (alias for --format json)')
20
+ p.add_argument('--warn', type=int, nargs='?', const=70, metavar='N',
21
+ help='exit 1 when any usage 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 main 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 account summary (plain format)')
26
+ p.add_argument('--format', choices=('plain', 'json', 'short'), default='plain',
27
+ help='output format (default: plain)')
28
+ p.add_argument('-v', '--verbose', action='store_true',
29
+ help='log credential and usage sources and the plan to stderr')
30
+ p.add_argument('-V', '--version', action='version', version='codex-usage %s' % __version__)
31
+ return p
32
+
33
+
34
+ def main(argv=None):
35
+ args = build_parser().parse_args(argv)
36
+ try:
37
+ out = usage(verbose=args.verbose)
38
+ if args.verbose:
39
+ plan = out['raw'].get('plan_type')
40
+ if not isinstance(plan, str) or not plan:
41
+ plan = resolve_plan()
42
+ if plan:
43
+ print('plan: ' + plan, file=sys.stderr)
44
+ if args.format == 'json':
45
+ json.dump(out['raw'], sys.stdout, indent=1)
46
+ print()
47
+ elif args.format == 'short':
48
+ print(render_short(out))
49
+ else:
50
+ print(render_plain(out))
51
+ if args.all:
52
+ details = render_limits(out)
53
+ if details:
54
+ print(details)
55
+ except (RuntimeError, OSError, ValueError, TypeError, AttributeError, OverflowError) as exc:
56
+ print('codex-usage: ' + str(exc), file=sys.stderr)
57
+ return 1
58
+ if args.warn is not None and warning_reached(out, args.warn):
59
+ return 1
60
+ if args.warn_7d is not None and warning_reached(out, args.warn_7d, weekly_only=True):
61
+ return 1
62
+ return 0
63
+
64
+
65
+ if __name__ == '__main__':
66
+ sys.exit(main())
codex_usage/report.py ADDED
@@ -0,0 +1,155 @@
1
+ """Turn endpoint and session-log payloads into compact usage reports."""
2
+
3
+ import re
4
+ import time
5
+ from datetime import datetime, timezone
6
+
7
+
8
+ IDENTITY_FIELDS = ('email', 'user_id', 'account_id')
9
+
10
+
11
+ def strip_identity(data):
12
+ if not isinstance(data, dict):
13
+ raise ValueError("usage data is not a JSON object")
14
+ return {key: value for key, value in data.items() if key not in IDENTITY_FIELDS}
15
+
16
+
17
+ def _label(seconds):
18
+ for size, label, short in ((86400, 'day', 'd'), (3600, 'hour', 'h')):
19
+ if seconds and seconds % size == 0:
20
+ count = int(seconds // size)
21
+ return f'{count}-{label}', f'{count}{short}'
22
+ count = int(seconds // 60)
23
+ return f'{count}-min', f'{count}m'
24
+
25
+
26
+ def _window(raw, seconds, reset, name, suffix=''):
27
+ label, short = _label(seconds)
28
+ used = raw.get('used_percent')
29
+ return {'name': name, 'label': label + suffix, 'short': short + suffix,
30
+ 'utilization': float(used) if used is not None else None,
31
+ 'resets_at': datetime.fromtimestamp(reset, timezone.utc).isoformat() if reset is not None else None}
32
+
33
+
34
+ def _endpoint_windows(limit, name, suffix=''):
35
+ windows = [window for key in ('primary_window', 'secondary_window')
36
+ if isinstance(window := limit.get(key), dict)
37
+ and isinstance(window.get('limit_window_seconds'), (int, float))]
38
+ windows.sort(key=lambda window: window['limit_window_seconds'])
39
+ return [_window(window, window['limit_window_seconds'], window.get('reset_at'), name, suffix)
40
+ for window in windows]
41
+
42
+
43
+ def _endpoint_limits(raw):
44
+ yield 'codex', raw.get('rate_limit') or {}, ''
45
+ for entry in raw.get('additional_rate_limits') or []:
46
+ name = entry.get('limit_name') or entry.get('metered_feature') or 'other'
47
+ yield name, entry.get('rate_limit') or {}, ' ' + name
48
+
49
+
50
+ def session_timestamp(iso):
51
+ # Codex writes nanoseconds, while Python 3.9 expects 3 or 6 fractional digits.
52
+ iso = re.sub(r'\.(\d+)', lambda match: '.' + match[1][:6].ljust(6, '0'), iso, count=1)
53
+ timestamp = datetime.fromisoformat(iso.replace('Z', '+00:00'))
54
+ if timestamp.tzinfo is None:
55
+ timestamp = timestamp.replace(tzinfo=timezone.utc)
56
+ return timestamp.timestamp()
57
+
58
+
59
+ def _session_windows(raw):
60
+ now = time.time()
61
+ windows = [window for key in ('primary', 'secondary')
62
+ if isinstance(window := raw.get(key), dict)
63
+ and isinstance(window.get('window_minutes'), (int, float))]
64
+ windows.sort(key=lambda window: window['window_minutes'])
65
+ out = []
66
+ for window in windows:
67
+ reset = window.get('resets_at')
68
+ relative = window.get('resets_in_seconds')
69
+ if reset is None and relative is not None and raw.get('timestamp'):
70
+ reset = session_timestamp(raw['timestamp']) + relative
71
+ if reset is None or reset > now:
72
+ out.append(_window(window, window['window_minutes'] * 60, reset, 'codex'))
73
+ return out
74
+
75
+
76
+ def shape(data, source):
77
+ """Normalize usage windows and keep the source payload with identities removed."""
78
+ raw = strip_identity(data)
79
+ if source.startswith('session log'):
80
+ windows = _session_windows(raw)
81
+ else:
82
+ windows = [window for name, limit, suffix in _endpoint_limits(raw)
83
+ for window in _endpoint_windows(limit, name, suffix)]
84
+ return {'source': source, 'raw': raw, 'windows': windows}
85
+
86
+
87
+ def warning_reached(usage, threshold, weekly_only=False):
88
+ """Check all windows, or only the main seven-day window."""
89
+ return any(window['utilization'] is not None and window['utilization'] >= threshold
90
+ for window in usage['windows'] if not weekly_only or window['label'] == '7-day')
91
+
92
+
93
+ def when(iso):
94
+ if not iso:
95
+ return "reset time unknown"
96
+ t = datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone()
97
+ now = datetime.now(t.tzinfo)
98
+ mins = max(0, int((t - now).total_seconds() // 60))
99
+ h, m = divmod(mins, 60)
100
+ span = f"{h}h{m:02d}m" if h else f"{m}m"
101
+ day = "" if t.date() == now.date() else t.strftime("%a ")
102
+ return f"resets {day}{t:%H:%M} (in {span})"
103
+
104
+
105
+ def pct(window):
106
+ used = window.get("utilization")
107
+ return "?" if used is None else f"{used:.0f}%"
108
+
109
+
110
+ def render_plain(usage):
111
+ out = []
112
+ for window in usage['windows']:
113
+ out.append(f"{window['label']}: {pct(window)} used, {when(window['resets_at'])}")
114
+ if usage['source'] != 'endpoint':
115
+ out.append(f"(from the {usage['source']})")
116
+ return '\n'.join(out)
117
+
118
+
119
+ def render_short(usage):
120
+ """Render a compact line, with a model name for session-log answers."""
121
+ model = usage['raw'].get('model') if usage['source'].startswith('session log') else None
122
+ parts = [model] if model else []
123
+ for window in usage['windows']:
124
+ if window['utilization'] is not None:
125
+ parts.append(f"{window['short']} {pct(window)}")
126
+ return ' ยท '.join(parts)
127
+
128
+
129
+ def render_limits(usage):
130
+ """Render per-limit detail and the account summary, when available."""
131
+ if usage['source'].startswith('session log'):
132
+ return '(details not available from the session-log source)'
133
+ raw = usage['raw']
134
+ row = '%-14s %-8s %7s %-10s %s'
135
+ out = []
136
+ limits = list(_endpoint_limits(raw))
137
+ limits.append(('code review', raw.get('code_review_rate_limit') or {}, ''))
138
+ for name, limit, _ in limits:
139
+ status = 'limit hit' if limit.get('limit_reached') or limit.get('allowed') is False else 'allowed'
140
+ for window in _endpoint_windows(limit, name):
141
+ out.append(row % (name, window['label'], pct(window), status, when(window['resets_at'])))
142
+ if out:
143
+ out[:0] = [row % ('limit', 'window', 'percent', 'status', 'reset'), '-' * 78]
144
+ summary = []
145
+ if raw.get('plan_type'):
146
+ summary.append(f"plan {raw['plan_type']}")
147
+ balance = (raw.get('credits') or {}).get('balance')
148
+ if balance is not None:
149
+ summary.append(f'credits {balance}')
150
+ resets = (raw.get('rate_limit_reset_credits') or {}).get('available_count')
151
+ if resets is not None:
152
+ summary.append(f'reset credits {resets} available')
153
+ if summary:
154
+ out.append(' ยท '.join(summary))
155
+ return '\n'.join(out)
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.4
2
+ Name: codex-usage-limits
3
+ Version: 0.1.0
4
+ Summary: CLI for Codex plan usage and rate limits, with session-log fallback and warning thresholds.
5
+ Author: codex-usage contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/javaisbetterthanpython/codex-usage
8
+ Project-URL: Issues, https://github.com/javaisbetterthanpython/codex-usage/issues
9
+ Keywords: codex,openai,chatgpt,usage,rate-limit,weekly-usage,subscription,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">๐Ÿ“Š codex-usage</h1>
22
+
23
+ <p align="center">
24
+ <b>Your Codex plan limits โ€” right from your terminal.</b>
25
+ </p>
26
+
27
+ <p align="center">
28
+ <a href="https://pypi.org/project/codex-usage-limits/"><img alt="PyPI" src="https://img.shields.io/pypi/v/codex-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/codex-usage/main/docs/demo.gif" alt="codex-usage demo" width="760">
37
+ </p>
38
+
39
+ ---
40
+
41
+ Codex shows your plan limits only in the interactive `/status` screen.
42
+ **`codex-usage` gives you plan usage from the shell** โ€” for scripts, hooks, and
43
+ AI agents deciding when to back off. It uses the Codex login already on your
44
+ machine.
45
+
46
+ The 5-hour window appears when your plan has one and the usage source reports
47
+ it. Some plans have weekly limits only.
48
+
49
+ **Install `codex-usage-limits` from PyPI. The command is `codex-usage`.**
50
+
51
+ ```text
52
+ $ codex-usage
53
+ 7-day: 59% used, resets Sun 03:00 (in 12h29m)
54
+ ```
55
+
56
+ ## โœจ Features
57
+
58
+ - **Usage windows** โ€” 5-hour and weekly usage when available, additional limits, and local reset times.
59
+ - **๐Ÿšฆ Thresholds for scripts** โ€” `--warn [N]` checks any usage window. `--warn-7d [N]` checks the main weekly window. Both exit 1 at or above N%.
60
+ - **๐Ÿ“Š Extra detail** โ€” `--all` shows limit status, code-review usage, and the plan and credits when available.
61
+ - **๐Ÿ“œ Session logs** โ€” a local fallback when the endpoint and its saved answer are unavailable.
62
+ - **๐Ÿงพ Plain, JSON, or short** โ€” readable in a terminal and easy to use from scripts.
63
+ - **๐ŸŒ Cross-platform** โ€” macOS, Linux, and Windows with Python 3.9+.
64
+ - **๐Ÿ”‹ Zero dependencies** โ€” pure Python standard library.
65
+ - **๐Ÿ”’ Local & private** โ€” reads your existing login and sends the token only to ChatGPT.
66
+
67
+ ## ๐Ÿš€ Quickstart
68
+
69
+ ```bash
70
+ pip install codex-usage-limits
71
+ codex-usage
72
+ ```
73
+
74
+ Sign in with ChatGPT using `codex login` on this machine first. Open `codex` if
75
+ the access token needs to refresh.
76
+
77
+ ## ๐Ÿง‘โ€๐Ÿ’ป Usage
78
+
79
+ | Command | What it does |
80
+ |---|---|
81
+ | `codex-usage` | Available usage windows and their reset times |
82
+ | `codex-usage --json` | Raw usage JSON with identity fields removed (alias for `--format json`) |
83
+ | `codex-usage --warn [N]` | Exit 1 when any usage window reaches N% (default 70) |
84
+ | `codex-usage --warn-7d [N]` | Exit 1 at or above N% of the main 7-day window (default 70) |
85
+ | `codex-usage --all` | Add per-limit details and the account summary in plain format |
86
+ | `codex-usage --format {plain,json,short}` | Choose output format (default plain) |
87
+ | `codex-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
88
+ | `codex-usage -V`, `--version` | Print the version |
89
+ | `codex-usage -h`, `--help` | Show help |
90
+
91
+ Flags combine. For example, run `codex-usage --format short --warn 70 --warn-7d 90`.
92
+ `--json` and `--format` set the same option, and the last one wins. `--all` adds
93
+ detail in plain format.
94
+
95
+ <details>
96
+ <summary><b>๐Ÿ“Š Example <code>--all</code> output</b></summary>
97
+
98
+ ```text
99
+ 5-hour: 23% used, resets 14:00 (in 2h41m)
100
+ 7-day: 59% used, resets Sun 03:00 (in 15h41m)
101
+ limit window percent status reset
102
+ ------------------------------------------------------------------------------
103
+ codex 5-hour 23% allowed resets 14:00 (in 2h41m)
104
+ codex 7-day 59% allowed resets Sun 03:00 (in 15h41m)
105
+ code review 7-day 4% allowed resets Sun 03:00 (in 15h41m)
106
+ plan pro ยท credits 0 ยท reset credits 2 available
107
+ ```
108
+
109
+ Detail fields depend on the account and endpoint response. With a session-log
110
+ answer, the CLI adds `(details not available from the session-log source)`.
111
+ </details>
112
+
113
+ ## ๐Ÿค– Using it from scripts and agents
114
+
115
+ ```bash
116
+ codex-usage --warn 70 || echo "back off"
117
+ codex-usage --warn 70 --warn-7d 90 --format short
118
+ codex-usage --json
119
+ ```
120
+
121
+ The usual output is printed even when a threshold trips. Exit codes are **0**
122
+ for success, **1** when a threshold trips or no source answers, and **2** for an
123
+ argument error. Thresholds are inclusive, so `--warn` exits 1 at exactly 70%.
124
+ Missing or null windows are skipped. `--warn` includes additional usage limits,
125
+ and `--warn-7d` checks only the main 7-day window. Code-review limits appear
126
+ under `--all`.
127
+
128
+ ## ๐Ÿ“œ Codex session logs
129
+
130
+ Codex records rate-limit snapshots in `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`
131
+ while you use it. When the endpoint and saved answer are unavailable, the CLI
132
+ reads the last Codex rate-limit snapshot from the newest session log. It uses
133
+ the event time to show the age and leaves out windows whose reset time has passed.
134
+
135
+ ```text
136
+ $ codex-usage
137
+ 5-hour: 23% used, resets 14:00 (in 2h41m)
138
+ 7-day: 59% used, resets Sun 03:00 (in 15h41m)
139
+ (from the session log, 3 min ago)
140
+ ```
141
+
142
+ With `--format short`, a session-log answer includes the model when available.
143
+
144
+ ```text
145
+ gpt-6.2-sol ยท 5h 23% ยท 7d 59%
146
+ ```
147
+
148
+ ## ๐Ÿค” How it works
149
+
150
+ Sources are tried in this order.
151
+
152
+ 1. `last-usage.json` if less than **5 minutes** old.
153
+ 2. One live `GET https://chatgpt.com/backend-api/wham/usage`, saved on success.
154
+ 3. `last-usage.json` if less than **60 minutes** old.
155
+ 4. The newest Codex session log if its selected usage event is less than **60 minutes** old.
156
+
157
+ The cache and logs live in `~/.codex`, or `CODEX_HOME` when set. Cache writes
158
+ are atomic. Cached answers at least a minute old show their source and age, for
159
+ example `(from the endpoint, 3 min ago)`. Session-log answers always show their
160
+ age in plain output. If every source fails, the distinct reasons appear once
161
+ each on stderr.
162
+
163
+ Five-minute reuse avoids repeating requests. The single request times out
164
+ after 15 seconds and the CLI never polls or retries.
165
+
166
+ <details>
167
+ <summary><b>๐Ÿ” Where credentials live (per OS)</b></summary>
168
+
169
+ The CLI looks for credentials in this order.
170
+
171
+ 1. `CODEX_ACCESS_TOKEN` environment override, used as-is. Set `CODEX_ACCOUNT_ID`
172
+ to override the account ID from the token.
173
+ 2. The `auth.json` credentials file.
174
+ 3. macOS Keychain service **`Codex Auth`**, read with
175
+ `security find-generic-password -s "Codex Auth" -w` when the file is missing.
176
+
177
+ | OS | Credentials file |
178
+ |---|---|
179
+ | macOS / Linux | `~/.codex/auth.json` |
180
+ | Windows | `%USERPROFILE%\.codex\auth.json` |
181
+
182
+ `CODEX_HOME` changes the credentials, cache, and session-log paths. The token is
183
+ `tokens.access_token`. If the token has expired, open `codex` so it refreshes.
184
+
185
+ For the protocol and a recipe to rebuild the tool, see
186
+ **[docs/HOW_THIS_WAS_BUILT.md](docs/HOW_THIS_WAS_BUILT.md)**.
187
+ </details>
188
+
189
+ ## ๐Ÿ”’ Privacy & security
190
+
191
+ - Reads existing credentials and session logs. Codex handles token refresh.
192
+ - Sends the token only to **`chatgpt.com`**, with the usage request.
193
+ - Removes `email`, `user_id`, and `account_id` before writing the cache or printing JSON.
194
+ - Keeps tokens, request headers, and identities out of errors and verbose output.
195
+ - **No telemetry or third-party calls.**
196
+
197
+ ## โš ๏ธ Good to know
198
+
199
+ - The usage endpoint is **undocumented**. Codex itself calls it, and the format may change.
200
+ - API-key logins have no ChatGPT plan limits. Use `codex login` to sign in with ChatGPT.
201
+ - Session logs update only while Codex runs. Old readings and reset windows age out.
202
+ - Plans differ. Some report a 5-hour and a weekly window, while others report only the weekly window.
203
+
204
+ ## ๐Ÿ› ๏ธ Install options
205
+
206
+ ```bash
207
+ pip install codex-usage-limits # from PyPI
208
+ pipx install codex-usage-limits # isolated command installation
209
+ pip install . # from a local clone
210
+ ```
211
+
212
+ Requires Python 3.9+. The PyPI distribution is **`codex-usage-limits`** because
213
+ `codex-usage` is taken on PyPI. The command and GitHub repo are `codex-usage`,
214
+ and the import package is `codex_usage`.
215
+
216
+ ## ๐Ÿค Contributing
217
+
218
+ Issues and PRs are welcome. After installing the local project with `pip install -e .`,
219
+ run the tests with:
220
+
221
+ ```bash
222
+ pip install pytest && pytest -q
223
+ ```
224
+
225
+ Tests use temporary config directories and mocked HTTP. They never contact the
226
+ endpoint or read your real credentials.
227
+
228
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
229
+ [agg](https://github.com/asciinema/agg/releases) and the DejaVu Sans Mono font. The
230
+ recorder runs the CLI against an illustrative cache and session log with network
231
+ access disabled; it needs no credentials. The README embeds the resulting `docs/demo.gif`.
232
+
233
+ ## ๐Ÿ“„ License
234
+
235
+ [MIT](LICENSE) โ€” do whatever you like.
@@ -0,0 +1,12 @@
1
+ codex_usage/__init__.py,sha256=ZFKGmH4xF4K_9OXES18Il2c-jteqPmGsx94MJNdH5Qo,83
2
+ codex_usage/__main__.py,sha256=OaQx9pkRFP1NfrS1cDKsfUPIBidolxoyFf_tqOjEaNs,138
3
+ codex_usage/api.py,sha256=py6HRH5S1HKLCBo8-9dD9bBnsFfseQXneDXIWrxzRt4,6307
4
+ codex_usage/auth.py,sha256=BhZUoijU7Kp2TE8EOz75bd4FpsV3-5WwKGeNDY1KkbY,3962
5
+ codex_usage/cli.py,sha256=aF-9jjlblgWKEHHB7XCwEdDNpTNS23aGooW--eIsRuM,2603
6
+ codex_usage/report.py,sha256=w1PctoHaA29VgXasVfp1593NsODfJ_1YbwmYUh_P3KQ,6203
7
+ codex_usage_limits-0.1.0.dist-info/licenses/LICENSE,sha256=f7pAjK3BkXOlCio2Z_aL1unlPRBBRBWDpDYUolXWb28,1081
8
+ codex_usage_limits-0.1.0.dist-info/METADATA,sha256=f5QyEHwpfkzkakXJ5JeUgKgVYZc3mQ8D75QjUoVfrOo,9586
9
+ codex_usage_limits-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ codex_usage_limits-0.1.0.dist-info/entry_points.txt,sha256=aPudYWR_iZJGA3oYqW0hx4qq6kX2cXhi97gM65MIJDo,53
11
+ codex_usage_limits-0.1.0.dist-info/top_level.txt,sha256=-IffGmguVBs2r0BEINTtRZmLsajCZgaZ-8RILGlLzgQ,12
12
+ codex_usage_limits-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ codex-usage = codex_usage.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 codex-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
+ codex_usage