llmswap-cli 1.0.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_swap/__init__.py +24 -0
- claude_swap/__main__.py +6 -0
- claude_swap/app_bundle.py +330 -0
- claude_swap/appearance.py +219 -0
- claude_swap/autoswitch.py +3065 -0
- claude_swap/cache.py +44 -0
- claude_swap/claude_locks.py +279 -0
- claude_swap/cli.py +2265 -0
- claude_swap/credentials.py +2156 -0
- claude_swap/exceptions.py +102 -0
- claude_swap/fsutil.py +409 -0
- claude_swap/json_output.py +455 -0
- claude_swap/launch_agent.py +862 -0
- claude_swap/lines.py +153 -0
- claude_swap/list_view.py +371 -0
- claude_swap/locking.py +87 -0
- claude_swap/logging_config.py +64 -0
- claude_swap/macos_keychain.py +240 -0
- claude_swap/mappings.py +127 -0
- claude_swap/menubar.py +1433 -0
- claude_swap/migrations.py +360 -0
- claude_swap/models.py +329 -0
- claude_swap/oauth.py +1628 -0
- claude_swap/pace.py +161 -0
- claude_swap/paths.py +250 -0
- claude_swap/poll_policy.py +337 -0
- claude_swap/printer.py +252 -0
- claude_swap/process_detection.py +370 -0
- claude_swap/session.py +2696 -0
- claude_swap/settings.py +827 -0
- claude_swap/signin.py +238 -0
- claude_swap/snapshot_source.py +121 -0
- claude_swap/spawn.py +135 -0
- claude_swap/subscription.py +349 -0
- claude_swap/switcher.py +9807 -0
- claude_swap/transfer.py +807 -0
- claude_swap/tui/__init__.py +43 -0
- claude_swap/tui/app.py +482 -0
- claude_swap/tui/autoview.py +381 -0
- claude_swap/tui/cswap.tcss +205 -0
- claude_swap/tui/dashboard.py +434 -0
- claude_swap/tui/data.py +194 -0
- claude_swap/tui/modals.py +159 -0
- claude_swap/tui/theme.py +88 -0
- claude_swap/tui/widgets.py +544 -0
- claude_swap/update_check.py +509 -0
- claude_swap/usage_bars.py +208 -0
- claude_swap/usage_rows.py +160 -0
- claude_swap/usage_store.py +1429 -0
- llmswap/AGENTS.md +11 -0
- llmswap/__init__.py +3 -0
- llmswap/__main__.py +4 -0
- llmswap/cli.py +535 -0
- llmswap/config.py +101 -0
- llmswap/httpjson.py +50 -0
- llmswap/jwt.py +20 -0
- llmswap/menubar.py +218 -0
- llmswap/model.py +172 -0
- llmswap/paths.py +41 -0
- llmswap/providers/AGENTS.md +12 -0
- llmswap/providers/base.py +619 -0
- llmswap/providers/claude.py +187 -0
- llmswap/providers/codex.py +274 -0
- llmswap/providers/gemini.py +80 -0
- llmswap/providers/registry.py +30 -0
- llmswap/render.py +127 -0
- llmswap/rotate.py +102 -0
- llmswap/store.py +138 -0
- llmswap/tui.py +182 -0
- llmswap/usage_cache.py +72 -0
- llmswap/warm/plan.py +118 -0
- llmswap/warm/runner.py +175 -0
- llmswap/warm/schedule.py +264 -0
- llmswap_cli-1.0.0.dist-info/METADATA +181 -0
- llmswap_cli-1.0.0.dist-info/RECORD +78 -0
- llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
- llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
- llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
claude_swap/oauth.py
ADDED
|
@@ -0,0 +1,1628 @@
|
|
|
1
|
+
"""OAuth token management and usage API for Claude Code accounts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import socket
|
|
11
|
+
import ssl
|
|
12
|
+
import sys
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from datetime import datetime, timedelta, timezone
|
|
18
|
+
|
|
19
|
+
from claude_swap.printer import warning as print_warning
|
|
20
|
+
|
|
21
|
+
OAUTH_BETA_HEADER = "oauth-2025-04-20"
|
|
22
|
+
OAUTH_EXPIRY_BUFFER_MS = 5 * 60 * 1000
|
|
23
|
+
OAUTH_TOKEN_URL = "https://platform.claude.com/v1/oauth/token"
|
|
24
|
+
OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
|
|
25
|
+
|
|
26
|
+
# What ``claude setup-token`` grants (and what ``cswap add-token`` stores).
|
|
27
|
+
# Such a token can run inference but cannot read the usage endpoint.
|
|
28
|
+
SETUP_TOKEN_SCOPES = ("user:inference",)
|
|
29
|
+
|
|
30
|
+
# The header probe: a 1-output-token Haiku request whose response headers
|
|
31
|
+
# carry the account's unified 5h/7d utilization. The undated id names the
|
|
32
|
+
# current Haiku generation rather than a dated snapshot, which retires
|
|
33
|
+
# sooner; once a model is gone the probe fails with http-404 and the account
|
|
34
|
+
# shows its usage as unavailable until the id is updated.
|
|
35
|
+
USAGE_PROBE_URL = "https://api.anthropic.com/v1/messages"
|
|
36
|
+
USAGE_PROBE_MODEL = "claude-haiku-5-5"
|
|
37
|
+
USAGE_PROBE_API_VERSION = "2023-06-01"
|
|
38
|
+
# OAuth inference requests are only accepted with Claude Code's system prompt.
|
|
39
|
+
USAGE_PROBE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude."
|
|
40
|
+
# The unified headers carry a per-model weekly bucket only on responses to
|
|
41
|
+
# that model's own requests: a Haiku probe never sees Fable's ``7d_oi``. So,
|
|
42
|
+
# with ``usage.fableProbe`` on, a second, best-effort 1-token probe per scoped
|
|
43
|
+
# model reads just that bucket (see ``_add_scoped_limits``).
|
|
44
|
+
# Model id -> the unified header prefix of the bucket its responses carry.
|
|
45
|
+
# Sonnet and Opus probes carry no per-model bucket (checked 2026-11), so they
|
|
46
|
+
# are not probed; a new bucket needs its model and prefix here and its display
|
|
47
|
+
# name and claim in ``_UNIFIED_SCOPED_WINDOWS``.
|
|
48
|
+
USAGE_PROBE_SCOPED_MODELS = {"claude-fable-5-1": "7d_oi"}
|
|
49
|
+
|
|
50
|
+
# How long the consume gate lets each step of a refresh request take. A grant
|
|
51
|
+
# is single-use: once the request is out, giving up on a slow reply loses the
|
|
52
|
+
# successor while the server retires the token cswap still holds. 30 s is what
|
|
53
|
+
# Claude Code gives the same request (`30000` around the token POST, read in
|
|
54
|
+
# the 2.1.333 binary).
|
|
55
|
+
GATE_REFRESH_TIMEOUT_S = 30.0
|
|
56
|
+
|
|
57
|
+
_logger = logging.getLogger("claude-swap")
|
|
58
|
+
|
|
59
|
+
# Refresh failures that happen before any byte of the request is written: the
|
|
60
|
+
# name did not resolve, the connection was refused, or the TLS handshake
|
|
61
|
+
# rejected the certificate.
|
|
62
|
+
_NEVER_SENT = (socket.gaierror, ConnectionRefusedError, ssl.SSLCertVerificationError)
|
|
63
|
+
|
|
64
|
+
# The token endpoint's error codes (RFC 6749 section 5.2). A refresh failure
|
|
65
|
+
# is logged with one of these or as unrecognised, never with the reply text.
|
|
66
|
+
_OAUTH_ERROR_CODES = frozenset({
|
|
67
|
+
"invalid_request", "invalid_client", "invalid_grant",
|
|
68
|
+
"unauthorized_client", "unsupported_grant_type", "invalid_scope",
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def extract_access_token(credentials: str) -> str | None:
|
|
73
|
+
"""Extract the OAuth access token from a credentials JSON string."""
|
|
74
|
+
try:
|
|
75
|
+
data = json.loads(credentials)
|
|
76
|
+
return data.get("claudeAiOauth", {}).get("accessToken")
|
|
77
|
+
except (json.JSONDecodeError, AttributeError):
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def extract_oauth_data(credentials: str) -> dict | None:
|
|
82
|
+
"""Extract the Claude AI OAuth payload from a credentials JSON string."""
|
|
83
|
+
try:
|
|
84
|
+
data = json.loads(credentials)
|
|
85
|
+
except json.JSONDecodeError:
|
|
86
|
+
return None
|
|
87
|
+
if not isinstance(data, dict):
|
|
88
|
+
return None
|
|
89
|
+
oauth = data.get("claudeAiOauth")
|
|
90
|
+
return oauth if isinstance(oauth, dict) else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def credential_fingerprint(credentials: str) -> str | None:
|
|
94
|
+
"""Stable identity fingerprint for a stored credential.
|
|
95
|
+
|
|
96
|
+
Refresh-token hash when one exists (survives access-token rotation, so two
|
|
97
|
+
generations of the same OAuth lineage compare equal); full-content hash
|
|
98
|
+
otherwise (API keys and setup-tokens rotate never, so content identity is
|
|
99
|
+
lineage identity). None only for empty input — a caller comparing "did the
|
|
100
|
+
credential change?" must never get None for real bytes, or every
|
|
101
|
+
comparison against it would degenerate to "changed".
|
|
102
|
+
"""
|
|
103
|
+
if not credentials:
|
|
104
|
+
return None
|
|
105
|
+
data = extract_oauth_data(credentials)
|
|
106
|
+
token = data.get("refreshToken") if data else None
|
|
107
|
+
if isinstance(token, str) and token:
|
|
108
|
+
return "sha256:" + hashlib.sha256(token.encode()).hexdigest()
|
|
109
|
+
return "sha256-full:" + hashlib.sha256(credentials.encode()).hexdigest()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def access_token_fingerprint(credentials: str) -> str | None:
|
|
113
|
+
"""Hash of the access token alone: the part that rotates within a
|
|
114
|
+
lineage, so a refused token and its replacement compare unequal."""
|
|
115
|
+
data = extract_oauth_data(credentials)
|
|
116
|
+
token = data.get("accessToken") if data else None
|
|
117
|
+
if not isinstance(token, str) or not token:
|
|
118
|
+
return None
|
|
119
|
+
return "sha256-at:" + hashlib.sha256(token.encode()).hexdigest()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def login_account_ids(credentials: str) -> tuple[str, str] | None:
|
|
123
|
+
"""``(accountUuid, organizationUuid)`` a stored login carries, or ``None``
|
|
124
|
+
when it carries no account uuid.
|
|
125
|
+
|
|
126
|
+
Claude Code (read in 2.1.329 to 2.1.333) writes both into
|
|
127
|
+
``claudeAiOauth`` at sign-in, from the profile of the account that signed
|
|
128
|
+
in, and a refresh copies them from the login it renews. So they say whose
|
|
129
|
+
login this is without asking the network, and they still say it once the
|
|
130
|
+
access token has expired. Seen on a login made under 2.1.333; the copy on
|
|
131
|
+
refresh is read, not seen. A login from before those versions has neither
|
|
132
|
+
until its next sign-in, and a setup token never has them. The
|
|
133
|
+
organisation is ``""`` when only the account is recorded.
|
|
134
|
+
"""
|
|
135
|
+
data = extract_oauth_data(credentials)
|
|
136
|
+
account = data.get("accountUuid") if data else None
|
|
137
|
+
if not isinstance(account, str) or not account.strip():
|
|
138
|
+
return None
|
|
139
|
+
org = data.get("organizationUuid")
|
|
140
|
+
return account.strip(), org.strip() if isinstance(org, str) else ""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _refresh_token_expires_at_ms(credentials: str) -> float | None:
|
|
144
|
+
"""Raw ``refreshTokenExpiresAt`` (epoch milliseconds), or ``None`` when
|
|
145
|
+
absent/unreadable. Shared parse behind :func:`login_expires_at_iso` and
|
|
146
|
+
:func:`login_expires_at_epoch` so there is one reader of the field."""
|
|
147
|
+
data = extract_oauth_data(credentials)
|
|
148
|
+
value = data.get("refreshTokenExpiresAt") if data else None
|
|
149
|
+
if (
|
|
150
|
+
isinstance(value, bool)
|
|
151
|
+
or not isinstance(value, (int, float))
|
|
152
|
+
or not math.isfinite(value)
|
|
153
|
+
or value <= 0
|
|
154
|
+
):
|
|
155
|
+
return None
|
|
156
|
+
return float(value)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def login_expires_at_iso(credentials: str) -> str | None:
|
|
160
|
+
"""When the stored *login* itself lapses, as ISO-8601 UTC, or ``None``.
|
|
161
|
+
|
|
162
|
+
Claude Code stores ``refreshTokenExpiresAt`` (epoch milliseconds) next to the
|
|
163
|
+
access token's ``expiresAt``. The two age differently: the access token is
|
|
164
|
+
renewed from the refresh token on its own, while the refresh token is only
|
|
165
|
+
ever replaced by a fresh ``/login``. Once it lapses the slot reports
|
|
166
|
+
``relogin_required`` and nothing short of logging in again fixes it, so this
|
|
167
|
+
is the date worth showing *before* that happens. Logins issued before Claude
|
|
168
|
+
Code recorded the field carry nothing, which means "unknown", never "now".
|
|
169
|
+
"""
|
|
170
|
+
value = _refresh_token_expires_at_ms(credentials)
|
|
171
|
+
if value is None:
|
|
172
|
+
return None
|
|
173
|
+
return (
|
|
174
|
+
datetime.fromtimestamp(value / 1000, tz=timezone.utc)
|
|
175
|
+
.isoformat(timespec="seconds")
|
|
176
|
+
.replace("+00:00", "Z")
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def login_expires_at_epoch(credentials: str) -> float | None:
|
|
181
|
+
"""Epoch-seconds twin of :func:`login_expires_at_iso`: what
|
|
182
|
+
``AccountSnapshot.login_expires_at`` and :func:`format_login_expiry` want,
|
|
183
|
+
without an ISO round-trip."""
|
|
184
|
+
value = _refresh_token_expires_at_ms(credentials)
|
|
185
|
+
return value / 1000 if value is not None else None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# How far ahead a stored login's expiry is worth showing. Claude Code's own
|
|
189
|
+
# notice fires inside the last three days; a week leaves time to plan the
|
|
190
|
+
# re-logins of several accounts without every view nagging for a month.
|
|
191
|
+
LOGIN_DUE_WITHIN_S = 7 * 86400
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def login_time_left(
|
|
195
|
+
expires_at: float | None, quarantined: bool, now: float | None = None
|
|
196
|
+
) -> float | None:
|
|
197
|
+
"""Seconds until a stored login must be redone, when that is worth saying.
|
|
198
|
+
|
|
199
|
+
``None`` means "nothing to say": the stamp is unknown (logins older than
|
|
200
|
+
the field, API-key slots), the expiry is further out than
|
|
201
|
+
``LOGIN_DUE_WITHIN_S``, or the slot is quarantined, whose usage sentinel
|
|
202
|
+
already reads "re-login needed". Otherwise the seconds left, ``0.0`` once
|
|
203
|
+
the stamp is past.
|
|
204
|
+
"""
|
|
205
|
+
if quarantined or expires_at is None:
|
|
206
|
+
return None
|
|
207
|
+
now = now if now is not None else datetime.now(timezone.utc).timestamp()
|
|
208
|
+
remaining = expires_at - now
|
|
209
|
+
if remaining > LOGIN_DUE_WITHIN_S:
|
|
210
|
+
return None
|
|
211
|
+
return max(0.0, remaining)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def format_login_expiry(
|
|
215
|
+
expires_at: float | None,
|
|
216
|
+
quarantined: bool,
|
|
217
|
+
now: float | None = None,
|
|
218
|
+
short: bool = False,
|
|
219
|
+
) -> str | None:
|
|
220
|
+
"""``"re-login in 5d 12h"`` while a stored login is due (see
|
|
221
|
+
:func:`login_time_left`), ``"re-login needed"`` once its stamp is past,
|
|
222
|
+
``None`` when there is nothing to say. The countdown is the reset
|
|
223
|
+
counters' (:func:`format_countdown`); ``short`` keeps its first unit
|
|
224
|
+
(``"re-login in 5d"``) for rows with little room.
|
|
225
|
+
"""
|
|
226
|
+
left = login_time_left(expires_at, quarantined, now)
|
|
227
|
+
if left is None:
|
|
228
|
+
return None
|
|
229
|
+
if left <= 0:
|
|
230
|
+
return "re-login needed"
|
|
231
|
+
countdown = format_countdown(left)
|
|
232
|
+
return f"re-login in {countdown.split(' ')[0] if short else countdown}"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def login_expiry_clock(expires_at: float, now: float | None = None) -> str:
|
|
236
|
+
"""The stamp as the local clock string the reset columns use."""
|
|
237
|
+
now_utc = (
|
|
238
|
+
datetime.fromtimestamp(now, tz=timezone.utc) if now is not None
|
|
239
|
+
else datetime.now(timezone.utc)
|
|
240
|
+
)
|
|
241
|
+
return reset_clock_string(datetime.fromtimestamp(expires_at, tz=timezone.utc), now_utc)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def is_oauth_token_expired(expires_at: object) -> bool:
|
|
245
|
+
"""Return whether an OAuth token is expired or about to expire."""
|
|
246
|
+
if not isinstance(expires_at, (int, float)):
|
|
247
|
+
return False
|
|
248
|
+
|
|
249
|
+
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
|
|
250
|
+
return now_ms + OAUTH_EXPIRY_BUFFER_MS >= int(expires_at)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
@dataclass(frozen=True)
|
|
254
|
+
class RefreshOutcome:
|
|
255
|
+
"""Result of a refresh-token grant attempt.
|
|
256
|
+
|
|
257
|
+
``credentials`` is the full rotated credentials JSON on success, else None.
|
|
258
|
+
``error`` classifies failures so callers can distinguish a dead refresh-token
|
|
259
|
+
lineage (permanent: quarantine, stop retrying) from a network blip
|
|
260
|
+
(transient: retry later):
|
|
261
|
+
|
|
262
|
+
- ``None`` — success (``credentials`` is set)
|
|
263
|
+
- ``"invalid_grant"`` — the token endpoint rejected the grant; this refresh
|
|
264
|
+
token is dead and re-login is required
|
|
265
|
+
- ``"no_refresh_token"`` — the stored credential carries no usable refresh
|
|
266
|
+
token (also permanent for retry purposes)
|
|
267
|
+
- ``"transient"`` — network/server error; the token may still be valid
|
|
268
|
+
|
|
269
|
+
``token_account`` is the account identity the token endpoint optionally
|
|
270
|
+
includes alongside a successful grant (``{"uuid", "email",
|
|
271
|
+
"organizationUuid"}``, fields possibly None) — a zero-request identity
|
|
272
|
+
source for the credential that was just refreshed. None when the server
|
|
273
|
+
omitted it or on failure; callers must treat it as opportunistic.
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
credentials: str | None
|
|
277
|
+
error: str | None
|
|
278
|
+
token_account: dict | None = None
|
|
279
|
+
# Fingerprint of the generation actually consumed (POSTed). Set by the
|
|
280
|
+
# consume gate, which may substitute a fresher re-read or a session
|
|
281
|
+
# profile for the caller's snapshot — strike binding must follow the
|
|
282
|
+
# POSTed bytes, not the snapshot.
|
|
283
|
+
consumed_fp: str | None = None
|
|
284
|
+
# Did the consumed successor actually reach the stash? Only meaningful on
|
|
285
|
+
# a demoted (`transient` WITH credentials) outcome from the consume gate.
|
|
286
|
+
# False there means the `consume-gate-unpersisted` corner: BOTH the
|
|
287
|
+
# persist and the stash write failed, so the successor survives only in
|
|
288
|
+
# `credentials` and retrying POSTs the spent predecessor. Callers that
|
|
289
|
+
# tell the user what to do next must not promise a stash that never
|
|
290
|
+
# happened.
|
|
291
|
+
stashed: bool = False
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def try_refresh_oauth_credentials(
|
|
295
|
+
credentials: str, timeout_s: float = 10.0
|
|
296
|
+
) -> RefreshOutcome:
|
|
297
|
+
"""Refresh an OAuth access token via direct token endpoint POST.
|
|
298
|
+
|
|
299
|
+
``timeout_s`` bounds the network exchange. Callers that hold locks other
|
|
300
|
+
processes contend for should pass a budget comfortably inside the
|
|
301
|
+
contenders' acquire timeout (see ``_fetch_active_usage``).
|
|
302
|
+
"""
|
|
303
|
+
# ``no_refresh_token`` is a PERMANENT verdict (it strikes at
|
|
304
|
+
# AUTH_DEAD_STRIKES=1), so it demands a structurally complete OAuth dict
|
|
305
|
+
# genuinely missing the field. An unparseable or non-dict blob is more
|
|
306
|
+
# likely a torn/partial read than a real credential shape — transient:
|
|
307
|
+
# the next pass re-reads and either succeeds or sees the true shape.
|
|
308
|
+
try:
|
|
309
|
+
data = json.loads(credentials)
|
|
310
|
+
except json.JSONDecodeError:
|
|
311
|
+
return RefreshOutcome(None, "transient")
|
|
312
|
+
if not isinstance(data, dict):
|
|
313
|
+
return RefreshOutcome(None, "transient")
|
|
314
|
+
oauth = data.get("claudeAiOauth")
|
|
315
|
+
if not isinstance(oauth, dict) or not oauth.get("refreshToken"):
|
|
316
|
+
return RefreshOutcome(None, "no_refresh_token")
|
|
317
|
+
|
|
318
|
+
try:
|
|
319
|
+
body = json.dumps({
|
|
320
|
+
"grant_type": "refresh_token",
|
|
321
|
+
"refresh_token": oauth["refreshToken"],
|
|
322
|
+
"client_id": OAUTH_CLIENT_ID,
|
|
323
|
+
}).encode()
|
|
324
|
+
|
|
325
|
+
req = urllib.request.Request(
|
|
326
|
+
OAUTH_TOKEN_URL,
|
|
327
|
+
data=body,
|
|
328
|
+
headers={
|
|
329
|
+
"Content-Type": "application/json",
|
|
330
|
+
"User-Agent": "claude-swap/1.0",
|
|
331
|
+
},
|
|
332
|
+
method="POST",
|
|
333
|
+
)
|
|
334
|
+
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
|
|
335
|
+
resp_data = json.loads(resp.read().decode())
|
|
336
|
+
|
|
337
|
+
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
|
|
338
|
+
oauth["accessToken"] = resp_data["access_token"]
|
|
339
|
+
oauth["expiresAt"] = now_ms + resp_data["expires_in"] * 1000
|
|
340
|
+
if resp_data.get("refresh_token"):
|
|
341
|
+
oauth["refreshToken"] = resp_data["refresh_token"]
|
|
342
|
+
if resp_data.get("scope"):
|
|
343
|
+
oauth["scopes"] = resp_data["scope"].split()
|
|
344
|
+
|
|
345
|
+
data["claudeAiOauth"] = oauth
|
|
346
|
+
return RefreshOutcome(
|
|
347
|
+
json.dumps(data), None, _parse_token_account(resp_data)
|
|
348
|
+
)
|
|
349
|
+
except urllib.error.HTTPError as e:
|
|
350
|
+
# Reading the error body can fail too, when a gateway drops the
|
|
351
|
+
# connection part-way. That is a reply without a verdict.
|
|
352
|
+
unread = ""
|
|
353
|
+
try:
|
|
354
|
+
body = e.read().decode(errors="replace") if hasattr(e, "read") else ""
|
|
355
|
+
except Exception as read_error:
|
|
356
|
+
body = ""
|
|
357
|
+
unread = f", body unread ({type(read_error).__name__})"
|
|
358
|
+
err = None
|
|
359
|
+
# Permanent only when the server itself rejected the grant: a 4xx AND
|
|
360
|
+
# an explicit marker in the body. Anything ambiguous stays transient —
|
|
361
|
+
# a misclassified transient costs one retry, a misclassified permanent
|
|
362
|
+
# would wrongly quarantine a live token.
|
|
363
|
+
if e.code in (400, 401, 403):
|
|
364
|
+
# RFC 6749 §5.2: the verdict is the top-level ``error`` member of
|
|
365
|
+
# the JSON body. A substring scan misclassifies — the marker can
|
|
366
|
+
# appear inside another envelope's detail text, and a dead-token
|
|
367
|
+
# verdict at AUTH_DEAD_STRIKES=1 quarantines the slot on the
|
|
368
|
+
# spot. Unparseable bodies stay transient (a misclassified
|
|
369
|
+
# transient costs one retry; a misclassified permanent wrongly
|
|
370
|
+
# quarantines a live token).
|
|
371
|
+
try:
|
|
372
|
+
err = json.loads(body).get("error")
|
|
373
|
+
except (ValueError, AttributeError):
|
|
374
|
+
err = None
|
|
375
|
+
# The status and a known OAuth error code only: the body is whatever
|
|
376
|
+
# a server or a proxy chose to send.
|
|
377
|
+
known = isinstance(err, str) and err in _OAUTH_ERROR_CODES
|
|
378
|
+
_logger.debug(
|
|
379
|
+
"OAuth refresh failed: HTTP %s, error %s%s",
|
|
380
|
+
e.code, err if known else "unrecognised", unread,
|
|
381
|
+
)
|
|
382
|
+
# invalid_grant: this slot's refresh lineage is dead.
|
|
383
|
+
# invalid_client: OUR client credential was rejected — systemic
|
|
384
|
+
# (client_id rotated/blocked), no evidence about any slot, so it
|
|
385
|
+
# keeps its own kind and lands no strike.
|
|
386
|
+
if err in ("invalid_grant", "invalid_client"):
|
|
387
|
+
return RefreshOutcome(None, err)
|
|
388
|
+
if e.code >= 500:
|
|
389
|
+
# Not a verdict on the grant either: a gateway can report an error
|
|
390
|
+
# for a request the origin already acted on.
|
|
391
|
+
_warn_grant_fate_unknown(credentials, f"HTTP {e.code}")
|
|
392
|
+
return RefreshOutcome(None, "transient")
|
|
393
|
+
except urllib.error.URLError as e:
|
|
394
|
+
# urllib wraps every failure before the reply is read in URLError:
|
|
395
|
+
# name lookup, connect, TLS and writing the request. A failure while
|
|
396
|
+
# reading the reply arrives unwrapped, below.
|
|
397
|
+
reason = e.reason
|
|
398
|
+
what = "URLError" if isinstance(reason, str) else type(reason).__name__
|
|
399
|
+
if isinstance(reason, (str, *_NEVER_SENT)):
|
|
400
|
+
# Nothing reached the server, so no grant can have been spent.
|
|
401
|
+
# The ordinary offline case; it stays quiet.
|
|
402
|
+
_logger.debug("OAuth refresh not sent: %s", what)
|
|
403
|
+
else:
|
|
404
|
+
# A timeout or a reset here can be the connect or the write, and
|
|
405
|
+
# the exception does not say which. INFO, because the default log
|
|
406
|
+
# keeps it and it is not a reason for alarm.
|
|
407
|
+
_logger.info(
|
|
408
|
+
"OAuth refresh for %s failed while connecting or sending "
|
|
409
|
+
"(%s); whether the request reached the server is unknown.",
|
|
410
|
+
credential_fingerprint(credentials)[:19],
|
|
411
|
+
what,
|
|
412
|
+
)
|
|
413
|
+
return RefreshOutcome(None, "transient")
|
|
414
|
+
except Exception as e:
|
|
415
|
+
# The request went out and no usable reply came back: a timeout or
|
|
416
|
+
# reset while waiting, or a reply that could not be read. The type
|
|
417
|
+
# name only: a decode error's repr holds the reply bytes.
|
|
418
|
+
_logger.debug("OAuth refresh failed: %s", type(e).__name__)
|
|
419
|
+
_warn_grant_fate_unknown(credentials, type(e).__name__)
|
|
420
|
+
return RefreshOutcome(None, "transient")
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _warn_grant_fate_unknown(credentials: str, what: str) -> None:
|
|
424
|
+
"""Log a refresh that went out and came back without a verdict on the grant.
|
|
425
|
+
|
|
426
|
+
The outcome stays ``transient``: a retry is the only move either way. But
|
|
427
|
+
a timeout, a reset or a server error is not proof that nothing was spent,
|
|
428
|
+
and if the server did rotate the grant, the next refresh of these same
|
|
429
|
+
bytes gets invalid_grant. WARNING is a level the default log keeps, so
|
|
430
|
+
that later strike can be traced back to this exchange.
|
|
431
|
+
|
|
432
|
+
This module is not told which account it serves, so the line carries the
|
|
433
|
+
head of the credential fingerprint ("sha256:" and 12 hex digits): the
|
|
434
|
+
value the usage store writes as ``struckFingerprint``. ``what`` is a
|
|
435
|
+
status or an exception type name, never a repr: a decode error's repr is
|
|
436
|
+
the reply body, and a reply body can hold tokens.
|
|
437
|
+
"""
|
|
438
|
+
_logger.warning(
|
|
439
|
+
"OAuth refresh for %s got no usable reply (%s). The refresh token "
|
|
440
|
+
"on disk may now be spent; if the next refresh fails with "
|
|
441
|
+
"invalid_grant, re-run `cswap --add-account` after logging in.",
|
|
442
|
+
credential_fingerprint(credentials)[:19],
|
|
443
|
+
what,
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _parse_token_account(resp_data: dict) -> dict | None:
|
|
448
|
+
"""Extract the optional account identity from a token-endpoint response.
|
|
449
|
+
|
|
450
|
+
The refresh grant's response body may carry ``account`` / ``organization``
|
|
451
|
+
objects naming who the rotated token belongs to (Claude Code surfaces the
|
|
452
|
+
same fields as ``tokenAccount``). Absent in some responses — never rely on
|
|
453
|
+
it, but never discard it either. Same strict boundary as
|
|
454
|
+
``fetch_oauth_profile``: usable identity requires a non-empty string
|
|
455
|
+
``account.uuid`` (consumers backfill and compare by uuid), optional
|
|
456
|
+
fields are normalized to str-or-None, and anything malformed is None —
|
|
457
|
+
this identity is opportunistic and must never break the refresh that
|
|
458
|
+
carried it.
|
|
459
|
+
"""
|
|
460
|
+
account = resp_data.get("account")
|
|
461
|
+
if not isinstance(account, dict):
|
|
462
|
+
return None
|
|
463
|
+
uuid = account.get("uuid")
|
|
464
|
+
if not isinstance(uuid, str) or not uuid.strip():
|
|
465
|
+
return None
|
|
466
|
+
email = account.get("email_address")
|
|
467
|
+
organization = resp_data.get("organization")
|
|
468
|
+
org_uuid = organization.get("uuid") if isinstance(organization, dict) else None
|
|
469
|
+
return {
|
|
470
|
+
"uuid": uuid.strip(),
|
|
471
|
+
"email": email if isinstance(email, str) else None,
|
|
472
|
+
"organizationUuid": org_uuid if isinstance(org_uuid, str) else None,
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def refresh_oauth_credentials(credentials: str) -> str | None:
|
|
477
|
+
"""Refresh an OAuth access token; None on any failure (see RefreshOutcome)."""
|
|
478
|
+
return try_refresh_oauth_credentials(credentials).credentials
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def fetch_oauth_profile(access_token: str) -> dict | None:
|
|
482
|
+
"""Resolve an OAuth access token to its account identity, or None.
|
|
483
|
+
|
|
484
|
+
``GET /api/oauth/profile`` answers the one question the credential bytes
|
|
485
|
+
can't: *whose* token is this. Returns ``{"uuid", "email",
|
|
486
|
+
"organizationUuid"}`` or None on any failure — callers treat None as
|
|
487
|
+
"unresolvable", never as an error. The identity oracle is strictly
|
|
488
|
+
advisory (a switch proceeds pre-fix on None), so the boundary is strict
|
|
489
|
+
the other way: a response counts as resolved only when it carries a
|
|
490
|
+
non-empty string ``account.uuid`` — a response without a usable uuid,
|
|
491
|
+
including a schema change that renames it, is None, keeping that drift
|
|
492
|
+
on the fail-open path rather than silently degrading switches.
|
|
493
|
+
``email``/``organizationUuid`` are optional (str-or-None); a uuid-only
|
|
494
|
+
response *does* resolve, and classification decides whether such partial
|
|
495
|
+
evidence is sufficient for each decision. Must not be called while any
|
|
496
|
+
credential/config lock is held (network under locks is forbidden).
|
|
497
|
+
"""
|
|
498
|
+
url = "https://api.anthropic.com/api/oauth/profile"
|
|
499
|
+
headers = {
|
|
500
|
+
"Authorization": f"Bearer {access_token}",
|
|
501
|
+
"Content-Type": "application/json",
|
|
502
|
+
"User-Agent": "claude-swap/1.0",
|
|
503
|
+
}
|
|
504
|
+
req = urllib.request.Request(url, headers=headers)
|
|
505
|
+
try:
|
|
506
|
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
507
|
+
data = json.loads(resp.read().decode())
|
|
508
|
+
except urllib.error.HTTPError as e:
|
|
509
|
+
if e.code == 401:
|
|
510
|
+
# Evidence, not proof: the live access token can't authenticate.
|
|
511
|
+
# A freshly rotated own-credential would carry a fresh token, but
|
|
512
|
+
# this also fires benignly (family rotated, then the access token
|
|
513
|
+
# expired on an idle machine). Log-file only — the caller falls
|
|
514
|
+
# back to pre-fix behavior and the user sees nothing.
|
|
515
|
+
_logger.warning(
|
|
516
|
+
"OAuth profile returned 401 while resolving credential "
|
|
517
|
+
"ownership; proceeding without identity (pre-fix behavior)."
|
|
518
|
+
)
|
|
519
|
+
else:
|
|
520
|
+
_logger.debug("OAuth profile fetch failed: %r", e)
|
|
521
|
+
return None
|
|
522
|
+
except Exception as e:
|
|
523
|
+
_logger.debug("OAuth profile fetch failed: %r", e)
|
|
524
|
+
return None
|
|
525
|
+
account = data.get("account") if isinstance(data, dict) else None
|
|
526
|
+
if not isinstance(account, dict):
|
|
527
|
+
_logger.debug("OAuth profile response missing account object")
|
|
528
|
+
return None
|
|
529
|
+
uuid = account.get("uuid")
|
|
530
|
+
if not isinstance(uuid, str) or not uuid.strip():
|
|
531
|
+
_logger.debug("OAuth profile response missing account.uuid")
|
|
532
|
+
return None
|
|
533
|
+
email = account.get("email")
|
|
534
|
+
organization = data.get("organization")
|
|
535
|
+
org_uuid = organization.get("uuid") if isinstance(organization, dict) else None
|
|
536
|
+
return {
|
|
537
|
+
"uuid": uuid.strip(),
|
|
538
|
+
"email": email if isinstance(email, str) else None,
|
|
539
|
+
"organizationUuid": org_uuid if isinstance(org_uuid, str) else None,
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def build_token_status(credentials: str) -> str | None:
|
|
545
|
+
"""Return a short debug summary of stored OAuth token state."""
|
|
546
|
+
oauth = extract_oauth_data(credentials)
|
|
547
|
+
if not oauth:
|
|
548
|
+
return None
|
|
549
|
+
|
|
550
|
+
has_refresh_token = bool(oauth.get("refreshToken"))
|
|
551
|
+
expires_at = oauth.get("expiresAt")
|
|
552
|
+
refresh_str = "yes" if has_refresh_token else "no"
|
|
553
|
+
|
|
554
|
+
if not isinstance(expires_at, (int, float)):
|
|
555
|
+
return f"oauth: unknown expiry, refresh token {refresh_str}"
|
|
556
|
+
|
|
557
|
+
expires_utc = datetime.fromtimestamp(expires_at / 1000, tz=timezone.utc)
|
|
558
|
+
state = "expired" if is_oauth_token_expired(expires_at) else "fresh"
|
|
559
|
+
countdown, clock = format_reset(expires_utc.isoformat())
|
|
560
|
+
return f"oauth: {state}, refresh token {refresh_str}, expires {clock} in {countdown}"
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def format_reset(resets_at: str) -> tuple[str, str]:
|
|
564
|
+
"""Return (countdown, clock) for a reset time in local time."""
|
|
565
|
+
reset_utc = datetime.fromisoformat(resets_at)
|
|
566
|
+
now = datetime.now(timezone.utc)
|
|
567
|
+
return format_countdown((reset_utc - now).total_seconds()), reset_clock_string(reset_utc, now)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def format_countdown(seconds: float) -> str:
|
|
571
|
+
"""``"5d 12h"`` / ``"1h 59m"`` / ``"45m"``: the grammar of every countdown shown."""
|
|
572
|
+
total = max(0, int(seconds))
|
|
573
|
+
days, remainder = divmod(total, 86400)
|
|
574
|
+
hours, remainder = divmod(remainder, 3600)
|
|
575
|
+
minutes = remainder // 60
|
|
576
|
+
if days > 0:
|
|
577
|
+
return f"{days}d {hours}h"
|
|
578
|
+
if hours > 0:
|
|
579
|
+
return f"{hours}h {minutes}m"
|
|
580
|
+
return f"{minutes}m"
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def reset_clock_string(reset_utc: datetime, now_utc: datetime) -> str:
|
|
584
|
+
"""Absolute reset time in local time: "20:39" same-day, else "Jul 5 08:59"."""
|
|
585
|
+
reset_local = reset_utc.astimezone()
|
|
586
|
+
now_local = now_utc.astimezone()
|
|
587
|
+
if reset_local.date() == now_local.date():
|
|
588
|
+
return reset_local.strftime("%H:%M")
|
|
589
|
+
day = str(reset_local.day)
|
|
590
|
+
return reset_local.strftime(f"%b {day} %H:%M")
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def fresh_reset_strings(window: dict) -> tuple[str, str] | None:
|
|
594
|
+
"""``(countdown, clock)`` for one usage window, or None when unknown.
|
|
595
|
+
|
|
596
|
+
Recomputed from ``resets_at`` at render time: the strings cached at fetch
|
|
597
|
+
time drift as the measurement ages (a countdown frozen 2h ago overstates
|
|
598
|
+
the remaining wait by those 2h, and a same-day "15:30" clock silently
|
|
599
|
+
starts meaning yesterday). Entries persisted without ``resets_at`` fall
|
|
600
|
+
back to the fetch-time strings — stale beats blank.
|
|
601
|
+
"""
|
|
602
|
+
resets_at = window.get("resets_at")
|
|
603
|
+
if resets_at:
|
|
604
|
+
try:
|
|
605
|
+
return format_reset(resets_at)
|
|
606
|
+
except (ValueError, TypeError):
|
|
607
|
+
pass # unparseable cached value — fall back below
|
|
608
|
+
if "clock" in window:
|
|
609
|
+
return window.get("countdown", "?"), window["clock"]
|
|
610
|
+
return None
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def window_reset_passed(window: dict | None, now: float | None = None) -> bool:
|
|
614
|
+
"""Whether a usage window's recorded reset has come.
|
|
615
|
+
|
|
616
|
+
From then on the stored percentage describes a window that has ended, so
|
|
617
|
+
the human views print no figure for it. Claude Code 2.1.332 applies the
|
|
618
|
+
same test to the windows it holds: one is kept only while ``resets_at``
|
|
619
|
+
lies ahead. A window whose ``resets_at`` is missing or unreadable has not
|
|
620
|
+
passed one; ``format_reset`` reads exactly the values this accepts, so a
|
|
621
|
+
passed window always has a clock to print.
|
|
622
|
+
"""
|
|
623
|
+
if not isinstance(window, dict) or not window.get("resets_at"):
|
|
624
|
+
return False
|
|
625
|
+
now_utc = (
|
|
626
|
+
datetime.now(timezone.utc)
|
|
627
|
+
if now is None
|
|
628
|
+
else datetime.fromtimestamp(now, tz=timezone.utc)
|
|
629
|
+
)
|
|
630
|
+
try:
|
|
631
|
+
return datetime.fromisoformat(window["resets_at"]) <= now_utc
|
|
632
|
+
except (ValueError, TypeError):
|
|
633
|
+
return False
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def request_usage_data(
|
|
637
|
+
access_token: str, *, request_log: bool = False, slot: str | None = None
|
|
638
|
+
) -> dict:
|
|
639
|
+
"""Request raw utilization data from the Anthropic usage API.
|
|
640
|
+
|
|
641
|
+
``request_log`` logs one INFO line for the request (see
|
|
642
|
+
:func:`_log_usage_request`); ``slot`` is the account number it names."""
|
|
643
|
+
url = "https://api.anthropic.com/api/oauth/usage"
|
|
644
|
+
headers = {
|
|
645
|
+
"Authorization": f"Bearer {access_token}",
|
|
646
|
+
"anthropic-beta": OAUTH_BETA_HEADER,
|
|
647
|
+
"User-Agent": "claude-swap/1.0",
|
|
648
|
+
}
|
|
649
|
+
req = urllib.request.Request(url, headers=headers)
|
|
650
|
+
outcome, resp_headers = "?", None
|
|
651
|
+
try:
|
|
652
|
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
653
|
+
resp_headers = resp.headers
|
|
654
|
+
data = json.loads(resp.read().decode())
|
|
655
|
+
outcome = "http-200"
|
|
656
|
+
return data
|
|
657
|
+
except Exception as e:
|
|
658
|
+
resp_headers = getattr(e, "headers", resp_headers)
|
|
659
|
+
outcome = f"http-{e.code}" if isinstance(e, urllib.error.HTTPError) else type(e).__name__
|
|
660
|
+
raise
|
|
661
|
+
finally:
|
|
662
|
+
if request_log:
|
|
663
|
+
try:
|
|
664
|
+
_log_usage_request(access_token, outcome, resp_headers, slot)
|
|
665
|
+
except Exception: # a log line must never replace the result or the HTTPError
|
|
666
|
+
pass
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _log_safe(value) -> str:
|
|
670
|
+
"""A server-controlled header value made safe for one log line: ASCII only
|
|
671
|
+
(a folded header can carry CR/LF and would forge a line), what an id or a
|
|
672
|
+
number needs, capped."""
|
|
673
|
+
keep = (c for c in str(value or "") if c.isascii() and (c.isalnum() or c in " ._:-"))
|
|
674
|
+
return "".join(keep)[:64].strip()
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _log_usage_request(
|
|
678
|
+
access_token: str, outcome: str, headers, slot: str | None
|
|
679
|
+
) -> None:
|
|
680
|
+
"""One INFO line per usage request, success or not, so a block can be
|
|
681
|
+
traced to the token, slot and process that spent the budget. The token
|
|
682
|
+
appears only as a 12-hex sha256 prefix of the access token; no email, so
|
|
683
|
+
the line is paste-safe. No body is read: a 429 adds its Retry-After only."""
|
|
684
|
+
headers = headers or {}
|
|
685
|
+
tag = hashlib.sha256(access_token.encode()).hexdigest()[:12]
|
|
686
|
+
argv0 = os.path.basename(sys.argv[0]) if sys.argv else ""
|
|
687
|
+
at = f" slot {slot}" if slot is not None else ""
|
|
688
|
+
parts = [f"Usage request: {outcome} token {tag}{at} pid {os.getpid()} ({argv0 or '?'})"]
|
|
689
|
+
for name in ("request-id", "x-request-id", "cf-ray"):
|
|
690
|
+
if value := _log_safe(headers.get(name)):
|
|
691
|
+
parts.append(f"{name} {value}")
|
|
692
|
+
if outcome == "http-429":
|
|
693
|
+
if value := _log_safe(headers.get("Retry-After")):
|
|
694
|
+
parts.append(f"retry-after {value}")
|
|
695
|
+
_logger.info(" ".join(parts))
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def is_setup_token(oauth: dict | None) -> bool:
|
|
699
|
+
"""Whether an OAuth payload is an inference-only setup-token.
|
|
700
|
+
|
|
701
|
+
``claude setup-token`` issues a long-lived access token with no refresh
|
|
702
|
+
token and only the ``user:inference`` scope. The usage endpoint needs
|
|
703
|
+
``user:profile``, so it never answers such a token: its usage is read
|
|
704
|
+
from response headers instead (see :func:`request_usage_via_probe`), or
|
|
705
|
+
not at all.
|
|
706
|
+
"""
|
|
707
|
+
if not isinstance(oauth, dict) or oauth.get("refreshToken"):
|
|
708
|
+
return False
|
|
709
|
+
scopes = oauth.get("scopes")
|
|
710
|
+
return isinstance(scopes, list) and set(scopes) == set(SETUP_TOKEN_SCOPES)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
# Marks a usage dict read from rate-limit headers (``usage["source"]``). The
|
|
714
|
+
# headers can omit a window the endpoint reports, so such a reading gates
|
|
715
|
+
# decisions only when it is complete (see :func:`relevant_windows`).
|
|
716
|
+
USAGE_SOURCE_HEADERS = "headers"
|
|
717
|
+
|
|
718
|
+
# Unified rate-limit header prefix → usage API window key.
|
|
719
|
+
_UNIFIED_WINDOWS = (("5h", "five_hour"), ("7d", "seven_day"))
|
|
720
|
+
# Per-model weekly buckets in the unified headers, by header prefix: the model
|
|
721
|
+
# display name the usage API's ``weekly_scoped`` limits use, so
|
|
722
|
+
# ``autoswitch.model`` matches them the same way, and the representative claim
|
|
723
|
+
# the headers give when that bucket is the limit their status is about.
|
|
724
|
+
# ``7d_oi`` is Fable's weekly window; Claude Code 2.1.322 labels its claim the
|
|
725
|
+
# "Fable limit".
|
|
726
|
+
_UNIFIED_SCOPED_WINDOWS = {"7d_oi": ("Fable", "seven_day_overage_included")}
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _unified_window(headers, prefix: str) -> tuple[float, str | None] | None:
|
|
730
|
+
"""``(utilization %, resets_at ISO)`` of one unified header window, or None
|
|
731
|
+
when its utilization is missing or unusable (a missing reset only drops
|
|
732
|
+
``resets_at``)."""
|
|
733
|
+
base = f"anthropic-ratelimit-unified-{prefix}"
|
|
734
|
+
try:
|
|
735
|
+
fraction = float(headers.get(f"{base}-utilization"))
|
|
736
|
+
except (TypeError, ValueError):
|
|
737
|
+
return None
|
|
738
|
+
if not math.isfinite(fraction) or fraction < 0:
|
|
739
|
+
return None
|
|
740
|
+
return round(fraction * 100, 2), _epoch_header_iso(headers.get(f"{base}-reset"))
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _unified_window_present(headers, prefix: str) -> bool:
|
|
744
|
+
"""Whether any ``anthropic-ratelimit-unified-<prefix>-*`` header is sent."""
|
|
745
|
+
start = f"anthropic-ratelimit-unified-{prefix}-"
|
|
746
|
+
return any(k.lower().startswith(start) for k in headers.keys())
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def _epoch_header_iso(raw) -> str | None:
|
|
750
|
+
"""An epoch-seconds header value as ISO 8601, or None when unusable."""
|
|
751
|
+
try:
|
|
752
|
+
ts = float(raw)
|
|
753
|
+
if math.isfinite(ts) and ts > 0:
|
|
754
|
+
return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
|
|
755
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
756
|
+
pass
|
|
757
|
+
return None
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def parse_unified_ratelimit_headers(headers) -> dict:
|
|
761
|
+
"""Map ``anthropic-ratelimit-unified-*`` response headers to the raw usage
|
|
762
|
+
API shape, so :func:`build_usage_result` normalizes them unchanged.
|
|
763
|
+
|
|
764
|
+
``-utilization`` is a 0-1 fraction (the API's ``utilization`` is a
|
|
765
|
+
percentage) and ``-reset`` is epoch seconds (the API's ``resets_at`` is
|
|
766
|
+
ISO 8601). A 5h or 7d window with no header at all is left out; one whose
|
|
767
|
+
headers are present without a usable utilization is kept so
|
|
768
|
+
:func:`build_usage_result` rejects it.
|
|
769
|
+
Fable's ``7d_oi`` bucket becomes a ``weekly_scoped`` limit named "Fable";
|
|
770
|
+
the headers carry no other per-model window and no ``extra_usage``.
|
|
771
|
+
A ``rejected`` unified status adds a ``rejected`` entry (see
|
|
772
|
+
:func:`request_usage_via_probe`).
|
|
773
|
+
"""
|
|
774
|
+
data: dict = {}
|
|
775
|
+
for prefix, key in _UNIFIED_WINDOWS:
|
|
776
|
+
window = _unified_window(headers, prefix)
|
|
777
|
+
if window is None:
|
|
778
|
+
if _unified_window_present(headers, prefix):
|
|
779
|
+
data[key] = {"utilization": math.nan} # unusable: fail the reading
|
|
780
|
+
continue
|
|
781
|
+
pct, resets_at = window
|
|
782
|
+
data[key] = {"utilization": pct}
|
|
783
|
+
if resets_at:
|
|
784
|
+
data[key]["resets_at"] = resets_at
|
|
785
|
+
limits = [
|
|
786
|
+
_scoped_limit(name, *window)
|
|
787
|
+
for prefix, (name, _claim) in _UNIFIED_SCOPED_WINDOWS.items()
|
|
788
|
+
if (window := _unified_window(headers, prefix)) is not None
|
|
789
|
+
]
|
|
790
|
+
if limits:
|
|
791
|
+
data["limits"] = limits
|
|
792
|
+
if headers.get("anthropic-ratelimit-unified-status") == "rejected":
|
|
793
|
+
data["rejected"] = {
|
|
794
|
+
"resets_at": _epoch_header_iso(
|
|
795
|
+
headers.get("anthropic-ratelimit-unified-reset")
|
|
796
|
+
),
|
|
797
|
+
}
|
|
798
|
+
return data
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _scoped_limit(
|
|
802
|
+
name: str,
|
|
803
|
+
pct: float,
|
|
804
|
+
resets_at: str | None = None,
|
|
805
|
+
probe_after: str | None = None,
|
|
806
|
+
) -> dict:
|
|
807
|
+
"""One per-model weekly limit in the usage API's ``limits`` shape.
|
|
808
|
+
|
|
809
|
+
``probe_after`` is the header probe's own addition, for a bucket it read
|
|
810
|
+
as spent (see :func:`_scoped_limit_from_headers`).
|
|
811
|
+
"""
|
|
812
|
+
limit: dict = {
|
|
813
|
+
"kind": "weekly_scoped",
|
|
814
|
+
"scope": {"model": {"display_name": name}},
|
|
815
|
+
"percent": pct,
|
|
816
|
+
}
|
|
817
|
+
if resets_at:
|
|
818
|
+
limit["resets_at"] = resets_at
|
|
819
|
+
if probe_after:
|
|
820
|
+
limit["probe_after"] = probe_after
|
|
821
|
+
return limit
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def request_usage_via_probe(access_token: str) -> dict:
|
|
825
|
+
"""Read utilization from the rate-limit headers of a minimal model request.
|
|
826
|
+
|
|
827
|
+
Every ``/v1/messages`` response carries the account's unified 5h/7d
|
|
828
|
+
utilization, and inference is the one thing a setup-token may do. The
|
|
829
|
+
request asks for a single Haiku output token. Returns the raw usage API
|
|
830
|
+
shape (possibly empty) from :func:`parse_unified_ratelimit_headers`.
|
|
831
|
+
Per-model weekly buckets (Fable's) are not in it: they are only reported
|
|
832
|
+
on that model's own responses, see :func:`_add_scoped_limits`.
|
|
833
|
+
|
|
834
|
+
A 429 carrying ``anthropic-ratelimit-unified-status: rejected`` is the
|
|
835
|
+
account confirming its quota refuses inference, whatever the utilization
|
|
836
|
+
numbers say (a per-model or overage limit can bind below 100% on 5h/7d),
|
|
837
|
+
so it is returned as a reading with a ``rejected`` entry rather than
|
|
838
|
+
raised: ``{"retry_after_s": Retry-After or None, "resets_at": when the
|
|
839
|
+
refusal ends — now + Retry-After, else the unified reset header, else
|
|
840
|
+
None}``. A bare 429 (no rejected status) proves no exhaustion and
|
|
841
|
+
re-raises like any other error, so it stays an ``http-429`` failure
|
|
842
|
+
with its Retry-After.
|
|
843
|
+
"""
|
|
844
|
+
try:
|
|
845
|
+
with urllib.request.urlopen(
|
|
846
|
+
_probe_request(access_token, USAGE_PROBE_MODEL), timeout=10
|
|
847
|
+
) as resp:
|
|
848
|
+
return parse_unified_ratelimit_headers(resp.headers)
|
|
849
|
+
except urllib.error.HTTPError as e:
|
|
850
|
+
data = parse_unified_ratelimit_headers(e.headers) if e.headers else {}
|
|
851
|
+
if e.code != 429 or "rejected" not in data:
|
|
852
|
+
raise
|
|
853
|
+
_kind, retry_after = _classify_usage_error(e)
|
|
854
|
+
rejected = data["rejected"]
|
|
855
|
+
if retry_after is not None:
|
|
856
|
+
rejected["resets_at"] = (
|
|
857
|
+
datetime.now(timezone.utc) + timedelta(seconds=retry_after)
|
|
858
|
+
).isoformat()
|
|
859
|
+
rejected["retry_after_s"] = retry_after
|
|
860
|
+
data["rejected"] = rejected
|
|
861
|
+
return data
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _probe_request(access_token: str, model: str) -> urllib.request.Request:
|
|
865
|
+
"""A 1-output-token ``/v1/messages`` request to ``model``."""
|
|
866
|
+
body = json.dumps({
|
|
867
|
+
"model": model,
|
|
868
|
+
"max_tokens": 1,
|
|
869
|
+
"system": USAGE_PROBE_SYSTEM,
|
|
870
|
+
"messages": [{"role": "user", "content": "hi"}],
|
|
871
|
+
}).encode()
|
|
872
|
+
headers = {
|
|
873
|
+
"Authorization": f"Bearer {access_token}",
|
|
874
|
+
"anthropic-beta": OAUTH_BETA_HEADER,
|
|
875
|
+
"anthropic-version": USAGE_PROBE_API_VERSION,
|
|
876
|
+
"Content-Type": "application/json",
|
|
877
|
+
"User-Agent": "claude-swap/1.0",
|
|
878
|
+
}
|
|
879
|
+
return urllib.request.Request(
|
|
880
|
+
USAGE_PROBE_URL, data=body, headers=headers, method="POST"
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def _add_scoped_limits(
|
|
885
|
+
data: dict, access_token: str, last_usage: dict | None
|
|
886
|
+
) -> None:
|
|
887
|
+
"""Add to ``data`` each per-model weekly bucket the main probe lacks.
|
|
888
|
+
|
|
889
|
+
The unified headers report such a bucket (Fable's) only on that model's
|
|
890
|
+
own responses, so each of :data:`USAGE_PROBE_SCOPED_MODELS` costs one
|
|
891
|
+
more 1-token request per poll (:func:`_probe_scoped_limit`). Only the
|
|
892
|
+
per-model ``limits`` are taken from it: the 5h/7d windows and any
|
|
893
|
+
account-level rejection stay the main probe's, since one model's limit
|
|
894
|
+
refusing says nothing about the others.
|
|
895
|
+
|
|
896
|
+
No request is sent for a bucket:
|
|
897
|
+
|
|
898
|
+
- the main response already carries;
|
|
899
|
+
- whose row in ``last_usage`` (the stored reading) is still paused
|
|
900
|
+
(``poll_policy.scoped_probe_paused``): it was read as spent, and that
|
|
901
|
+
row is carried into this reading as it is;
|
|
902
|
+
- when the main probe says ``rejected``, refused or served: the account
|
|
903
|
+
is past a limit of its own, and a second request only adds load or
|
|
904
|
+
spends usage credits.
|
|
905
|
+
"""
|
|
906
|
+
limits = list(data.get("limits") or [])
|
|
907
|
+
have = {
|
|
908
|
+
((lim.get("scope") or {}).get("model") or {}).get("display_name")
|
|
909
|
+
for lim in limits if isinstance(lim, dict)
|
|
910
|
+
}
|
|
911
|
+
now = datetime.now(timezone.utc)
|
|
912
|
+
for model, prefix in USAGE_PROBE_SCOPED_MODELS.items():
|
|
913
|
+
name, _claim = _UNIFIED_SCOPED_WINDOWS[prefix]
|
|
914
|
+
if name in have:
|
|
915
|
+
continue
|
|
916
|
+
limit = _paused_scoped_limit(last_usage, name, now)
|
|
917
|
+
if limit is not None:
|
|
918
|
+
_logger.debug(
|
|
919
|
+
"Scoped usage probe (%s) paused until %s: keeping the stored row",
|
|
920
|
+
model, limit["probe_after"],
|
|
921
|
+
)
|
|
922
|
+
elif "rejected" not in data:
|
|
923
|
+
limit = _probe_scoped_limit(access_token, model, prefix, now)
|
|
924
|
+
if limit is not None:
|
|
925
|
+
have.add(name)
|
|
926
|
+
limits.append(limit)
|
|
927
|
+
if limits:
|
|
928
|
+
data["limits"] = limits
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def _paused_scoped_limit(
|
|
932
|
+
last_usage: dict | None, name: str, now: datetime
|
|
933
|
+
) -> dict | None:
|
|
934
|
+
"""The stored row for bucket ``name`` as a raw limit while its probe is
|
|
935
|
+
paused, else None. A row whose reset cannot be read is not kept."""
|
|
936
|
+
from claude_swap import poll_policy # it imports this module
|
|
937
|
+
|
|
938
|
+
rows = last_usage.get("scoped") if isinstance(last_usage, dict) else None
|
|
939
|
+
for row in rows if isinstance(rows, list) else []:
|
|
940
|
+
if not (
|
|
941
|
+
isinstance(row, dict)
|
|
942
|
+
and row.get("name") == name
|
|
943
|
+
and isinstance(row.get("pct"), (int, float))
|
|
944
|
+
and poll_policy.scoped_probe_paused(row, now.timestamp())
|
|
945
|
+
):
|
|
946
|
+
continue
|
|
947
|
+
resets_at = row.get("resets_at")
|
|
948
|
+
try:
|
|
949
|
+
if resets_at:
|
|
950
|
+
format_reset(resets_at)
|
|
951
|
+
except (ValueError, TypeError):
|
|
952
|
+
return None
|
|
953
|
+
return _scoped_limit(name, float(row["pct"]), resets_at, row["probe_after"])
|
|
954
|
+
return None
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def _probe_scoped_limit(
|
|
958
|
+
access_token: str, model: str, prefix: str, now: datetime
|
|
959
|
+
) -> dict | None:
|
|
960
|
+
"""One 1-token request to ``model``, read as its weekly bucket.
|
|
961
|
+
|
|
962
|
+
A served response, and a 429 with ``anthropic-ratelimit-unified-status:
|
|
963
|
+
rejected``, both describe the bucket
|
|
964
|
+
(:func:`_scoped_limit_from_headers`). Anything else (a bare 429, no
|
|
965
|
+
access to the model, a network error) says nothing about it: None.
|
|
966
|
+
"""
|
|
967
|
+
try:
|
|
968
|
+
with urllib.request.urlopen(
|
|
969
|
+
_probe_request(access_token, model), timeout=10
|
|
970
|
+
) as resp:
|
|
971
|
+
return _scoped_limit_from_headers(resp.headers, prefix, None, now)
|
|
972
|
+
except urllib.error.HTTPError as e:
|
|
973
|
+
refused = (
|
|
974
|
+
e.code == 429 and e.headers
|
|
975
|
+
and e.headers.get("anthropic-ratelimit-unified-status") == "rejected"
|
|
976
|
+
)
|
|
977
|
+
if not refused:
|
|
978
|
+
_logger.debug("Scoped usage probe (%s) failed: HTTP %s", model, e.code)
|
|
979
|
+
return None
|
|
980
|
+
_kind, retry_after = _classify_usage_error(e)
|
|
981
|
+
return _scoped_limit_from_headers(e.headers, prefix, retry_after, now)
|
|
982
|
+
except Exception as e:
|
|
983
|
+
_logger.debug("Scoped usage probe (%s) failed: %r", model, e)
|
|
984
|
+
return None
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
def _scoped_limit_from_headers(
|
|
988
|
+
headers, prefix: str, retry_after_s: float | None, now: datetime
|
|
989
|
+
) -> dict | None:
|
|
990
|
+
"""The per-model bucket a scoped probe's response reports, or None when
|
|
991
|
+
it reports none.
|
|
992
|
+
|
|
993
|
+
The bucket is spent when the response's unified status is ``rejected``
|
|
994
|
+
for it, when the bucket's own ``-status`` is, or when its utilization is
|
|
995
|
+
at 100%. As Claude Code 2.1.322 reads these headers: a served response
|
|
996
|
+
whose unified status is ``rejected`` (with an overage status of
|
|
997
|
+
``allowed`` or ``allowed_warning``) ran on usage credits, and a bucket
|
|
998
|
+
status of ``rejected`` means "at or past its limit", which alone does
|
|
999
|
+
not say requests are refused. So whichever way the next request would
|
|
1000
|
+
go, refused or billed to credits, a spent bucket:
|
|
1001
|
+
|
|
1002
|
+
- reads as at least 100%, whatever its utilization header says (a
|
|
1003
|
+
refusal can bind below it, or arrive without one);
|
|
1004
|
+
- resets at the bucket's own reset, else at the unified reset when the
|
|
1005
|
+
unified status is what marked it;
|
|
1006
|
+
- carries ``probe_after``, before which no request is sent for it again
|
|
1007
|
+
(``poll_policy.scoped_probe_after``). A refusal's Retry-After moves
|
|
1008
|
+
only that deadline: as the row's reset it would end before the bucket
|
|
1009
|
+
does, and a display that rolls a passed weekly reset forward would
|
|
1010
|
+
then show a spent bucket as empty.
|
|
1011
|
+
|
|
1012
|
+
The unified status is for this bucket only when its representative
|
|
1013
|
+
claim names it, or when the response carries no claim. One that names
|
|
1014
|
+
another limit (the 5h window filling after the main probe was served,
|
|
1015
|
+
the usage credits running out) is not this bucket's, which is then read
|
|
1016
|
+
from its own headers alone. The two mistakes are not equal: a bucket
|
|
1017
|
+
wrongly read as spent stays so until ``probe_after``, while one wrongly
|
|
1018
|
+
read as having room costs a request that the next poll corrects.
|
|
1019
|
+
"""
|
|
1020
|
+
from claude_swap import poll_policy # it imports this module
|
|
1021
|
+
|
|
1022
|
+
name, claim = _UNIFIED_SCOPED_WINDOWS[prefix]
|
|
1023
|
+
base = f"anthropic-ratelimit-unified-{prefix}"
|
|
1024
|
+
window = _unified_window(headers, prefix)
|
|
1025
|
+
pct = window[0] if window else None
|
|
1026
|
+
resets_at = _epoch_header_iso(headers.get(f"{base}-reset"))
|
|
1027
|
+
past_limit = (
|
|
1028
|
+
headers.get("anthropic-ratelimit-unified-status") == "rejected"
|
|
1029
|
+
and headers.get("anthropic-ratelimit-unified-representative-claim")
|
|
1030
|
+
in (None, claim)
|
|
1031
|
+
)
|
|
1032
|
+
spent = (
|
|
1033
|
+
past_limit
|
|
1034
|
+
or headers.get(f"{base}-status") == "rejected"
|
|
1035
|
+
or (pct is not None and pct >= 100.0)
|
|
1036
|
+
)
|
|
1037
|
+
if not spent:
|
|
1038
|
+
return None if pct is None else _scoped_limit(name, pct, resets_at)
|
|
1039
|
+
if not past_limit:
|
|
1040
|
+
retry_after_s = None # the Retry-After of another limit's refusal
|
|
1041
|
+
elif not resets_at:
|
|
1042
|
+
resets_at = _epoch_header_iso(
|
|
1043
|
+
headers.get("anthropic-ratelimit-unified-reset")
|
|
1044
|
+
)
|
|
1045
|
+
until = poll_policy.scoped_probe_after(now.timestamp(), resets_at, retry_after_s)
|
|
1046
|
+
return _scoped_limit(
|
|
1047
|
+
name,
|
|
1048
|
+
max(pct or 0.0, 100.0),
|
|
1049
|
+
resets_at,
|
|
1050
|
+
datetime.fromtimestamp(until, tz=timezone.utc).isoformat(),
|
|
1051
|
+
)
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def _usage_from_probe(
|
|
1055
|
+
access_token: str,
|
|
1056
|
+
context: str,
|
|
1057
|
+
scoped_probe: bool = False,
|
|
1058
|
+
last_usage: dict | None = None,
|
|
1059
|
+
) -> "UsageOutcome":
|
|
1060
|
+
"""Usage from the header probe, classified like an endpoint fetch.
|
|
1061
|
+
|
|
1062
|
+
``scoped_probe`` (``usage.fableProbe``) adds the per-model weekly
|
|
1063
|
+
buckets, each from a request of its own unless ``last_usage``, the
|
|
1064
|
+
account's stored reading, shows that bucket as spent (see
|
|
1065
|
+
:func:`_add_scoped_limits`).
|
|
1066
|
+
|
|
1067
|
+
The result is marked ``source: headers`` and keeps the probe's
|
|
1068
|
+
``rejected`` entry, so a refused probe is stored (and decided on) as an
|
|
1069
|
+
account at its limit until the refusal ends, never as a healthy reading.
|
|
1070
|
+
That rejection outranks a window that fails to normalise: instead of
|
|
1071
|
+
failing as ``bad-response``, the reading then keeps ``rejected`` and
|
|
1072
|
+
drops the account's windows, readable ones included. Per-model rows are
|
|
1073
|
+
not among those and stay.
|
|
1074
|
+
"""
|
|
1075
|
+
try:
|
|
1076
|
+
data = request_usage_via_probe(access_token)
|
|
1077
|
+
if scoped_probe:
|
|
1078
|
+
_add_scoped_limits(data, access_token, last_usage)
|
|
1079
|
+
except Exception as e:
|
|
1080
|
+
kind, retry_after = _classify_usage_error(e)
|
|
1081
|
+
cause = kind if retry_after is None else f"{kind}, retry-after {retry_after:.0f}s"
|
|
1082
|
+
_logger.warning("Usage header probe failed %s: %s", context, cause)
|
|
1083
|
+
_logger.debug("Usage header probe failure detail %s: %r", context, e)
|
|
1084
|
+
return UsageOutcome(None, error=kind, retry_after_s=retry_after)
|
|
1085
|
+
try:
|
|
1086
|
+
usage = build_usage_result(data) or {}
|
|
1087
|
+
except Exception as e:
|
|
1088
|
+
kind, _ = _classify_usage_error(e)
|
|
1089
|
+
_logger.debug("Usage header probe failure detail %s: %r", context, e)
|
|
1090
|
+
if not (isinstance(e, _InvalidUsageResponse) and "rejected" in data):
|
|
1091
|
+
_logger.warning("Usage header probe failed %s: %s", context, kind)
|
|
1092
|
+
return UsageOutcome(None, error=kind)
|
|
1093
|
+
# A rejection outranks its unreadable windows: the refusal and its
|
|
1094
|
+
# Retry-After are kept, so the account stays at its limit. So are
|
|
1095
|
+
# the per-model rows: a paused one dropped here would be asked about
|
|
1096
|
+
# again as soon as the refusal ends.
|
|
1097
|
+
_logger.warning(
|
|
1098
|
+
"Usage header probe %s: %s, keeping the rejection", context, kind
|
|
1099
|
+
)
|
|
1100
|
+
usage = build_usage_result({"limits": data.get("limits")}) or {}
|
|
1101
|
+
if "rejected" in data:
|
|
1102
|
+
usage["rejected"] = data["rejected"]
|
|
1103
|
+
_logger.warning(
|
|
1104
|
+
"Usage header probe %s: request rejected (retry-after %s)",
|
|
1105
|
+
context, data["rejected"].get("retry_after_s"),
|
|
1106
|
+
)
|
|
1107
|
+
if not usage:
|
|
1108
|
+
_logger.warning(
|
|
1109
|
+
"Usage header probe %s: response carried no rate-limit headers",
|
|
1110
|
+
context,
|
|
1111
|
+
)
|
|
1112
|
+
return UsageOutcome(None, error="bad-response")
|
|
1113
|
+
usage["source"] = USAGE_SOURCE_HEADERS
|
|
1114
|
+
return UsageOutcome(usage)
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
class _InvalidUsageResponse(ValueError):
|
|
1118
|
+
"""A reported window that cannot be read as a measurement (``bad-response``)."""
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _reported_window(data: dict, key: str) -> dict | None:
|
|
1122
|
+
"""The raw ``five_hour``/``seven_day`` window, or None when absent.
|
|
1123
|
+
|
|
1124
|
+
Absent means missing or ``null``: from the usage endpoint, a limit the
|
|
1125
|
+
account does not have (a verified Ultra account reports ``five_hour:
|
|
1126
|
+
null``); from the header probe, a window it did not carry. ``{}`` counts
|
|
1127
|
+
as absent too, a compatibility exception for the falsy check this
|
|
1128
|
+
replaces. Any other non-object value is a malformed response.
|
|
1129
|
+
"""
|
|
1130
|
+
if key not in data or data[key] is None:
|
|
1131
|
+
return None
|
|
1132
|
+
window = data[key]
|
|
1133
|
+
if isinstance(window, dict):
|
|
1134
|
+
return window if window else None
|
|
1135
|
+
raise _InvalidUsageResponse(f"{key} must be an object or null")
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
def _window_entry(key: str, window: dict) -> dict:
|
|
1139
|
+
"""Normalise one reported window to ``{"pct", "resets_at", ...}``.
|
|
1140
|
+
|
|
1141
|
+
``utilization: null`` (allowed by Claude Code's usage schema) keeps the
|
|
1142
|
+
window with ``pct`` None, unavailable rather than zero, and any
|
|
1143
|
+
``resets_at``. A missing, boolean, string, non-finite or negative
|
|
1144
|
+
``utilization`` raises ``_InvalidUsageResponse``: dropping the window
|
|
1145
|
+
would let the other one pass as a complete reading.
|
|
1146
|
+
"""
|
|
1147
|
+
if "utilization" not in window:
|
|
1148
|
+
raise _InvalidUsageResponse(f"{key}.utilization is missing")
|
|
1149
|
+
pct = window["utilization"]
|
|
1150
|
+
if pct is not None:
|
|
1151
|
+
try:
|
|
1152
|
+
valid = (
|
|
1153
|
+
isinstance(pct, (int, float))
|
|
1154
|
+
and not isinstance(pct, bool)
|
|
1155
|
+
and math.isfinite(pct)
|
|
1156
|
+
and pct >= 0
|
|
1157
|
+
)
|
|
1158
|
+
except OverflowError:
|
|
1159
|
+
valid = False
|
|
1160
|
+
if not valid:
|
|
1161
|
+
raise _InvalidUsageResponse(
|
|
1162
|
+
f"{key}.utilization must be null or a finite non-negative number"
|
|
1163
|
+
)
|
|
1164
|
+
entry: dict = {"pct": pct}
|
|
1165
|
+
if window.get("resets_at"):
|
|
1166
|
+
entry["resets_at"] = window["resets_at"]
|
|
1167
|
+
entry["countdown"], entry["clock"] = format_reset(window["resets_at"])
|
|
1168
|
+
return entry
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _classify_usage_error(e: Exception) -> tuple[str, float | None]:
|
|
1172
|
+
"""Map a usage-fetch exception to ``(kind, retry_after_s)``.
|
|
1173
|
+
|
|
1174
|
+
``kind`` is a short stable token for logs and backoff decisions
|
|
1175
|
+
(``"http-429"``, ``"timeout"``, ``"tls-cert"``, ``"network"``,
|
|
1176
|
+
``"bad-response"``, ``"oauth_not_allowed_for_organization"`` (a 403 whose
|
|
1177
|
+
body says so), or the exception type name as a fallback).
|
|
1178
|
+
``retry_after_s`` is the parsed ``Retry-After`` header when the server sent
|
|
1179
|
+
one (seconds form only — the HTTP-date form is rare enough to ignore).
|
|
1180
|
+
"""
|
|
1181
|
+
if isinstance(e, urllib.error.HTTPError):
|
|
1182
|
+
retry_after = None
|
|
1183
|
+
raw = e.headers.get("Retry-After") if e.headers else None
|
|
1184
|
+
if raw:
|
|
1185
|
+
try:
|
|
1186
|
+
retry_after = max(0.0, float(raw.strip()))
|
|
1187
|
+
except ValueError:
|
|
1188
|
+
pass
|
|
1189
|
+
if e.code == 403:
|
|
1190
|
+
# The org-policy 403 (a lapsed plan) names its cause only in the
|
|
1191
|
+
# body, so it is the one status whose body is read. This runs
|
|
1192
|
+
# inside `except` handlers: it must never raise.
|
|
1193
|
+
try:
|
|
1194
|
+
code = json.loads(e.read(4096))["error"]["details"]["error_code"]
|
|
1195
|
+
except Exception:
|
|
1196
|
+
code = None
|
|
1197
|
+
if code == "oauth_not_allowed_for_organization":
|
|
1198
|
+
return code, retry_after
|
|
1199
|
+
return f"http-{e.code}", retry_after
|
|
1200
|
+
if isinstance(e, TimeoutError): # socket.timeout is an alias since 3.10
|
|
1201
|
+
return "timeout", None
|
|
1202
|
+
if isinstance(e, urllib.error.URLError):
|
|
1203
|
+
if isinstance(e.reason, TimeoutError):
|
|
1204
|
+
return "timeout", None
|
|
1205
|
+
# A certificate the client refused (an untrusted chain, a name that
|
|
1206
|
+
# does not match, an expired one) is not an unreachable host: the
|
|
1207
|
+
# repair is trust or the clock, so it gets its own kind. Measured on
|
|
1208
|
+
# macOS against a local server, with truststore 0.10.4 and with stdlib
|
|
1209
|
+
# ssl: all three raise this class, SSL_CERT_FILE adds a CA on both
|
|
1210
|
+
# paths, and NODE_EXTRA_CA_CERTS, which Claude Code 2.1.322 honours,
|
|
1211
|
+
# does not. Other TLS failures (a plaintext port) stay "network".
|
|
1212
|
+
if isinstance(e.reason, ssl.SSLCertVerificationError):
|
|
1213
|
+
return "tls-cert", None
|
|
1214
|
+
return "network", None
|
|
1215
|
+
if isinstance(e, (json.JSONDecodeError, _InvalidUsageResponse)):
|
|
1216
|
+
return "bad-response", None
|
|
1217
|
+
return type(e).__name__, None
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def _log_usage_failure(
|
|
1221
|
+
context: str, e: Exception, kind: str, retry_after_s: float | None = None
|
|
1222
|
+
) -> None:
|
|
1223
|
+
"""One WARNING line with the cause so it lands in the default log file
|
|
1224
|
+
(issue #85 was undiagnosable with failures swallowed at DEBUG); the full
|
|
1225
|
+
exception repr stays at DEBUG. The line is what users paste into public
|
|
1226
|
+
issues, so ``context`` must not carry the email, and the server's
|
|
1227
|
+
Retry-After rides along when present (it answers the backoff-tuning
|
|
1228
|
+
question without a second ask)."""
|
|
1229
|
+
where = f" {context}" if context else ""
|
|
1230
|
+
cause = kind if retry_after_s is None else f"{kind}, retry-after {retry_after_s:.0f}s"
|
|
1231
|
+
if kind == "http-429":
|
|
1232
|
+
# Whether the budget counts per access token or per account depends
|
|
1233
|
+
# on the org's 429 regime (both measured; see poll_policy), so the
|
|
1234
|
+
# message stays scope-neutral. Under the account-scoped regime
|
|
1235
|
+
# re-authenticating does not clear a block, and two machines holding
|
|
1236
|
+
# different tokens for one account still compete for one budget —
|
|
1237
|
+
# cumulative polling across surfaces and machines can saturate it,
|
|
1238
|
+
# and backoff plus the adaptive cadence are the recovery.
|
|
1239
|
+
cause += " (usage-endpoint budget reached; backing off)"
|
|
1240
|
+
_logger.warning("Usage fetch failed%s: %s", where, cause)
|
|
1241
|
+
_logger.debug("Usage fetch failure detail%s: %r", where, e)
|
|
1242
|
+
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
def build_usage_result(data: dict) -> dict | None:
|
|
1246
|
+
"""Normalize raw usage API data into the structure used by the CLI.
|
|
1247
|
+
|
|
1248
|
+
``five_hour``/``seven_day`` go through :func:`_reported_window` and
|
|
1249
|
+
:func:`_window_entry`: an absent window stays absent, ``utilization:
|
|
1250
|
+
null`` keeps the window with ``pct`` None, and a malformed one fails
|
|
1251
|
+
the whole fetch as ``bad-response`` (a refused header probe keeps its
|
|
1252
|
+
rejection instead, see :func:`_usage_from_probe`).
|
|
1253
|
+
"""
|
|
1254
|
+
_logger.debug("Usage API response: %s", json.dumps(data, indent=2))
|
|
1255
|
+
|
|
1256
|
+
result = {}
|
|
1257
|
+
|
|
1258
|
+
for key in ("five_hour", "seven_day"):
|
|
1259
|
+
window = _reported_window(data, key)
|
|
1260
|
+
if window is not None:
|
|
1261
|
+
result[key] = _window_entry(key, window)
|
|
1262
|
+
|
|
1263
|
+
eu = data.get("extra_usage")
|
|
1264
|
+
if eu and eu.get("is_enabled"):
|
|
1265
|
+
# Claude Code returns nullable used_credits, monthly_limit, and utilization
|
|
1266
|
+
# (monthly_limit=None = unlimited). All three are needed to render the spend
|
|
1267
|
+
# line, so when any is null skip just the spend entry; five_hour/seven_day
|
|
1268
|
+
# go through unchanged.
|
|
1269
|
+
used_credits = eu.get("used_credits")
|
|
1270
|
+
monthly_limit = eu.get("monthly_limit")
|
|
1271
|
+
utilization = eu.get("utilization")
|
|
1272
|
+
if used_credits is not None and monthly_limit is not None and utilization is not None:
|
|
1273
|
+
try:
|
|
1274
|
+
spend_entry: dict = {
|
|
1275
|
+
"used": float(used_credits) / 100,
|
|
1276
|
+
"limit": float(monthly_limit) / 100,
|
|
1277
|
+
"pct": float(utilization),
|
|
1278
|
+
"currency": eu.get("currency", "USD"),
|
|
1279
|
+
}
|
|
1280
|
+
if eu.get("resets_at"):
|
|
1281
|
+
spend_entry["resets_at"] = eu["resets_at"]
|
|
1282
|
+
spend_entry["countdown"], spend_entry["clock"] = format_reset(eu["resets_at"])
|
|
1283
|
+
result["spend"] = spend_entry
|
|
1284
|
+
except (TypeError, ValueError) as e:
|
|
1285
|
+
_logger.debug("extra_usage parse failed: %r", e)
|
|
1286
|
+
|
|
1287
|
+
# Per-model weekly limits live in the newer ``limits`` array as
|
|
1288
|
+
# ``weekly_scoped`` entries carrying a ``scope.model.display_name`` (e.g.
|
|
1289
|
+
# "Fable"). The legacy five_hour/seven_day keys above never expose these, so
|
|
1290
|
+
# surface each scoped window separately. Absent/older responses (no
|
|
1291
|
+
# ``limits``) simply yield no ``scoped`` key.
|
|
1292
|
+
limits = data.get("limits")
|
|
1293
|
+
if isinstance(limits, list):
|
|
1294
|
+
scoped: list[dict] = []
|
|
1295
|
+
for lim in limits:
|
|
1296
|
+
if not isinstance(lim, dict):
|
|
1297
|
+
continue
|
|
1298
|
+
scope = lim.get("scope")
|
|
1299
|
+
model = scope.get("model") if isinstance(scope, dict) else None
|
|
1300
|
+
name = model.get("display_name") if isinstance(model, dict) else None
|
|
1301
|
+
pct = lim.get("percent")
|
|
1302
|
+
if not name or not isinstance(pct, (int, float)):
|
|
1303
|
+
continue
|
|
1304
|
+
scoped_entry: dict = {"name": name, "pct": float(pct)}
|
|
1305
|
+
if lim.get("resets_at"):
|
|
1306
|
+
scoped_entry["resets_at"] = lim["resets_at"]
|
|
1307
|
+
scoped_entry["countdown"], scoped_entry["clock"] = format_reset(lim["resets_at"])
|
|
1308
|
+
if isinstance(lim.get("probe_after"), str):
|
|
1309
|
+
# Only the header probe sets it (see _scoped_limit_from_headers).
|
|
1310
|
+
scoped_entry["probe_after"] = lim["probe_after"]
|
|
1311
|
+
scoped.append(scoped_entry)
|
|
1312
|
+
if scoped:
|
|
1313
|
+
result["scoped"] = scoped
|
|
1314
|
+
|
|
1315
|
+
return result if result else None
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
# Label of the 5-hour window as ``relevant_windows`` reports it. The only
|
|
1319
|
+
# window that is NOT weekly: every consumer that treats the 5h window
|
|
1320
|
+
# differently (``lines.window_line``, the TUI's per-row switch-line tick) keys
|
|
1321
|
+
# on this constant, so the label is spelled in one place.
|
|
1322
|
+
FIVE_HOUR_LABEL = "5h"
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
# Label of the window a refused header probe adds (see relevant_windows).
|
|
1326
|
+
REJECTED_LABEL = "rejected"
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def _header_reading_complete(usage: dict, models: Sequence[str]) -> bool:
|
|
1330
|
+
"""Whether a header-probe reading carries every window a decision needs.
|
|
1331
|
+
|
|
1332
|
+
The 7d window always, plus each configured per-model window; the headers
|
|
1333
|
+
only carry Fable's, and only with ``usage.fableProbe`` on, so ``all``
|
|
1334
|
+
(every per-model window the account has) can never be shown complete.
|
|
1335
|
+
A missing 5h window is not a gap: an Ultra account has none (a 5h header
|
|
1336
|
+
without a usable utilization fails the reading instead, see
|
|
1337
|
+
:func:`parse_unified_ratelimit_headers`).
|
|
1338
|
+
"""
|
|
1339
|
+
if not isinstance(usage.get("seven_day"), dict):
|
|
1340
|
+
return False
|
|
1341
|
+
if not models:
|
|
1342
|
+
return True
|
|
1343
|
+
wanted = {m.lower() for m in models}
|
|
1344
|
+
if "all" in wanted:
|
|
1345
|
+
return False
|
|
1346
|
+
have = {
|
|
1347
|
+
s["name"].lower()
|
|
1348
|
+
for s in usage.get("scoped") or []
|
|
1349
|
+
if isinstance(s, dict) and isinstance(s.get("name"), str)
|
|
1350
|
+
}
|
|
1351
|
+
return wanted <= have
|
|
1352
|
+
|
|
1353
|
+
|
|
1354
|
+
def relevant_windows(
|
|
1355
|
+
usage: dict | None, models: Sequence[str] = ()
|
|
1356
|
+
) -> list[tuple[str, float, str | None]]:
|
|
1357
|
+
"""Every ``(label, pct, resets_at)`` window that gates this account.
|
|
1358
|
+
|
|
1359
|
+
The reported 5-hour ("5h") and 7-day ("7d") windows: an Ultra account
|
|
1360
|
+
has no 5-hour one, and a window without a figure (``pct`` None) is
|
|
1361
|
+
skipped. When ``models`` is non-empty, each named per-model weekly
|
|
1362
|
+
``scoped`` window is included too
|
|
1363
|
+
(matched case-insensitively on display name, e.g. "Fable"; the sentinel
|
|
1364
|
+
``all`` matches every scoped window the account reports). The single
|
|
1365
|
+
canonical window source for decisions, scheduling, and reset math — so a
|
|
1366
|
+
window that binds a decision can never be invisible to the scheduler.
|
|
1367
|
+
``spend`` (pay-as-you-go extra-usage credits) is a separate axis and is
|
|
1368
|
+
deliberately excluded. ``resets_at`` is the ISO string as fetched, or
|
|
1369
|
+
``None`` when the API sent none.
|
|
1370
|
+
|
|
1371
|
+
A header-probe reading (``source: headers``) missing any window the
|
|
1372
|
+
decision needs (:func:`_header_reading_complete`) yields none of its
|
|
1373
|
+
windows, so it reads as unknown — still shown, never ranked: one 5h
|
|
1374
|
+
window at 5% must not pass for 95% headroom. A reading without a 5h
|
|
1375
|
+
window is complete unless a per-model window is needed. A refused probe
|
|
1376
|
+
(``rejected``) adds a 100% ``"rejected"`` window resetting when the
|
|
1377
|
+
refusal ends, so the account reads as at its limit until then.
|
|
1378
|
+
"""
|
|
1379
|
+
if not isinstance(usage, dict):
|
|
1380
|
+
return []
|
|
1381
|
+
windows: list[tuple[str, float, str | None]] = []
|
|
1382
|
+
if usage.get("source") != USAGE_SOURCE_HEADERS or _header_reading_complete(
|
|
1383
|
+
usage, models
|
|
1384
|
+
):
|
|
1385
|
+
for key, label in (("five_hour", FIVE_HOUR_LABEL), ("seven_day", "7d")):
|
|
1386
|
+
window = usage.get(key)
|
|
1387
|
+
if isinstance(window, dict) and isinstance(window.get("pct"), (int, float)):
|
|
1388
|
+
windows.append((label, float(window["pct"]), window.get("resets_at")))
|
|
1389
|
+
if models:
|
|
1390
|
+
wanted = {m.lower() for m in models}
|
|
1391
|
+
match_all = "all" in wanted
|
|
1392
|
+
scoped = usage.get("scoped")
|
|
1393
|
+
if isinstance(scoped, list):
|
|
1394
|
+
for s in scoped:
|
|
1395
|
+
if (
|
|
1396
|
+
isinstance(s, dict)
|
|
1397
|
+
and isinstance(s.get("pct"), (int, float))
|
|
1398
|
+
and isinstance(s.get("name"), str)
|
|
1399
|
+
and (match_all or s["name"].lower() in wanted)
|
|
1400
|
+
):
|
|
1401
|
+
windows.append((s["name"], float(s["pct"]), s.get("resets_at")))
|
|
1402
|
+
rejected = usage.get("rejected")
|
|
1403
|
+
if isinstance(rejected, dict):
|
|
1404
|
+
windows.append((REJECTED_LABEL, 100.0, rejected.get("resets_at")))
|
|
1405
|
+
return windows
|
|
1406
|
+
|
|
1407
|
+
|
|
1408
|
+
def account_headroom(
|
|
1409
|
+
usage: dict | None, models: Sequence[str] = ()
|
|
1410
|
+
) -> float | None:
|
|
1411
|
+
"""Remaining percentage before this account hits a rate-limit window.
|
|
1412
|
+
|
|
1413
|
+
Considers the 5-hour and 7-day windows the account reports (Ultra has
|
|
1414
|
+
no 5-hour one; a window without a figure does not count). When
|
|
1415
|
+
``models`` is non-empty, each named per-model weekly
|
|
1416
|
+
``scoped`` window (see :func:`relevant_windows`) is folded in too: a model
|
|
1417
|
+
maxed at 100% blocks that model's work even with 5h/7d headroom, so for
|
|
1418
|
+
someone pinned to that model it binds just as hard. Returns the headroom
|
|
1419
|
+
of the *binding* window (``100 - max(pct)``), so ``<= 0`` means the
|
|
1420
|
+
account is at or over a limit. Returns ``None`` when usage is unavailable
|
|
1421
|
+
or carries no window data, which callers treat as "unknown" (never
|
|
1422
|
+
auto-skipped).
|
|
1423
|
+
"""
|
|
1424
|
+
pcts = [pct for _, pct, _ in relevant_windows(usage, models)]
|
|
1425
|
+
if not pcts:
|
|
1426
|
+
return None
|
|
1427
|
+
return 100.0 - max(pcts)
|
|
1428
|
+
|
|
1429
|
+
|
|
1430
|
+
@dataclass(frozen=True)
|
|
1431
|
+
class UsageOutcome:
|
|
1432
|
+
"""Result of a usage-API fetch attempt.
|
|
1433
|
+
|
|
1434
|
+
``usage`` is the normalized usage dict on success (it can also be ``None``
|
|
1435
|
+
on a successful round trip whose response carried no window data).
|
|
1436
|
+
``error`` is ``None`` on success, else a ``_classify_usage_error`` kind
|
|
1437
|
+
(plus ``"no-access-token"`` / ``"refresh-failed"`` for pre-request
|
|
1438
|
+
failures). ``retry_after_s`` carries the server's Retry-After when sent.
|
|
1439
|
+
"""
|
|
1440
|
+
|
|
1441
|
+
usage: dict | None
|
|
1442
|
+
error: str | None = None
|
|
1443
|
+
retry_after_s: float | None = None
|
|
1444
|
+
# Fingerprint of the credential whose rt was POSTed when error is a
|
|
1445
|
+
# permanent auth kind — lets the store bind the strike to that
|
|
1446
|
+
# generation (see usage_store.FetchRecord.struck_fp).
|
|
1447
|
+
struck_fp: str | None = None
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def fetch_usage(access_token: str) -> dict | None:
|
|
1451
|
+
"""Fetch 5-hour and 7-day utilization from the Anthropic usage API."""
|
|
1452
|
+
try:
|
|
1453
|
+
data = request_usage_data(access_token)
|
|
1454
|
+
return build_usage_result(data)
|
|
1455
|
+
except Exception as e:
|
|
1456
|
+
kind, _ = _classify_usage_error(e)
|
|
1457
|
+
_log_usage_failure("", e, kind)
|
|
1458
|
+
return None
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
# Refresh refusals that keep their own kind in the outcome instead of the
|
|
1462
|
+
# generic "refresh-failed": each has its own note (``ERROR_NOTES``) and none
|
|
1463
|
+
# is a verdict on the token. `consume-busy` is another gate holding the slot;
|
|
1464
|
+
# `live-login` is the gate declining a grant the live login also holds.
|
|
1465
|
+
_DETERMINISTIC_REFRESH_ERRORS = (
|
|
1466
|
+
"store-unmirrored", "invalid_client", "consume-busy", "stash-unreadable",
|
|
1467
|
+
"live-login",
|
|
1468
|
+
)
|
|
1469
|
+
|
|
1470
|
+
|
|
1471
|
+
def try_fetch_usage_for_account(
|
|
1472
|
+
account_num: str,
|
|
1473
|
+
email: str,
|
|
1474
|
+
credentials: str,
|
|
1475
|
+
is_active: bool,
|
|
1476
|
+
persist_credentials: Callable[[str, str, str], None] | None = None,
|
|
1477
|
+
refresh_via: Callable[[str, str, str], RefreshOutcome] | None = None,
|
|
1478
|
+
header_probe: bool = False,
|
|
1479
|
+
scoped_probe: bool = False,
|
|
1480
|
+
last_usage: dict | None = None,
|
|
1481
|
+
request_log: bool = False,
|
|
1482
|
+
) -> UsageOutcome:
|
|
1483
|
+
"""Fetch usage for an account, refreshing an inactive account's token
|
|
1484
|
+
when the usage endpoint answers 401.
|
|
1485
|
+
|
|
1486
|
+
The usage request goes first even when the stored expiry has passed. A
|
|
1487
|
+
refresh token is spent once it is sent, so it is not sent on a connection
|
|
1488
|
+
that has just failed a cheaper request: a timeout or a network error here
|
|
1489
|
+
ends the call with nothing spent, and the store's backoff paces the next
|
|
1490
|
+
try. The endpoint answers 401 to an expired access token (issue #596's
|
|
1491
|
+
log on cswap 1.1.0: ``Usage fetch failed for account 2: http-401`` for a
|
|
1492
|
+
token past its expiry). One refresh attempt per call.
|
|
1493
|
+
|
|
1494
|
+
Active accounts are never refreshed — Claude Code owns those credentials.
|
|
1495
|
+
``refresh_via(account_num, email, snapshot)`` supersedes the direct POST
|
|
1496
|
+
when given: the switcher passes its consume gate, which re-reads the
|
|
1497
|
+
freshest copy under the slot lock, persists via fingerprint CAS, and
|
|
1498
|
+
never consumes a superseded snapshot. ``persist_credentials`` is then
|
|
1499
|
+
unused for the refresh (the gate persists internally).
|
|
1500
|
+
|
|
1501
|
+
A setup-token credential (see :func:`is_setup_token`) never reaches the
|
|
1502
|
+
usage endpoint, which cannot answer its inference-only scope. With
|
|
1503
|
+
``header_probe`` its usage comes from :func:`request_usage_via_probe`
|
|
1504
|
+
instead, in place of the endpoint request, so the caller's poll plan and
|
|
1505
|
+
backoff pace it exactly like an endpoint fetch; without it the outcome is
|
|
1506
|
+
the ``"setup-token"`` error and no request is sent. ``scoped_probe`` and
|
|
1507
|
+
``last_usage`` (the account's stored reading) only shape that probe, see
|
|
1508
|
+
:func:`_usage_from_probe`. ``request_log`` logs a line for each usage
|
|
1509
|
+
endpoint request (see :func:`request_usage_data`).
|
|
1510
|
+
"""
|
|
1511
|
+
context = f"for account {account_num}" # no email: paste-safe for public issues
|
|
1512
|
+
oauth = extract_oauth_data(credentials)
|
|
1513
|
+
access_token = oauth.get("accessToken") if oauth else None
|
|
1514
|
+
if not access_token:
|
|
1515
|
+
return UsageOutcome(None, error="no-access-token")
|
|
1516
|
+
|
|
1517
|
+
if is_setup_token(oauth):
|
|
1518
|
+
if header_probe:
|
|
1519
|
+
return _usage_from_probe(
|
|
1520
|
+
access_token, context, scoped_probe, last_usage
|
|
1521
|
+
)
|
|
1522
|
+
return UsageOutcome(None, error="setup-token")
|
|
1523
|
+
|
|
1524
|
+
working_credentials = credentials
|
|
1525
|
+
|
|
1526
|
+
try:
|
|
1527
|
+
data = request_usage_data(access_token, request_log=request_log, slot=account_num)
|
|
1528
|
+
return UsageOutcome(build_usage_result(data))
|
|
1529
|
+
except urllib.error.HTTPError as e:
|
|
1530
|
+
kind, retry_after = _classify_usage_error(e)
|
|
1531
|
+
if (
|
|
1532
|
+
e.code != 401
|
|
1533
|
+
or is_active
|
|
1534
|
+
or not oauth
|
|
1535
|
+
or not oauth.get("refreshToken")
|
|
1536
|
+
):
|
|
1537
|
+
_log_usage_failure(context, e, kind, retry_after)
|
|
1538
|
+
return UsageOutcome(None, error=kind, retry_after_s=retry_after)
|
|
1539
|
+
|
|
1540
|
+
# The server refused the access token and the request came back, so
|
|
1541
|
+
# the network works: refresh once and ask again (inactive accounts
|
|
1542
|
+
# only). A server-rejected grant (invalid_grant) means this
|
|
1543
|
+
# refresh-token lineage is permanently dead — surface it distinctly
|
|
1544
|
+
# (not the generic "refresh-failed") so the store can quarantine
|
|
1545
|
+
# instead of retrying a dead token forever.
|
|
1546
|
+
if refresh_via is not None:
|
|
1547
|
+
refresh = refresh_via(account_num, email, working_credentials)
|
|
1548
|
+
else:
|
|
1549
|
+
refresh = try_refresh_oauth_credentials(working_credentials)
|
|
1550
|
+
if not refresh.credentials:
|
|
1551
|
+
_log_usage_failure(context, e, kind)
|
|
1552
|
+
dead = refresh.error in ("invalid_grant", "no_refresh_token")
|
|
1553
|
+
# Deterministic kinds keep their identity here too — collapsing
|
|
1554
|
+
# them to "refresh-failed" would hide the ERROR_NOTES remedy
|
|
1555
|
+
# exactly on the 401 path (a not-yet-locally-expired token the
|
|
1556
|
+
# server already rotated past).
|
|
1557
|
+
distinct = dead or refresh.error in _DETERMINISTIC_REFRESH_ERRORS
|
|
1558
|
+
return UsageOutcome(
|
|
1559
|
+
None,
|
|
1560
|
+
error=refresh.error if distinct else "refresh-failed",
|
|
1561
|
+
struck_fp=(
|
|
1562
|
+
(refresh.consumed_fp
|
|
1563
|
+
or credential_fingerprint(working_credentials))
|
|
1564
|
+
if dead else None
|
|
1565
|
+
),
|
|
1566
|
+
)
|
|
1567
|
+
|
|
1568
|
+
working_credentials = refresh.credentials
|
|
1569
|
+
if refresh_via is None:
|
|
1570
|
+
_persist(persist_credentials, account_num, email, working_credentials)
|
|
1571
|
+
refreshed_oauth = extract_oauth_data(working_credentials)
|
|
1572
|
+
new_token = refreshed_oauth.get("accessToken") if refreshed_oauth else None
|
|
1573
|
+
if not new_token:
|
|
1574
|
+
return UsageOutcome(None, error="refresh-failed")
|
|
1575
|
+
|
|
1576
|
+
try:
|
|
1577
|
+
data = request_usage_data(new_token, request_log=request_log, slot=account_num)
|
|
1578
|
+
return UsageOutcome(build_usage_result(data))
|
|
1579
|
+
except Exception as retry_error:
|
|
1580
|
+
kind, retry_after = _classify_usage_error(retry_error)
|
|
1581
|
+
_log_usage_failure(context + " after refresh", retry_error, kind, retry_after)
|
|
1582
|
+
return UsageOutcome(None, error=kind, retry_after_s=retry_after)
|
|
1583
|
+
except Exception as e:
|
|
1584
|
+
kind, retry_after = _classify_usage_error(e)
|
|
1585
|
+
_log_usage_failure(context, e, kind, retry_after)
|
|
1586
|
+
return UsageOutcome(None, error=kind, retry_after_s=retry_after)
|
|
1587
|
+
|
|
1588
|
+
|
|
1589
|
+
def fetch_usage_for_account(
|
|
1590
|
+
account_num: str,
|
|
1591
|
+
email: str,
|
|
1592
|
+
credentials: str,
|
|
1593
|
+
is_active: bool,
|
|
1594
|
+
persist_credentials: Callable[[str, str, str], None] | None = None,
|
|
1595
|
+
) -> dict | None:
|
|
1596
|
+
"""Usage dict or None (see try_fetch_usage_for_account for the cause)."""
|
|
1597
|
+
return try_fetch_usage_for_account(
|
|
1598
|
+
account_num, email, credentials, is_active, persist_credentials
|
|
1599
|
+
).usage
|
|
1600
|
+
|
|
1601
|
+
|
|
1602
|
+
def _persist(
|
|
1603
|
+
callback: Callable[[str, str, str], None] | None,
|
|
1604
|
+
account_num: str,
|
|
1605
|
+
email: str,
|
|
1606
|
+
credentials: str,
|
|
1607
|
+
) -> None:
|
|
1608
|
+
"""Call the persist callback, warning loudly on failure."""
|
|
1609
|
+
if not callback:
|
|
1610
|
+
return
|
|
1611
|
+
try:
|
|
1612
|
+
callback(account_num, email, credentials)
|
|
1613
|
+
except Exception as e:
|
|
1614
|
+
_logger.warning(
|
|
1615
|
+
"Refreshed OAuth token for account %s (%s) but failed to persist it: %r. "
|
|
1616
|
+
"The refresh token on disk may now be stale; if the next refresh fails "
|
|
1617
|
+
"with invalid_grant, re-run `cswap --add-account` after logging in.",
|
|
1618
|
+
account_num,
|
|
1619
|
+
email,
|
|
1620
|
+
e,
|
|
1621
|
+
)
|
|
1622
|
+
# stderr, not stdout: this runs inside ``cswap list --json`` and the
|
|
1623
|
+
# other ``--json`` commands, whose stdout is one machine-readable object.
|
|
1624
|
+
print_warning(
|
|
1625
|
+
f"Warning: failed to save refreshed token for account {account_num} ({email}). "
|
|
1626
|
+
f"If the next refresh fails, re-run `cswap --add-account` after logging in.",
|
|
1627
|
+
file=sys.stderr,
|
|
1628
|
+
)
|