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
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Subscription plan per account, for display only (#350).
|
|
2
|
+
|
|
3
|
+
The plan comes from ``GET /api/oauth/profile`` — the same endpoint
|
|
4
|
+
:func:`oauth.fetch_oauth_profile` calls to resolve identity. That function
|
|
5
|
+
returns only the identity it needs; the response carries a good deal more, of
|
|
6
|
+
which five ``organization`` fields are kept here.
|
|
7
|
+
|
|
8
|
+
Measured shapes, one account each:
|
|
9
|
+
|
|
10
|
+
===================== ========== ====================== ===================
|
|
11
|
+
state status rate_limit_tier billing_type
|
|
12
|
+
===================== ========== ====================== ===================
|
|
13
|
+
active Max active default_claude_max_20x stripe_subscription
|
|
14
|
+
cancelled, in period active default_claude_max_20x stripe_subscription
|
|
15
|
+
lapsed canceled default_claude_ai none
|
|
16
|
+
===================== ========== ====================== ===================
|
|
17
|
+
|
|
18
|
+
2026-11-07: an Ultra account carries ``default_claude_max_20x``, organization
|
|
19
|
+
type ``claude_max`` and ``plan_display_name`` "Ultra", so the tier alone does
|
|
20
|
+
not name the plan. An Enterprise seat carries ``default_claude_zero`` and no
|
|
21
|
+
plan name, so its organization type claims the label.
|
|
22
|
+
|
|
23
|
+
``subscription_status`` does not move at cancellation, only at lapse, so a
|
|
24
|
+
cancelled-but-still-running subscription is indistinguishable from one that
|
|
25
|
+
will renew. That is why renewal is not shown. Expired is ``canceled`` together
|
|
26
|
+
with the free tier — both, so neither field alone can mark an account.
|
|
27
|
+
|
|
28
|
+
Paced on its own clock and stored in its own file, never through the usage
|
|
29
|
+
store. The usage endpoint is rate limited and backs off per account; a plan
|
|
30
|
+
refresh that rode on it would freeze an old label behind exactly the accounts
|
|
31
|
+
most likely to have changed plan — the ones whose usage calls are failing.
|
|
32
|
+
|
|
33
|
+
A refresh only ever uses an access token that is already valid. This module
|
|
34
|
+
never refreshes a token itself: rotating an inactive slot's refresh token
|
|
35
|
+
without persisting the result would leave that slot holding a consumed token.
|
|
36
|
+
The usage collector refreshes tokens on its own schedule, and a due plan whose
|
|
37
|
+
token is not valid yet simply waits for the next pass.
|
|
38
|
+
|
|
39
|
+
A response is only believed once its account and organization UUIDs match the
|
|
40
|
+
slot: the token in a slot is not proof of whose it is. A failed or mismatched
|
|
41
|
+
read sets ``retryAt`` beside the record and leaves ``fetchedAt`` alone, so the
|
|
42
|
+
label keeps the age of the last real reading and the endpoint is not asked
|
|
43
|
+
again on every snapshot.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import json
|
|
49
|
+
import logging
|
|
50
|
+
import time
|
|
51
|
+
import urllib.request
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from dataclasses import dataclass
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
|
|
56
|
+
from claude_swap import oauth
|
|
57
|
+
from claude_swap.locking import FileLock
|
|
58
|
+
from claude_swap.settings import atomic_write_json
|
|
59
|
+
|
|
60
|
+
_logger = logging.getLogger("claude-swap")
|
|
61
|
+
|
|
62
|
+
PROFILE_URL = "https://api.anthropic.com/api/oauth/profile"
|
|
63
|
+
PLAN_FILENAME = "subscription_plans.json"
|
|
64
|
+
|
|
65
|
+
# Plans change on a billing cadence, not a usage one. Six hours keeps a lapse
|
|
66
|
+
# visible the same day without adding meaningful traffic: one profile call per
|
|
67
|
+
# account four times a day.
|
|
68
|
+
PLAN_TTL_S = 6 * 3600
|
|
69
|
+
|
|
70
|
+
# After a failed read: at least this long, longer if the server says so. A
|
|
71
|
+
# Retry-After of 0 is real on this API (#220), so it cannot be the only floor.
|
|
72
|
+
FAILURE_RETRY_S = 15 * 60
|
|
73
|
+
# Ceiling on any wait, and the bound past which a stored retryAt is clock skew.
|
|
74
|
+
MAX_RETRY_S = 24 * 3600
|
|
75
|
+
|
|
76
|
+
FREE_TIER = "default_claude_ai"
|
|
77
|
+
|
|
78
|
+
# Used when a record carries no planDisplayName (the server sent none, or the
|
|
79
|
+
# record predates the name and is refetched on the next pass allowed to read
|
|
80
|
+
# it), and when the server's name is only a prefix of the table label ("Max"
|
|
81
|
+
# vs "Max 5x").
|
|
82
|
+
# Only values that have actually been observed. An unknown tier falls back to
|
|
83
|
+
# the raw string rather than a guessed label — a wrong "Pro" is worse than an
|
|
84
|
+
# honest "default_claude_pro".
|
|
85
|
+
_TIER_LABELS = {
|
|
86
|
+
"default_claude_ai": "Free",
|
|
87
|
+
"default_claude_max_5x": "Max 5x",
|
|
88
|
+
"default_claude_max_20x": "Max 20x",
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
# A seat on a Team or Enterprise organization is not a personal subscription,
|
|
92
|
+
# whatever rate tier the seat carries, so the organization type wins where it
|
|
93
|
+
# is known.
|
|
94
|
+
#
|
|
95
|
+
# ``claude_pro`` is the same story with a different label: a paying Pro
|
|
96
|
+
# subscription reports the *default* rate-limit bucket (``default_claude_ai``),
|
|
97
|
+
# which is also what a lapsed account falls back to, so the tier alone would
|
|
98
|
+
# print "Free" for a subscriber who is paying. The organization type is the
|
|
99
|
+
# field that still names the plan.
|
|
100
|
+
_ORG_TYPE_LABELS = {
|
|
101
|
+
"claude_team": "Team",
|
|
102
|
+
"claude_enterprise": "Enterprise",
|
|
103
|
+
"claude_pro": "Pro",
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
_KEPT_FIELDS = (
|
|
107
|
+
("organization_type", "organizationType"),
|
|
108
|
+
("billing_type", "billingType"),
|
|
109
|
+
("subscription_status", "subscriptionStatus"),
|
|
110
|
+
("plan_display_name", "planDisplayName"),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class PlanFetch:
|
|
116
|
+
"""One profile read. ``plan`` is None on any failure."""
|
|
117
|
+
|
|
118
|
+
plan: dict | None = None
|
|
119
|
+
account_uuid: str = ""
|
|
120
|
+
organization_uuid: str = ""
|
|
121
|
+
retry_after_s: float | None = None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def fetch_plan(access_token: str, timeout: float = 5.0) -> PlanFetch:
|
|
125
|
+
"""Read the plan fields of ``/api/oauth/profile``.
|
|
126
|
+
|
|
127
|
+
Requires a non-empty ``rate_limit_tier``, the field every label derives
|
|
128
|
+
from; a response without one is treated as no answer rather than as a plan
|
|
129
|
+
with nothing in it. Must not be called while a credential or config lock is
|
|
130
|
+
held, the same rule as every other network call here.
|
|
131
|
+
"""
|
|
132
|
+
req = urllib.request.Request(
|
|
133
|
+
PROFILE_URL,
|
|
134
|
+
headers={
|
|
135
|
+
"Authorization": f"Bearer {access_token}",
|
|
136
|
+
"Content-Type": "application/json",
|
|
137
|
+
"User-Agent": "claude-swap/1.0",
|
|
138
|
+
},
|
|
139
|
+
)
|
|
140
|
+
try:
|
|
141
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
142
|
+
data = json.loads(resp.read().decode())
|
|
143
|
+
except Exception as e: # noqa: BLE001 — display-only; never let it surface
|
|
144
|
+
_logger.debug("Plan fetch failed: %r", e)
|
|
145
|
+
_kind, retry_after_s = oauth._classify_usage_error(e)
|
|
146
|
+
return PlanFetch(retry_after_s=retry_after_s)
|
|
147
|
+
organization = data.get("organization") if isinstance(data, dict) else None
|
|
148
|
+
if not isinstance(organization, dict):
|
|
149
|
+
return PlanFetch()
|
|
150
|
+
tier = organization.get("rate_limit_tier")
|
|
151
|
+
if not isinstance(tier, str) or not tier:
|
|
152
|
+
return PlanFetch()
|
|
153
|
+
plan = {"tier": tier}
|
|
154
|
+
for source, key in _KEPT_FIELDS:
|
|
155
|
+
value = organization.get(source)
|
|
156
|
+
if isinstance(value, str) and value:
|
|
157
|
+
plan[key] = value
|
|
158
|
+
# Always present (None if unsent): is_due reads a missing key as an old record.
|
|
159
|
+
plan.setdefault("planDisplayName", None)
|
|
160
|
+
account = data.get("account")
|
|
161
|
+
account_uuid = account.get("uuid") if isinstance(account, dict) else None
|
|
162
|
+
organization_uuid = organization.get("uuid")
|
|
163
|
+
return PlanFetch(
|
|
164
|
+
plan=plan,
|
|
165
|
+
account_uuid=account_uuid if isinstance(account_uuid, str) else "",
|
|
166
|
+
organization_uuid=(
|
|
167
|
+
organization_uuid if isinstance(organization_uuid, str) else ""
|
|
168
|
+
),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def matches_slot(fetched: PlanFetch, account_uuid: str, org_uuid: str) -> bool:
|
|
173
|
+
"""Whether a read provably belongs to the slot it was made for.
|
|
174
|
+
|
|
175
|
+
Every UUID the slot records must match, and at least one must exist: a slot
|
|
176
|
+
recording neither cannot confirm anything, so it shows no plan rather than
|
|
177
|
+
one that may be another account's.
|
|
178
|
+
"""
|
|
179
|
+
expected = [
|
|
180
|
+
(recorded, seen)
|
|
181
|
+
for recorded, seen in (
|
|
182
|
+
(account_uuid, fetched.account_uuid),
|
|
183
|
+
(org_uuid, fetched.organization_uuid),
|
|
184
|
+
)
|
|
185
|
+
if recorded
|
|
186
|
+
]
|
|
187
|
+
return bool(expected) and all(recorded == seen for recorded, seen in expected)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def next_retry_at(now: float, retry_after_s: float | None) -> float:
|
|
191
|
+
"""When a failed read may be repeated."""
|
|
192
|
+
wait = max(FAILURE_RETRY_S, retry_after_s or 0.0)
|
|
193
|
+
return now + min(wait, MAX_RETRY_S)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def plan_label(plan: dict | None) -> str | None:
|
|
197
|
+
"""Human label: organization type where known, else the server's plan name,
|
|
198
|
+
else tier, else raw tier."""
|
|
199
|
+
if not plan:
|
|
200
|
+
return None
|
|
201
|
+
org_label = _ORG_TYPE_LABELS.get(plan.get("organizationType"))
|
|
202
|
+
if org_label:
|
|
203
|
+
return org_label
|
|
204
|
+
tier = plan.get("tier")
|
|
205
|
+
label = _TIER_LABELS.get(tier, tier)
|
|
206
|
+
# The server's name wins unless the table names the same plan more
|
|
207
|
+
# precisely ("Max" vs "Max 5x"); Ultra shares the Max 20x tier string.
|
|
208
|
+
name = plan.get("planDisplayName")
|
|
209
|
+
if (
|
|
210
|
+
isinstance(name, str)
|
|
211
|
+
and name
|
|
212
|
+
and not (isinstance(label, str) and label.startswith(name))
|
|
213
|
+
):
|
|
214
|
+
return name
|
|
215
|
+
return label
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def is_expired(plan: dict | None) -> bool:
|
|
219
|
+
"""A subscription that has lapsed: ``canceled`` AND back on the free tier."""
|
|
220
|
+
return (
|
|
221
|
+
bool(plan)
|
|
222
|
+
and plan.get("subscriptionStatus") == "canceled"
|
|
223
|
+
and plan.get("tier") == FREE_TIER
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def identity_key(email: str, org_uuid: str | None) -> str:
|
|
228
|
+
"""Store key. Identity, not slot number — ``swap``/``move`` renumber slots."""
|
|
229
|
+
return f"{email}\n{org_uuid or ''}"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def usable_access_token(credentials: str | None) -> str | None:
|
|
233
|
+
"""The access token in ``credentials`` if it is present and unexpired."""
|
|
234
|
+
if not credentials:
|
|
235
|
+
return None
|
|
236
|
+
blob = oauth.extract_oauth_data(credentials)
|
|
237
|
+
if not isinstance(blob, dict):
|
|
238
|
+
return None
|
|
239
|
+
token = blob.get("accessToken")
|
|
240
|
+
if not isinstance(token, str) or not token:
|
|
241
|
+
return None
|
|
242
|
+
if oauth.is_oauth_token_expired(blob.get("expiresAt")):
|
|
243
|
+
return None
|
|
244
|
+
return token
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def valid_record(record: object) -> bool:
|
|
248
|
+
return (
|
|
249
|
+
isinstance(record, dict)
|
|
250
|
+
and isinstance(record.get("plan"), dict)
|
|
251
|
+
and isinstance(record["plan"].get("tier"), str)
|
|
252
|
+
and isinstance(record.get("fetchedAt"), (int, float))
|
|
253
|
+
and not isinstance(record.get("fetchedAt"), bool)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _is_number(value: object) -> bool:
|
|
258
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def is_due(record: object, now: float, ttl: float = PLAN_TTL_S) -> bool:
|
|
262
|
+
"""Whether a record needs refreshing. A future stamp is clock skew: refresh.
|
|
263
|
+
|
|
264
|
+
A live ``retryAt`` holds the read back whatever the age of the plan; one
|
|
265
|
+
further out than any wait this module sets is skew and is ignored.
|
|
266
|
+
"""
|
|
267
|
+
if isinstance(record, dict):
|
|
268
|
+
retry_at = record.get("retryAt")
|
|
269
|
+
if _is_number(retry_at) and now < retry_at <= now + MAX_RETRY_S:
|
|
270
|
+
return False
|
|
271
|
+
if not valid_record(record):
|
|
272
|
+
return True
|
|
273
|
+
if "planDisplayName" not in record["plan"]: # stored before the name was kept
|
|
274
|
+
return True
|
|
275
|
+
fetched_at = record["fetchedAt"]
|
|
276
|
+
return fetched_at > now or now - fetched_at >= ttl
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _past_stamp(record: dict, key: str, now: float) -> float | None:
|
|
280
|
+
"""A stored stamp that may take part in ordering: a number no later than
|
|
281
|
+
``now``. A stamp ahead of the clock was written before the clock was set
|
|
282
|
+
back; it says nothing about recency, so it is treated as absent."""
|
|
283
|
+
value = record.get(key)
|
|
284
|
+
if _is_number(value) and value <= now:
|
|
285
|
+
return value
|
|
286
|
+
return None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _merge(existing: object, update: dict, now: float) -> dict:
|
|
290
|
+
"""One key of a save. The newer reading wins, whichever process lands last.
|
|
291
|
+
|
|
292
|
+
``update`` is a success (``plan``, ``fetchedAt``) or a failure (``retryAt``,
|
|
293
|
+
``attemptedAt``). Both are stamped before their request went out, so an
|
|
294
|
+
answer that was slow to arrive cannot pass for a newer one, and an older
|
|
295
|
+
failure cannot shorten the wait a newer one set. A stored stamp ahead of
|
|
296
|
+
``now`` is clock skew and never outranks the update: ``is_due`` asks for a
|
|
297
|
+
fresh read of such a record, and that read has to be allowed to land, or
|
|
298
|
+
the old label would stand while the endpoint was asked on every pass.
|
|
299
|
+
"""
|
|
300
|
+
current = existing if isinstance(existing, dict) else {}
|
|
301
|
+
fetched = _past_stamp(current, "fetchedAt", now) if valid_record(current) else None
|
|
302
|
+
attempted = _past_stamp(current, "attemptedAt", now)
|
|
303
|
+
if "plan" in update:
|
|
304
|
+
if fetched is not None and fetched > update["fetchedAt"]:
|
|
305
|
+
return current
|
|
306
|
+
if attempted is not None and attempted > update["fetchedAt"]:
|
|
307
|
+
return {
|
|
308
|
+
**update,
|
|
309
|
+
"retryAt": current.get("retryAt"),
|
|
310
|
+
"attemptedAt": attempted,
|
|
311
|
+
}
|
|
312
|
+
return update
|
|
313
|
+
if fetched is not None and fetched >= update["attemptedAt"]:
|
|
314
|
+
return current
|
|
315
|
+
if attempted is not None and attempted > update["attemptedAt"]:
|
|
316
|
+
return current
|
|
317
|
+
return {**current, **update}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class PlanStore:
|
|
321
|
+
"""``subscription_plans.json``: ``{identity_key: record}``.
|
|
322
|
+
|
|
323
|
+
``list``, ``watch`` and the auto view may refresh at once. ``save`` holds a
|
|
324
|
+
lock across its read/merge/write, and only that: the network calls happen
|
|
325
|
+
before it, so the lock is short and never waits on a slow response.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
def __init__(self, path: Path, clock: Callable[[], float] = time.time):
|
|
329
|
+
self.path = path
|
|
330
|
+
self.clock = clock
|
|
331
|
+
|
|
332
|
+
def load(self) -> dict[str, dict]:
|
|
333
|
+
try:
|
|
334
|
+
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
|
335
|
+
except (OSError, ValueError, UnicodeDecodeError):
|
|
336
|
+
return {}
|
|
337
|
+
return raw if isinstance(raw, dict) else {}
|
|
338
|
+
|
|
339
|
+
def save(self, updates: dict[str, dict]) -> None:
|
|
340
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
341
|
+
with FileLock(self.path.with_name(self.path.name + ".lock")):
|
|
342
|
+
# Read the clock under the lock: a record another writer landed
|
|
343
|
+
# while this one waited carries a stamp later than a clock read
|
|
344
|
+
# before the wait, and would be mistaken for skew and overwritten.
|
|
345
|
+
now = self.clock()
|
|
346
|
+
merged = self.load()
|
|
347
|
+
for key, update in updates.items():
|
|
348
|
+
merged[key] = _merge(merged.get(key), update, now)
|
|
349
|
+
atomic_write_json(self.path, merged)
|