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,360 @@
|
|
|
1
|
+
"""One-time, run-once data migrations for claude-swap.
|
|
2
|
+
|
|
3
|
+
A small, boring home for compatibility migrations so they don't pollute the
|
|
4
|
+
core switch/read/write flow in :mod:`claude_swap.switcher`. Each migration:
|
|
5
|
+
|
|
6
|
+
- is **idempotent** and **self-guarded** (safe to run twice, safe even if the
|
|
7
|
+
state file is missing or corrupt),
|
|
8
|
+
- returns ``True`` when it *completed* (runner records it as applied),
|
|
9
|
+
- returns ``False`` when it was *skipped / not applicable* (runner records
|
|
10
|
+
nothing, so a later-restored backup can still trigger it),
|
|
11
|
+
- raises :class:`~claude_swap.exceptions.MigrationIncomplete` (or any other
|
|
12
|
+
exception) when it *partially failed* — the runner logs it and leaves it
|
|
13
|
+
unmarked so the next run retries.
|
|
14
|
+
|
|
15
|
+
Applied migrations are tracked in ``<backup_dir>/.migrations.json``:
|
|
16
|
+
|
|
17
|
+
{"version": 1, "applied": {"macos_keyring_to_security": "<iso-timestamp>"}}
|
|
18
|
+
|
|
19
|
+
Run once at switcher construction (see ``ClaudeAccountSwitcher.__init__``);
|
|
20
|
+
after the state file records a migration it short-circuits with a single tiny
|
|
21
|
+
file read and never touches the source backend again.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import sys
|
|
28
|
+
from collections import Counter
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import TYPE_CHECKING, Callable
|
|
31
|
+
|
|
32
|
+
from claude_swap import macos_keychain
|
|
33
|
+
from claude_swap.exceptions import MigrationIncomplete
|
|
34
|
+
from claude_swap.fsutil import atomic_write_text
|
|
35
|
+
from claude_swap.models import Platform, get_timestamp
|
|
36
|
+
from claude_swap.switcher import KEYRING_SERVICE
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from claude_swap.switcher import ClaudeAccountSwitcher
|
|
40
|
+
|
|
41
|
+
STATE_FILENAME = ".migrations.json"
|
|
42
|
+
STATE_VERSION = 1
|
|
43
|
+
|
|
44
|
+
# How long a legacy read waits for a person to answer the Keychain permission
|
|
45
|
+
# window: time to type the login password and click. See
|
|
46
|
+
# ``migrate_macos_keyring_to_security``.
|
|
47
|
+
_PROMPT_WAIT = 60.0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
# State file
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _state_path(switcher: "ClaudeAccountSwitcher") -> Path:
|
|
56
|
+
return switcher.backup_dir / STATE_FILENAME
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _load_applied(switcher: "ClaudeAccountSwitcher") -> dict:
|
|
60
|
+
"""Return the ``{migration_id: timestamp}`` map; {} if missing or corrupt.
|
|
61
|
+
|
|
62
|
+
A missing or unparseable state file is treated as "nothing applied" so a
|
|
63
|
+
corrupt file can never permanently block a migration.
|
|
64
|
+
"""
|
|
65
|
+
path = _state_path(switcher)
|
|
66
|
+
if not path.exists():
|
|
67
|
+
return {}
|
|
68
|
+
try:
|
|
69
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
70
|
+
except (json.JSONDecodeError, OSError, UnicodeDecodeError):
|
|
71
|
+
return {}
|
|
72
|
+
applied = data.get("applied") if isinstance(data, dict) else None
|
|
73
|
+
return applied if isinstance(applied, dict) else {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _mark_applied(switcher: "ClaudeAccountSwitcher", migration_id: str) -> None:
|
|
77
|
+
"""Record ``migration_id`` as applied, written atomically.
|
|
78
|
+
|
|
79
|
+
Preserves any previously-recorded migrations. Published through the shared
|
|
80
|
+
``fsutil.atomic_write_text`` (0600 temp beside the target, rename), like
|
|
81
|
+
every other local state file; this one holds no secrets, the mode simply
|
|
82
|
+
matches.
|
|
83
|
+
"""
|
|
84
|
+
path = _state_path(switcher)
|
|
85
|
+
applied = _load_applied(switcher)
|
|
86
|
+
applied[migration_id] = get_timestamp()
|
|
87
|
+
content = json.dumps({"version": STATE_VERSION, "applied": applied}, indent=2)
|
|
88
|
+
atomic_write_text(path, content)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------------------
|
|
92
|
+
# Migrations
|
|
93
|
+
# ---------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def migrate_macos_keyring_to_security(switcher: "ClaudeAccountSwitcher") -> bool:
|
|
97
|
+
"""Move macOS backup credentials from the legacy ``keyring`` service to the
|
|
98
|
+
``security`` service.
|
|
99
|
+
|
|
100
|
+
macOS stores per-account backup credentials in the Keychain via the
|
|
101
|
+
``security`` CLI under ``SECURITY_SERVICE`` (see
|
|
102
|
+
:mod:`claude_swap.macos_keychain`). Versions before 0.19 stored them through
|
|
103
|
+
the third-party ``keyring`` library under ``KEYRING_SERVICE`` instead. Source
|
|
104
|
+
and destination are *different* services, so old and new items coexist during
|
|
105
|
+
a safe write → verify → delete (no risk window).
|
|
106
|
+
|
|
107
|
+
The legacy items are read and deleted through ``security`` too (the
|
|
108
|
+
``keyring`` library is no longer a dependency). Reading the secret of an item
|
|
109
|
+
another app created goes through the item's ACL and may prompt once; deleting
|
|
110
|
+
an item does not consult the ACL, so the cleanup never prompts. A failed
|
|
111
|
+
delete leaves a harmless orphan behind (logged; ``purge`` sweeps it up).
|
|
112
|
+
|
|
113
|
+
The prompt asks for the login password, and under the wrapper's default
|
|
114
|
+
bound the read's ``security`` process is usually killed before a person has
|
|
115
|
+
answered: the window closes with it on macOS 15.7.7 (issue #589) and stays
|
|
116
|
+
open with no reader left on 27.2.1 (measured). When a person is running the
|
|
117
|
+
command (``switcher.interactive``) and an attribute-only lookup finds the
|
|
118
|
+
legacy item, the read is announced on stderr and waits ``_PROMPT_WAIT``
|
|
119
|
+
instead. The lookup only chooses the bound: an item it does
|
|
120
|
+
not find is still read, under the default bound, and that read decides
|
|
121
|
+
whether the item is absent. A prompt left unanswered ends the attempt, so an
|
|
122
|
+
unattended terminal waits once per run, not once per account; accounts
|
|
123
|
+
already moved stay moved and the rest retry on the next run. Every other
|
|
124
|
+
caller keeps the default bound on every read.
|
|
125
|
+
|
|
126
|
+
Returns ``True`` (completed) on macOS once every account is accounted for
|
|
127
|
+
(including the benign "already migrated / nothing to do" cases); ``False``
|
|
128
|
+
(skip) on non-macOS or when there's no readable sequence yet. Raises
|
|
129
|
+
:class:`MigrationIncomplete` if any account could not be safely relocated, so
|
|
130
|
+
the runner retries on the next launch rather than marking it done.
|
|
131
|
+
"""
|
|
132
|
+
if switcher.platform != Platform.MACOS:
|
|
133
|
+
return False
|
|
134
|
+
if not switcher.sequence_file.exists():
|
|
135
|
+
return False # No managed accounts yet — let a later restore migrate.
|
|
136
|
+
|
|
137
|
+
data = switcher._get_sequence_data()
|
|
138
|
+
if data is None:
|
|
139
|
+
# sequence.json exists but is corrupt. Never mark applied: a user who
|
|
140
|
+
# repairs/restores it must still get the migration.
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
accounts = data.get("accounts", {})
|
|
144
|
+
if not accounts:
|
|
145
|
+
return True # Readable sequence, nothing to migrate → done.
|
|
146
|
+
|
|
147
|
+
# Pre-check: anything already in the new security service is done. New installs
|
|
148
|
+
# and already-migrated users have every account here, so they never touch the
|
|
149
|
+
# legacy service at all. Only the still-missing accounts proceed below; on a
|
|
150
|
+
# retry this also narrows work to the accounts that actually failed last time.
|
|
151
|
+
#
|
|
152
|
+
# Read the security service *directly* (not the transparent .enc-wins backup
|
|
153
|
+
# methods): this migration's job is the Keychain specifically, so a fallback
|
|
154
|
+
# .enc must not be mistaken for "already migrated". A down Keychain here is not
|
|
155
|
+
# "nothing to migrate" — defer and retry rather than skip real entries.
|
|
156
|
+
try:
|
|
157
|
+
pending = {
|
|
158
|
+
account_num: info
|
|
159
|
+
for account_num, info in accounts.items()
|
|
160
|
+
if not switcher._kc_read_backup(account_num, info.get("email", ""))
|
|
161
|
+
}
|
|
162
|
+
except macos_keychain.KEYCHAIN_ERRORS as e:
|
|
163
|
+
# Keychain unusable (locked/denied/missing) — defer, don't skip real
|
|
164
|
+
# entries. A programming error is NOT caught here; it propagates.
|
|
165
|
+
raise MigrationIncomplete(
|
|
166
|
+
f"Keychain unavailable, deferring macOS keyring migration: {e}"
|
|
167
|
+
) from e
|
|
168
|
+
if not pending:
|
|
169
|
+
return True # All accounts already in the security service.
|
|
170
|
+
|
|
171
|
+
# account-None-{email} maps to a slot only when its email is unique.
|
|
172
|
+
email_counts = Counter(info.get("email", "") for info in accounts.values())
|
|
173
|
+
|
|
174
|
+
announced = False
|
|
175
|
+
unanswered = False # a prompt went unanswered: stop reading for this run
|
|
176
|
+
timed_out = False
|
|
177
|
+
|
|
178
|
+
def _read_old(username: str) -> str | None:
|
|
179
|
+
"""Read a legacy ``KEYRING_SERVICE`` item: its value, ``""`` if absent,
|
|
180
|
+
``None`` if the read failed (logged). A failed read (e.g. a locked
|
|
181
|
+
Keychain) is a real failure, never "nothing to migrate"."""
|
|
182
|
+
nonlocal announced, unanswered, timed_out
|
|
183
|
+
prompted = switcher.interactive and macos_keychain.item_exists(
|
|
184
|
+
KEYRING_SERVICE, username
|
|
185
|
+
)
|
|
186
|
+
try:
|
|
187
|
+
if prompted:
|
|
188
|
+
if not announced:
|
|
189
|
+
announced = True
|
|
190
|
+
print(
|
|
191
|
+
"claude-swap: moving saved logins from an older version. "
|
|
192
|
+
"macOS may ask for your login password for each one: "
|
|
193
|
+
'enter it and choose "Always Allow" (waiting up to '
|
|
194
|
+
f"{_PROMPT_WAIT:.0f} s)",
|
|
195
|
+
file=sys.stderr,
|
|
196
|
+
)
|
|
197
|
+
value = macos_keychain.get_password(
|
|
198
|
+
KEYRING_SERVICE, username, timeout=_PROMPT_WAIT
|
|
199
|
+
)
|
|
200
|
+
else:
|
|
201
|
+
value = macos_keychain.get_password(KEYRING_SERVICE, username)
|
|
202
|
+
except Exception as e: # noqa: BLE001
|
|
203
|
+
switcher._logger.warning(
|
|
204
|
+
f"macos_keyring_to_security: read of {username} failed: {e}"
|
|
205
|
+
)
|
|
206
|
+
if isinstance(e, macos_keychain.KeychainTimeout):
|
|
207
|
+
timed_out = True
|
|
208
|
+
if prompted:
|
|
209
|
+
unanswered = True
|
|
210
|
+
return None
|
|
211
|
+
return value or ""
|
|
212
|
+
|
|
213
|
+
def _delete_old(username: str) -> None:
|
|
214
|
+
"""Best-effort removal of a legacy ``KEYRING_SERVICE`` item. Never raises:
|
|
215
|
+
the copy is already verified, so a leftover is harmless cruft that
|
|
216
|
+
``purge`` sweeps up. An absent item (rc 44) counts as removed."""
|
|
217
|
+
try:
|
|
218
|
+
macos_keychain.delete_password(KEYRING_SERVICE, username)
|
|
219
|
+
except Exception as e: # noqa: BLE001 - best effort
|
|
220
|
+
switcher._logger.warning(
|
|
221
|
+
f"macos_keyring_to_security: legacy keyring entry {username} was "
|
|
222
|
+
f"left behind (delete failed: {e}); harmless — remove manually or "
|
|
223
|
+
"via purge"
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
migrated = 0
|
|
227
|
+
failed = 0
|
|
228
|
+
|
|
229
|
+
for account_num, info in pending.items():
|
|
230
|
+
if unanswered:
|
|
231
|
+
failed += 1 # not attempted; the next run retries it
|
|
232
|
+
continue
|
|
233
|
+
|
|
234
|
+
email = info.get("email", "")
|
|
235
|
+
canonical = f"account-{account_num}-{email}"
|
|
236
|
+
none_user = f"account-None-{email}"
|
|
237
|
+
|
|
238
|
+
# --- pick a source (canonical wins) -------------------------------
|
|
239
|
+
creds = _read_old(canonical)
|
|
240
|
+
if creds is None:
|
|
241
|
+
failed += 1
|
|
242
|
+
continue
|
|
243
|
+
|
|
244
|
+
source_username = canonical
|
|
245
|
+
if not creds and str(account_num) != "None" and email_counts[email] == 1:
|
|
246
|
+
creds = _read_old(none_user)
|
|
247
|
+
if creds is None:
|
|
248
|
+
failed += 1
|
|
249
|
+
continue
|
|
250
|
+
if creds:
|
|
251
|
+
source_username = none_user
|
|
252
|
+
|
|
253
|
+
if not creds:
|
|
254
|
+
# Nothing in the legacy service for this slot (e.g. added on the new
|
|
255
|
+
# version, or an ambiguous account-None we won't touch). Benign — not
|
|
256
|
+
# a failure.
|
|
257
|
+
continue
|
|
258
|
+
|
|
259
|
+
# --- write + verify before deleting the source ------------------------
|
|
260
|
+
# Keychain-only helpers: this migration targets the security service, so
|
|
261
|
+
# it must not be diverted to .enc files by the transparent backup methods.
|
|
262
|
+
try:
|
|
263
|
+
switcher._kc_write_backup(account_num, email, creds)
|
|
264
|
+
readback = switcher._kc_read_backup(account_num, email)
|
|
265
|
+
except Exception as e: # noqa: BLE001
|
|
266
|
+
switcher._logger.warning(
|
|
267
|
+
f"macos_keyring_to_security: write/read-back for {canonical} failed: {e}"
|
|
268
|
+
)
|
|
269
|
+
# A partial/garbage security item must not shadow the still-intact
|
|
270
|
+
# legacy entry. Drop it; the retry rewrites it.
|
|
271
|
+
switcher._delete_backup_keychain_quiet(account_num, email)
|
|
272
|
+
failed += 1
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
if readback != creds:
|
|
276
|
+
switcher._logger.warning(
|
|
277
|
+
f"macos_keyring_to_security: read-back mismatch for {canonical}; "
|
|
278
|
+
"discarding the security item and leaving the legacy entry in place"
|
|
279
|
+
)
|
|
280
|
+
switcher._delete_backup_keychain_quiet(account_num, email)
|
|
281
|
+
failed += 1
|
|
282
|
+
continue
|
|
283
|
+
|
|
284
|
+
# Data is safely in the security service now → remove the legacy source
|
|
285
|
+
# and, when the email is unique, its stale account-None duplicate. An
|
|
286
|
+
# ambiguous account-None (shared email) is left alone; purge sweeps it.
|
|
287
|
+
_delete_old(source_username)
|
|
288
|
+
if (
|
|
289
|
+
source_username != none_user
|
|
290
|
+
and str(account_num) != "None"
|
|
291
|
+
and email_counts[email] == 1
|
|
292
|
+
):
|
|
293
|
+
_delete_old(none_user)
|
|
294
|
+
migrated += 1
|
|
295
|
+
|
|
296
|
+
if migrated:
|
|
297
|
+
print(
|
|
298
|
+
f"claude-swap: migrated {migrated} macOS credential(s) from the legacy "
|
|
299
|
+
"keyring service into the Keychain via security",
|
|
300
|
+
file=sys.stderr,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
if failed:
|
|
304
|
+
hint = (
|
|
305
|
+
". If macOS showed a Keychain permission window, run `cswap list` in a "
|
|
306
|
+
'terminal and approve it (login password, then "Always Allow")'
|
|
307
|
+
if timed_out
|
|
308
|
+
else ""
|
|
309
|
+
)
|
|
310
|
+
raise MigrationIncomplete(
|
|
311
|
+
f"{failed} account(s) could not be migrated to the security service; "
|
|
312
|
+
f"will retry on next run{hint}"
|
|
313
|
+
)
|
|
314
|
+
return True
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# Registry of (id, fn). Order matters if migrations ever depend on each other.
|
|
318
|
+
# Retired ids stay valid in an old state file (``windows_keyring_to_files``, the
|
|
319
|
+
# Credential Manager → files move that needed the keyring library) and are simply
|
|
320
|
+
# carried along.
|
|
321
|
+
MIGRATIONS: list[tuple[str, Callable[["ClaudeAccountSwitcher"], bool]]] = [
|
|
322
|
+
("macos_keyring_to_security", migrate_macos_keyring_to_security),
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------------------------------------------------------------------------
|
|
327
|
+
# Runner
|
|
328
|
+
# ---------------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def run_migrations(switcher: "ClaudeAccountSwitcher") -> None:
|
|
332
|
+
"""Run any not-yet-applied migrations. Never raises.
|
|
333
|
+
|
|
334
|
+
A no-op on fresh installs (backup dir not yet materialized — preserves the
|
|
335
|
+
lazy-dir invariant) and once the state file records every migration. A
|
|
336
|
+
failing migration is logged and left unmarked so it retries next run; it
|
|
337
|
+
must never abort switcher construction.
|
|
338
|
+
"""
|
|
339
|
+
if not switcher.backup_dir.exists():
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
applied = _load_applied(switcher)
|
|
343
|
+
for migration_id, fn in MIGRATIONS:
|
|
344
|
+
if migration_id in applied:
|
|
345
|
+
continue
|
|
346
|
+
try:
|
|
347
|
+
completed = fn(switcher)
|
|
348
|
+
except Exception as e: # noqa: BLE001 - migrations must never brick the tool
|
|
349
|
+
switcher._logger.warning(
|
|
350
|
+
f"Migration {migration_id} did not complete (will retry): {e}"
|
|
351
|
+
)
|
|
352
|
+
continue
|
|
353
|
+
if completed:
|
|
354
|
+
try:
|
|
355
|
+
_mark_applied(switcher, migration_id)
|
|
356
|
+
except Exception as e: # noqa: BLE001
|
|
357
|
+
switcher._logger.warning(
|
|
358
|
+
f"Migration {migration_id} ran but recording it failed "
|
|
359
|
+
f"(will re-run next time): {e}"
|
|
360
|
+
)
|
claude_swap/models.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Data models for Claude Swap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from enum import Enum, auto
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
from claude_swap.fsutil import atomic_write_text
|
|
18
|
+
from claude_swap.usage_store import UsageEntry
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from claude_swap.switcher import ClaudeAccountSwitcher
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
#: Alias validation: letters/digits/-/_/., non-empty, not purely digits (so an
|
|
25
|
+
#: alias can never collide with a slot number in _resolve_account_identifier),
|
|
26
|
+
#: and not leading with '-' (argparse would treat it as an option, making the
|
|
27
|
+
#: alias impossible to pass back into any command once set).
|
|
28
|
+
_ALIAS_RE = re.compile(r"^[a-z0-9_.-]+$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def normalize_alias(name: str) -> str:
|
|
32
|
+
"""Lowercase and validate a proposed alias; raise ValueError if invalid.
|
|
33
|
+
|
|
34
|
+
Shared by the CLI (``cswap alias``), ``cswap add --alias``, and import
|
|
35
|
+
validation so every path enforces identical rules.
|
|
36
|
+
"""
|
|
37
|
+
normalized = name.strip().lower()
|
|
38
|
+
if not normalized:
|
|
39
|
+
raise ValueError("alias cannot be empty")
|
|
40
|
+
if normalized.isdigit():
|
|
41
|
+
raise ValueError(f"alias '{name}' cannot be purely numeric (reserved for slot numbers)")
|
|
42
|
+
if normalized.startswith("-"):
|
|
43
|
+
raise ValueError(
|
|
44
|
+
f"alias '{name}' cannot start with '-' (would be read as a command flag)"
|
|
45
|
+
)
|
|
46
|
+
if not _ALIAS_RE.match(normalized):
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"alias '{name}' may only contain letters, digits, '-', '_', and '.'"
|
|
49
|
+
)
|
|
50
|
+
return normalized
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
#: Per-account switch-away threshold bounds, in binding-window utilization
|
|
54
|
+
#: percent. Mirrors ``SETTING_SPECS["autoswitch.threshold"]``, written as
|
|
55
|
+
#: literals rather than imported: ``models`` is a leaf and must not import
|
|
56
|
+
#: ``settings``. The two are asserted equal in
|
|
57
|
+
#: ``tests/test_account_policy_values.py`` so they cannot drift apart.
|
|
58
|
+
ACCOUNT_THRESHOLD_MIN = 40.0
|
|
59
|
+
ACCOUNT_THRESHOLD_MAX = 99.9
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def normalize_account_threshold(value: object) -> float:
|
|
63
|
+
"""Validate a per-account switch-away threshold; raise ValueError if invalid.
|
|
64
|
+
|
|
65
|
+
Strict, in the manner of ``settings.parse_setting_value`` and unlike the
|
|
66
|
+
forgiving clamp applied when *reading* a record: a user who types 150 learns
|
|
67
|
+
about it at set time rather than by watching the account never switch away.
|
|
68
|
+
This is the single write-boundary validator for the value — the CLI verb,
|
|
69
|
+
the store setter, and any future UI all route through it.
|
|
70
|
+
|
|
71
|
+
Accepts ``int``, ``float``, and numeric ``str`` (the CLI hands over argv
|
|
72
|
+
strings). Rejects ``bool`` explicitly: ``True`` is an ``int`` in Python and
|
|
73
|
+
would otherwise normalize to 1.0, failing the range test for the wrong
|
|
74
|
+
reason.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
value: The proposed threshold.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
The threshold as a ``float`` in ``[ACCOUNT_THRESHOLD_MIN,
|
|
81
|
+
ACCOUNT_THRESHOLD_MAX]``.
|
|
82
|
+
|
|
83
|
+
Raises:
|
|
84
|
+
ValueError: If the value is not numeric, is NaN or infinite, or falls
|
|
85
|
+
outside the valid range. The message always names the range.
|
|
86
|
+
"""
|
|
87
|
+
range_text = (
|
|
88
|
+
f"must be between {ACCOUNT_THRESHOLD_MIN:g} and {ACCOUNT_THRESHOLD_MAX:g}"
|
|
89
|
+
)
|
|
90
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
|
|
91
|
+
raise ValueError(f"threshold {range_text}, got {value!r}")
|
|
92
|
+
if isinstance(value, str):
|
|
93
|
+
try:
|
|
94
|
+
pct = float(value.strip())
|
|
95
|
+
except ValueError:
|
|
96
|
+
raise ValueError(f"threshold {range_text}, got {value!r}") from None
|
|
97
|
+
else:
|
|
98
|
+
pct = float(value)
|
|
99
|
+
# NaN fails every comparison and infinity passes the lower bound, so both
|
|
100
|
+
# are rejected by name rather than left to the range test to catch by luck.
|
|
101
|
+
if math.isnan(pct) or math.isinf(pct):
|
|
102
|
+
raise ValueError(f"threshold {range_text}, got {value!r}")
|
|
103
|
+
if not ACCOUNT_THRESHOLD_MIN <= pct <= ACCOUNT_THRESHOLD_MAX:
|
|
104
|
+
raise ValueError(f"threshold {range_text}, got {pct:g}")
|
|
105
|
+
return pct
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
ACCOUNT_PRIORITY_MAX = 1000
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def normalize_account_priority(value: object) -> int:
|
|
112
|
+
"""Validate a priority tier. Higher numbers are preferred; zero is default."""
|
|
113
|
+
message = f"priority must be an integer between 0 and {ACCOUNT_PRIORITY_MAX}"
|
|
114
|
+
if isinstance(value, str):
|
|
115
|
+
value = value.strip()
|
|
116
|
+
if not value.isascii() or not value.isdecimal():
|
|
117
|
+
raise ValueError(message)
|
|
118
|
+
# Avoid converting an arbitrarily long hand-edited integer.
|
|
119
|
+
value = value.lstrip("0") or "0"
|
|
120
|
+
if len(value) > len(str(ACCOUNT_PRIORITY_MAX)):
|
|
121
|
+
raise ValueError(message)
|
|
122
|
+
value = int(value)
|
|
123
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
124
|
+
raise ValueError(message)
|
|
125
|
+
if not 0 <= value <= ACCOUNT_PRIORITY_MAX:
|
|
126
|
+
raise ValueError(message)
|
|
127
|
+
return value
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True)
|
|
131
|
+
class AccountPolicy:
|
|
132
|
+
"""Per-account auto-switch overrides, stored in the sequence record.
|
|
133
|
+
|
|
134
|
+
Defaults preserve existing behavior. Priority is read only by the
|
|
135
|
+
opt-in ``priority-consume-first`` strategy.
|
|
136
|
+
|
|
137
|
+
``threshold``
|
|
138
|
+
This account's own switch-away line, in binding-window utilization
|
|
139
|
+
percent. ``None`` inherits ``autoswitch.threshold``. Reserving headroom
|
|
140
|
+
on one shared account no longer means taxing the whole fleet with a
|
|
141
|
+
global line set to the strictest member's.
|
|
142
|
+
|
|
143
|
+
Frozen because ``AccountSnapshot`` is frozen — a mutable member would
|
|
144
|
+
silently break that guarantee for the whole row.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
threshold: float | None = None
|
|
148
|
+
priority: int = 0
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Platform(Enum):
|
|
152
|
+
"""Supported platforms."""
|
|
153
|
+
|
|
154
|
+
MACOS = auto()
|
|
155
|
+
LINUX = auto()
|
|
156
|
+
WSL = auto()
|
|
157
|
+
WINDOWS = auto()
|
|
158
|
+
UNKNOWN = auto()
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def detect(cls) -> Platform:
|
|
162
|
+
"""Detect current platform.
|
|
163
|
+
|
|
164
|
+
Uses sys.platform rather than platform.system() because the latter
|
|
165
|
+
calls platform.uname() on Windows, which runs a WMI query that can
|
|
166
|
+
hang indefinitely when the WMI service is slow or unresponsive.
|
|
167
|
+
"""
|
|
168
|
+
if sys.platform == "darwin":
|
|
169
|
+
return cls.MACOS
|
|
170
|
+
elif sys.platform == "win32":
|
|
171
|
+
return cls.WINDOWS
|
|
172
|
+
elif sys.platform.startswith("linux"):
|
|
173
|
+
if os.environ.get("WSL_DISTRO_NAME"):
|
|
174
|
+
return cls.WSL
|
|
175
|
+
return cls.LINUX
|
|
176
|
+
return cls.UNKNOWN
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass
|
|
180
|
+
class AccountInfo:
|
|
181
|
+
"""Information about a managed account."""
|
|
182
|
+
|
|
183
|
+
email: str
|
|
184
|
+
uuid: str
|
|
185
|
+
organization_uuid: str
|
|
186
|
+
organization_name: str
|
|
187
|
+
added: str
|
|
188
|
+
number: int
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def is_organization(self) -> bool:
|
|
192
|
+
"""Whether this is an organization account."""
|
|
193
|
+
return bool(self.organization_uuid)
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def display_label(self) -> str:
|
|
197
|
+
"""Display label: 'email [OrgName]' or 'email [personal]'."""
|
|
198
|
+
tag = self.organization_name if self.organization_name else "personal"
|
|
199
|
+
return f"{self.email} [{tag}]"
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def from_dict(cls, number: int, data: dict) -> AccountInfo:
|
|
203
|
+
"""Create AccountInfo from dictionary."""
|
|
204
|
+
return cls(
|
|
205
|
+
email=data.get("email", ""),
|
|
206
|
+
uuid=data.get("uuid", ""),
|
|
207
|
+
organization_uuid=data.get("organizationUuid", "") or "",
|
|
208
|
+
organization_name=data.get("organizationName", "") or "",
|
|
209
|
+
added=data.get("added", ""),
|
|
210
|
+
number=number,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def to_dict(self) -> dict:
|
|
214
|
+
"""Convert to dictionary for JSON serialization."""
|
|
215
|
+
return {
|
|
216
|
+
"email": self.email,
|
|
217
|
+
"uuid": self.uuid,
|
|
218
|
+
"organizationUuid": self.organization_uuid,
|
|
219
|
+
"organizationName": self.organization_name,
|
|
220
|
+
"added": self.added,
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def org_tag_shown(mode: str, email: str, emails: Sequence[str]) -> bool:
|
|
225
|
+
"""Whether a per-account listing draws ``email``'s org tag under ``ui.orgTag``.
|
|
226
|
+
|
|
227
|
+
``on`` always, ``off`` never, ``auto`` only when another managed account
|
|
228
|
+
(``emails`` lists every one, ``email`` included) has the same email.
|
|
229
|
+
"""
|
|
230
|
+
return mode == "on" or (mode == "auto" and emails.count(email) > 1)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass(frozen=True)
|
|
234
|
+
class AccountSnapshot:
|
|
235
|
+
"""One managed account as seen by interactive UIs (the TUI).
|
|
236
|
+
|
|
237
|
+
``usage`` is the store-backed :class:`UsageEntry` read model; display
|
|
238
|
+
code reads ``usage.last_good``/``age_s`` directly (may show old data,
|
|
239
|
+
annotated with its age), while ``usage.sentinel`` carries derived states
|
|
240
|
+
("api key", "token expired", ...) that replace the bars entirely.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
number: str
|
|
244
|
+
email: str
|
|
245
|
+
org_name: str
|
|
246
|
+
org_uuid: str
|
|
247
|
+
is_active: bool
|
|
248
|
+
kind: str # "oauth" | "api_key"
|
|
249
|
+
switchable: bool
|
|
250
|
+
usage: UsageEntry
|
|
251
|
+
alias: str = ""
|
|
252
|
+
disabled: bool = False # held out of auto-rotation (still a valid explicit target)
|
|
253
|
+
#: Per-account auto-switch overrides. Appended last and defaulted, so every
|
|
254
|
+
#: pre-existing construction site keeps working and yields the default.
|
|
255
|
+
policy: AccountPolicy = AccountPolicy()
|
|
256
|
+
#: Stored subscription plan record (``subscription.PlanStore`` shape), or
|
|
257
|
+
#: None for a slot whose plan has never been fetched. Defaulted for the
|
|
258
|
+
#: same reason as ``policy``.
|
|
259
|
+
subscription_plan: dict | None = None
|
|
260
|
+
# Stored refresh token's expiry (epoch seconds), or None when missing/
|
|
261
|
+
# unreadable; see oauth.login_expires_at_epoch. Feeds the "re-login in
|
|
262
|
+
# 5d 12h" note every account view shows while the login is due.
|
|
263
|
+
login_expires_at: float | None = None
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def display_tag(self) -> str:
|
|
267
|
+
"""Org tag for display: the org name, or 'personal'."""
|
|
268
|
+
return self.org_name if self.org_name else "personal"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@dataclass(frozen=True)
|
|
272
|
+
class AccountsSnapshot:
|
|
273
|
+
"""Coherent one-pass view of every managed account.
|
|
274
|
+
|
|
275
|
+
Produced by ``ClaudeAccountSwitcher.accounts_snapshot``: metadata, active
|
|
276
|
+
detection, and usage entries all come from the same collect pass, so a
|
|
277
|
+
consumer never sees an account list and usage table that disagree.
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
active_number: str | None
|
|
281
|
+
accounts: tuple[AccountSnapshot, ...]
|
|
282
|
+
taken_at: float
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@dataclass
|
|
286
|
+
class SwitchTransaction:
|
|
287
|
+
"""Represents a switch operation that can be rolled back."""
|
|
288
|
+
|
|
289
|
+
original_credentials: str
|
|
290
|
+
original_config: str
|
|
291
|
+
original_account_num: str
|
|
292
|
+
original_email: str
|
|
293
|
+
config_path: Path
|
|
294
|
+
completed_steps: list[str] = field(default_factory=list)
|
|
295
|
+
|
|
296
|
+
def record_step(self, step: str) -> None:
|
|
297
|
+
"""Record a completed step."""
|
|
298
|
+
self.completed_steps.append(step)
|
|
299
|
+
|
|
300
|
+
def rollback(self, switcher: ClaudeAccountSwitcher) -> bool:
|
|
301
|
+
"""Rollback all completed steps in reverse order.
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
True if rollback successful, False if any step failed.
|
|
305
|
+
"""
|
|
306
|
+
success = True
|
|
307
|
+
for step in reversed(self.completed_steps):
|
|
308
|
+
try:
|
|
309
|
+
if step == "credentials_written":
|
|
310
|
+
switcher._write_credentials(self.original_credentials)
|
|
311
|
+
elif step == "config_written":
|
|
312
|
+
# By rename, never in place (#419): see atomic_write_text.
|
|
313
|
+
atomic_write_text(self.config_path, self.original_config)
|
|
314
|
+
elif step == "sequence_updated":
|
|
315
|
+
data = switcher._get_sequence_data()
|
|
316
|
+
if data:
|
|
317
|
+
data["activeAccountNumber"] = int(self.original_account_num)
|
|
318
|
+
data["lastUpdated"] = get_timestamp()
|
|
319
|
+
switcher._write_json(switcher.sequence_file, data)
|
|
320
|
+
switcher._logger.info(f"Rolled back step: {step}")
|
|
321
|
+
except Exception as e:
|
|
322
|
+
switcher._logger.error(f"Failed to rollback step {step}: {e}")
|
|
323
|
+
success = False
|
|
324
|
+
return success
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def get_timestamp() -> str:
|
|
328
|
+
"""Get current UTC timestamp in ISO format."""
|
|
329
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|