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.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,807 @@
1
+ """Export and import account data for claude-swap.
2
+
3
+ Moves the OAuth credentials and config across machines via a portable
4
+ JSON envelope. No encryption is built in — users compose their own
5
+ (e.g. `cswap --export - | gpg -c > out.gpg`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from claude_swap import __version__
17
+ from claude_swap.credentials import looks_like_api_key
18
+ from claude_swap.exceptions import (
19
+ ConfigError,
20
+ CredentialReadError,
21
+ TransferError,
22
+ )
23
+ from claude_swap.fsutil import atomic_write_text, read_text_with_retry
24
+ from claude_swap.json_output import SCHEMA_VERSION as JSON_SCHEMA_VERSION
25
+ from claude_swap.json_output import usage_from_json
26
+ from claude_swap.models import Platform, get_timestamp, normalize_alias
27
+ from claude_swap.oauth import credential_fingerprint
28
+
29
+ if TYPE_CHECKING:
30
+ from claude_swap.switcher import ClaudeAccountSwitcher
31
+
32
+
33
+ FORMAT_VERSION = 1
34
+
35
+ _PLATFORM_TAG = {
36
+ Platform.MACOS: "macos",
37
+ Platform.LINUX: "linux",
38
+ Platform.WSL: "wsl",
39
+ Platform.WINDOWS: "windows",
40
+ Platform.UNKNOWN: "unknown",
41
+ }
42
+
43
+
44
+ def _eprint(msg: str) -> None:
45
+ """Print to stderr so stdout stays pure JSON in pipe mode."""
46
+ print(msg, file=sys.stderr)
47
+
48
+
49
+ def _parse_payload(text: str, label: str) -> dict:
50
+ """Parse a JSON string that should decode to an object."""
51
+ try:
52
+ parsed = json.loads(text)
53
+ except json.JSONDecodeError as exc:
54
+ raise TransferError(f"{label} is not valid JSON: {exc}")
55
+ if not isinstance(parsed, dict):
56
+ raise TransferError(f"{label} must be a JSON object")
57
+ return parsed
58
+
59
+
60
+ def _read_live_config(
61
+ switcher: ClaudeAccountSwitcher,
62
+ ) -> tuple[str | None, tuple[str, str] | None]:
63
+ """The live ``.claude.json`` text and the ``(email, organization_uuid)``
64
+ it names, from one read, so the text an export carries is the text that
65
+ was judged. ``(None, None)`` when the file is absent, unreadable or names
66
+ no account.
67
+ """
68
+ try:
69
+ text = read_text_with_retry(switcher._get_claude_config_path())
70
+ parsed = json.loads(text)
71
+ except (OSError, ValueError):
72
+ return None, None
73
+ triple = switcher._identity_triple_of(
74
+ parsed if isinstance(parsed, dict) else None
75
+ )
76
+ if triple is None:
77
+ return None, None
78
+ return text, triple[:2]
79
+
80
+
81
+ def _validate_imported_account(switcher: ClaudeAccountSwitcher, account: dict) -> tuple[str, str]:
82
+ """Validate per-account fields BEFORE any filename construction.
83
+
84
+ Defends against path traversal: email + slot number flow into f-string
85
+ filenames in switcher._read_account_credentials etc., so they must be
86
+ constrained before use.
87
+ """
88
+ if not isinstance(account, dict):
89
+ raise TransferError("account entry must be a JSON object")
90
+
91
+ email = account.get("email")
92
+ if not isinstance(email, str) or not switcher._validate_email(email):
93
+ raise TransferError(f"invalid or missing email in imported account: {email!r}")
94
+
95
+ raw_number = account.get("number")
96
+ if isinstance(raw_number, bool) or not isinstance(raw_number, int) or raw_number < 1:
97
+ raise TransferError(
98
+ f"invalid slot number in imported account ({email}): {raw_number!r}"
99
+ )
100
+
101
+ # Org/uuid/added must be strings (or absent). A list/dict here would
102
+ # otherwise blow up downstream (unhashable in seen_keys, broken composite
103
+ # key matching, garbage in sequence.json).
104
+ for field in ("organizationUuid", "organizationName", "uuid", "added", "alias"):
105
+ if field in account and account[field] is not None:
106
+ if not isinstance(account[field], str):
107
+ raise TransferError(
108
+ f"{field} for {email} must be a string, got {type(account[field]).__name__}"
109
+ )
110
+
111
+ alias = account.get("alias")
112
+ if isinstance(alias, str):
113
+ try:
114
+ normalize_alias(alias)
115
+ except ValueError as e:
116
+ raise TransferError(f"invalid alias for {email}: {e}") from e
117
+
118
+ return email, str(raw_number)
119
+
120
+
121
+ def _atomic_write_file(path: Path, content: str) -> None:
122
+ """Write text atomically with 0600 perms, never exposing plaintext content
123
+ at a world-readable mode.
124
+
125
+ Uses ``tempfile.mkstemp`` (0600 from creation, per the process umask being
126
+ irrelevant to it) rather than ``Path.write_text`` + a follow-up ``chmod``:
127
+ the export payload carries live OAuth refresh tokens, and a write-then-
128
+ chmod sequence leaves the temp file at the umask-derived default mode
129
+ (typically world-readable) for the window between creation and the chmod
130
+ call. The shared ``fsutil.atomic_write_text`` is that pattern.
131
+
132
+ ``follow_symlinks=False``: the destination is a path the user typed, often
133
+ under a shared directory such as ``/tmp``, and a symlink planted there by
134
+ another local user must not redirect an export full of refresh tokens onto
135
+ a file of their choosing. The rename replaces the link itself (in a sticky
136
+ directory a foreign entry makes that rename fail, which is the right
137
+ outcome).
138
+ """
139
+ if path.is_dir():
140
+ raise TransferError(
141
+ f"export destination must be a file path, not a directory: {path}"
142
+ )
143
+ atomic_write_text(path, content, follow_symlinks=False)
144
+
145
+
146
+ def _slim_config(config_obj: dict, label: str) -> dict:
147
+ """Reduce a parsed ~/.claude.json to just the keys a switch will consume.
148
+
149
+ Today, only `oauthAccount` is read back during a switch. Stripping the
150
+ rest at export time keeps cross-machine transfers small and avoids
151
+ leaking source-machine identity (userID, anonymousId, absolute paths,
152
+ cached feature flags) into the destination.
153
+ """
154
+ oauth = config_obj.get("oauthAccount")
155
+ if not isinstance(oauth, dict):
156
+ raise TransferError(
157
+ f"{label} is missing oauthAccount — cannot export"
158
+ )
159
+ return {"oauthAccount": oauth}
160
+
161
+
162
+ def _slim_credentials(creds_obj: dict) -> dict:
163
+ """Reduce an OAuth credential object to the account's own login.
164
+
165
+ The siblings of ``claudeAiOauth`` are either machine-shared MCP/plugin
166
+ OAuth state — owned by whichever machine the export lands on and
167
+ replaced from the live credential at activation anyway (#135) — or
168
+ device-bound (``trustedDeviceToken``), meaningless off-device. Both are
169
+ secret surface with no cross-machine value. Legacy shapes without
170
+ ``claudeAiOauth`` export verbatim; ``--full`` (same-PC backup) skips
171
+ this and keeps the whole blob.
172
+ """
173
+ if "claudeAiOauth" not in creds_obj:
174
+ return creds_obj
175
+ return {"claudeAiOauth": creds_obj["claudeAiOauth"]}
176
+
177
+
178
+ def export_accounts(
179
+ switcher: ClaudeAccountSwitcher,
180
+ destination: str,
181
+ account: str | None = None,
182
+ full: bool = False,
183
+ ) -> None:
184
+ """Export accounts to a JSON file or stdout.
185
+
186
+ Args:
187
+ switcher: Initialized ClaudeAccountSwitcher.
188
+ destination: File path, or "-" for stdout.
189
+ account: Optional NUM|EMAIL to limit export to a single account.
190
+ full: When True, include the entire ~/.claude.json snapshot and the
191
+ entire credential object per account (same-PC backup). Default
192
+ False writes only oauthAccount and the account's own
193
+ claudeAiOauth login.
194
+
195
+ Raises:
196
+ TransferError: malformed/missing data, unknown account.
197
+ CredentialReadError: failed to read credentials.
198
+ """
199
+ sequence_data = switcher._get_sequence_data_migrated()
200
+ if not sequence_data or not sequence_data.get("accounts"):
201
+ raise TransferError("no accounts to export — run cswap --add-account first")
202
+
203
+ accounts_map = sequence_data["accounts"]
204
+
205
+ # Resolve which account numbers to export. When the user named a specific
206
+ # account, missing backup data is a hard failure (they asked for that one);
207
+ # in the all-accounts case we skip broken slots with a warning so one
208
+ # damaged slot doesn't poison the whole backup.
209
+ explicit_account = account is not None
210
+ if explicit_account:
211
+ resolved = switcher._resolve_account_identifier(account)
212
+ if resolved is None or resolved not in accounts_map:
213
+ raise TransferError(f"account not found: {account}")
214
+ target_nums = [resolved]
215
+ else:
216
+ target_nums = sorted(accounts_map.keys(), key=int)
217
+
218
+ # The slot whose login is live is exported from the live store, which
219
+ # holds fresher tokens than its backup. Which slot that is, the login
220
+ # says (switcher._active_slot); the config only names an account. The
221
+ # live login and the live config are each read once, here, so a switch
222
+ # landing while the slots are read cannot put another account's login or
223
+ # config into this slot's entry.
224
+ live_config_text, current_identity = _read_live_config(switcher)
225
+ active_num: str | None = None
226
+ live_login = None
227
+ if current_identity is not None:
228
+ active_num, live_login = switcher._active_slot(
229
+ sequence_data, current_identity, cached=False
230
+ )
231
+
232
+ accounts_payload: list[dict[str, Any]] = []
233
+ for num in target_nums:
234
+ record = accounts_map[num]
235
+ email = record.get("email", "")
236
+ org_uuid = record.get("organizationUuid", "") or ""
237
+
238
+ is_active = num == active_num
239
+ # The live config goes with the live login only while it names the
240
+ # same account. Relabelled by another host, it describes that host's
241
+ # account, and this slot's own config is the one in its backup.
242
+ live_config = is_active and current_identity == (email, org_uuid)
243
+
244
+ if is_active:
245
+ creds_text = (
246
+ live_login.value if live_login is not None
247
+ else switcher._read_credentials()
248
+ )
249
+ if not creds_text:
250
+ raise CredentialReadError(
251
+ f"failed to read live credentials for active account {email}"
252
+ )
253
+ else:
254
+ creds_text = switcher._read_account_credentials(num, email)
255
+ if live_config:
256
+ config_text = live_config_text
257
+ else:
258
+ config_text = switcher._read_account_config(num, email)
259
+ if not creds_text or not config_text:
260
+ if explicit_account:
261
+ if not creds_text:
262
+ raise CredentialReadError(
263
+ f"no backup credentials found for account {num} ({email})"
264
+ )
265
+ raise ConfigError(
266
+ f"no backup config found for account {num} ({email})"
267
+ )
268
+ _eprint(
269
+ f"Skipping Account-{num} ({email}): no stored "
270
+ f"credentials/config — re-add with: "
271
+ f"cswap --add-account --slot {num}"
272
+ )
273
+ continue
274
+
275
+ config_obj = _parse_payload(config_text, f"config for {email}")
276
+ if not full:
277
+ config_obj = _slim_config(config_obj, f"config for {email}")
278
+
279
+ # API-key accounts store the credential as a raw ``sk-ant-…`` string,
280
+ # not OAuth JSON — carry it verbatim (and tag the kind) so the JSON parse
281
+ # below doesn't choke and import can restore it as-is.
282
+ is_api_key = looks_like_api_key(creds_text)
283
+ if is_api_key:
284
+ creds_payload: Any = creds_text.strip()
285
+ else:
286
+ creds_payload = _parse_payload(creds_text, f"credentials for {email}")
287
+ if not full:
288
+ creds_payload = _slim_credentials(creds_payload)
289
+ entry: dict[str, Any] = {
290
+ "number": int(num),
291
+ "email": email,
292
+ "uuid": record.get("uuid", ""),
293
+ "organizationUuid": org_uuid,
294
+ "organizationName": record.get("organizationName", "") or "",
295
+ "added": record.get("added", ""),
296
+ "credentials": creds_payload,
297
+ "config": config_obj,
298
+ }
299
+ if is_api_key:
300
+ entry["kind"] = "api_key"
301
+ if record.get("alias"):
302
+ entry["alias"] = record["alias"]
303
+ accounts_payload.append(entry)
304
+
305
+ if not accounts_payload:
306
+ raise TransferError(
307
+ "no exportable accounts — all managed slots are missing stored "
308
+ "credentials/config. Re-add with: cswap --add-account --slot <number>"
309
+ )
310
+
311
+ # Only carry activeAccountNumber if that slot is actually present in the
312
+ # payload — otherwise import would reference an account that isn't there
313
+ # (e.g., the recorded active slot was skipped due to missing backup).
314
+ recorded_active = sequence_data.get("activeAccountNumber")
315
+ exported_nums = {a["number"] for a in accounts_payload}
316
+ active_in_payload = (
317
+ recorded_active if recorded_active in exported_nums else None
318
+ )
319
+
320
+ envelope = {
321
+ "version": FORMAT_VERSION,
322
+ "exportedAt": get_timestamp(),
323
+ "exportedFrom": _PLATFORM_TAG.get(switcher.platform, "unknown"),
324
+ "swapVersion": __version__,
325
+ "encrypted": False,
326
+ "activeAccountNumber": active_in_payload,
327
+ "accounts": accounts_payload,
328
+ }
329
+
330
+ serialized = json.dumps(envelope, indent=2)
331
+
332
+ if destination == "-":
333
+ sys.stdout.write(serialized)
334
+ sys.stdout.write("\n")
335
+ sys.stdout.flush()
336
+ return
337
+
338
+ out_path = Path(destination).expanduser()
339
+ _atomic_write_file(out_path, serialized + "\n")
340
+ _eprint(f"Exported {len(accounts_payload)} account(s) to {out_path}")
341
+
342
+
343
+ def import_accounts(
344
+ switcher: ClaudeAccountSwitcher,
345
+ source: str,
346
+ force: bool = False,
347
+ ) -> None:
348
+ """Import accounts from a JSON file or stdin.
349
+
350
+ Args:
351
+ switcher: Initialized ClaudeAccountSwitcher.
352
+ source: File path, or "-" for stdin.
353
+ force: When True, overwrites the existing matching slot in place.
354
+ Without it, existing accounts are skipped — unless the slot is
355
+ quarantined as refresh-token-dead, which a plain import replaces
356
+ (auto-heal, issue #136).
357
+
358
+ Raises:
359
+ TransferError: unreadable source, malformed file, version mismatch,
360
+ encrypted payload.
361
+ """
362
+ if source == "-":
363
+ try:
364
+ text = sys.stdin.read()
365
+ except UnicodeDecodeError as e:
366
+ # ``cswap --export - | gpg -c > backup.gpg`` is a documented
367
+ # recipe, so the bytes on stdin are quite possibly that backup
368
+ # piped straight back in without being decrypted first.
369
+ raise TransferError(
370
+ "piped input is not UTF-8 text — decrypt an encrypted backup "
371
+ "first (e.g. gpg -d backup.gpg | cswap --import -)"
372
+ ) from e
373
+ else:
374
+ in_path = Path(source).expanduser()
375
+ if not in_path.exists():
376
+ raise TransferError(f"import file not found: {in_path}")
377
+ # A directory satisfies exists(), and letting the read discover it
378
+ # raises IsADirectoryError on POSIX but PermissionError on Windows;
379
+ # checking up front gives one message on both, and mirrors the
380
+ # destination guard in ``_atomic_write_file``.
381
+ if in_path.is_dir():
382
+ raise TransferError(
383
+ f"import source must be a file path, not a directory: {in_path}"
384
+ )
385
+ try:
386
+ text = in_path.read_text(encoding="utf-8")
387
+ except UnicodeDecodeError as e:
388
+ raise TransferError(
389
+ f"{in_path} is not UTF-8 text — if it is an encrypted backup, "
390
+ "decrypt it first (e.g. gpg -d backup.gpg | cswap --import -)"
391
+ ) from e
392
+ except OSError as e:
393
+ raise TransferError(f"could not read {in_path}: {e}") from e
394
+
395
+ try:
396
+ envelope = json.loads(text)
397
+ except json.JSONDecodeError as exc:
398
+ raise TransferError(f"export file is not valid JSON: {exc}")
399
+
400
+ if not isinstance(envelope, dict):
401
+ raise TransferError("export file must be a JSON object")
402
+
403
+ version = envelope.get("version")
404
+ if version != FORMAT_VERSION:
405
+ raise TransferError(
406
+ f"unsupported export version: {version!r} (expected {FORMAT_VERSION})"
407
+ )
408
+
409
+ if envelope.get("encrypted") is True:
410
+ raise TransferError(
411
+ "encrypted exports are not supported in this version — "
412
+ "decrypt before piping (e.g. gpg -d backup.gpg | cswap --import -)"
413
+ )
414
+
415
+ accounts = envelope.get("accounts")
416
+ if not isinstance(accounts, list) or not accounts:
417
+ raise TransferError("export file has no accounts to import")
418
+
419
+ # Pass 1: validate every account before any writes. A malformed account
420
+ # later in the list must not leave earlier accounts half-imported.
421
+ local_data = switcher._get_sequence_data_migrated() or {}
422
+ local_aliases: dict[str, tuple[str, str]] = {
423
+ (acc.get("alias") or "").lower(): (
424
+ acc.get("email", ""), acc.get("organizationUuid", "") or "",
425
+ )
426
+ for acc in local_data.get("accounts", {}).values()
427
+ if acc.get("alias")
428
+ }
429
+ normalized: list[dict[str, Any]] = []
430
+ seen_keys: set[tuple[str, str]] = set()
431
+ seen_aliases: set[str] = set()
432
+ for raw in accounts:
433
+ email, exported_num = _validate_imported_account(switcher, raw)
434
+ org_uuid = raw.get("organizationUuid", "") or ""
435
+ creds_obj = raw.get("credentials")
436
+ config_obj = raw.get("config")
437
+ if not isinstance(config_obj, dict):
438
+ raise TransferError(f"config for {email} must be a JSON object")
439
+ # API-key accounts carry the credential as a raw string; OAuth accounts
440
+ # carry a JSON object.
441
+ is_api_key = raw.get("kind") == "api_key" or isinstance(creds_obj, str)
442
+ if is_api_key:
443
+ if not (isinstance(creds_obj, str) and looks_like_api_key(creds_obj)):
444
+ raise TransferError(
445
+ f"API-key credentials for {email} must be a raw sk-ant-… key "
446
+ "(not an OAuth token)"
447
+ )
448
+ creds_text = creds_obj.strip()
449
+ else:
450
+ if not isinstance(creds_obj, dict):
451
+ raise TransferError(
452
+ f"credentials for {email} must be a JSON object"
453
+ )
454
+ creds_text = json.dumps(creds_obj)
455
+ key = (email, org_uuid)
456
+ if key in seen_keys:
457
+ raise TransferError(
458
+ f"duplicate account in export: {email} (org={org_uuid or 'personal'})"
459
+ )
460
+ seen_keys.add(key)
461
+
462
+ alias = raw.get("alias") or None
463
+ if alias:
464
+ alias_key = normalize_alias(alias) # already validated in pass-1 above
465
+ if alias_key in seen_aliases:
466
+ raise TransferError(f"duplicate alias in export: {alias_key}")
467
+ seen_aliases.add(alias_key)
468
+ owner = local_aliases.get(alias_key)
469
+ if owner is not None and owner != (email, org_uuid):
470
+ _eprint(
471
+ f"Warning: alias '{alias_key}' for {email} already used by an "
472
+ "existing account, dropping the imported alias"
473
+ )
474
+ alias = None
475
+ else:
476
+ alias = alias_key
477
+
478
+ normalized.append(
479
+ {
480
+ "email": email,
481
+ "exported_num": exported_num,
482
+ "org_uuid": org_uuid,
483
+ "org_name": raw.get("organizationName", "") or "",
484
+ "uuid": raw.get("uuid", "") or "",
485
+ "added": raw.get("added") or get_timestamp(),
486
+ "kind": "api_key" if is_api_key else "oauth",
487
+ "alias": alias,
488
+ "creds_text": creds_text,
489
+ "config_text": json.dumps(config_obj, indent=2),
490
+ }
491
+ )
492
+
493
+ # Pass 2: writes. Validation is complete; remaining failures (disk I/O,
494
+ # Keychain) are environmental and don't reflect on the file's integrity.
495
+ switcher._setup_directories()
496
+ switcher._init_sequence_file()
497
+
498
+ imported = 0
499
+ skipped = 0
500
+ overwritten = 0
501
+ replaced = 0
502
+ written_slots: set[str] = set()
503
+
504
+ # Track where the envelope's active account ended up locally. We can't
505
+ # just look up envelope_active in the final account map afterwards: the
506
+ # destination may already have an unrelated account at that slot number,
507
+ # while the envelope's active account got allocated to a different slot.
508
+ envelope_active = envelope.get("activeAccountNumber")
509
+ envelope_active_str = (
510
+ str(envelope_active) if isinstance(envelope_active, int) else None
511
+ )
512
+ resolved_active_slot: str | None = None
513
+
514
+ for entry in normalized:
515
+ is_envelope_active = (
516
+ envelope_active_str is not None
517
+ and entry["exported_num"] == envelope_active_str
518
+ )
519
+
520
+ # Re-read sequence each iteration so per-account writes see prior updates
521
+ data = switcher._get_sequence_data_migrated() or {
522
+ "activeAccountNumber": None,
523
+ "lastUpdated": get_timestamp(),
524
+ "sequence": [],
525
+ "accounts": {},
526
+ }
527
+ existing_slot = switcher._find_account_slot(
528
+ data, entry["email"], entry["org_uuid"]
529
+ )
530
+
531
+ if existing_slot is not None:
532
+ if force:
533
+ outcome = "overwrote"
534
+ # Snapshot the row before the write path's clear_dead_token
535
+ # wipes it, so the "Overwrote" print can say the strike was
536
+ # lifted. Silence here is how issue #218 read a lifted-then-
537
+ # honestly-re-condemned strike as a clear that never happened.
538
+ # Identity-guarded: a foreign row reads blank, so only this
539
+ # account's own verdict narrates.
540
+ row = switcher._usage_store.entries(
541
+ {existing_slot: (entry["email"], entry["org_uuid"])}
542
+ )[existing_slot]
543
+ had_strike = row.auth_dead_strikes > 0
544
+ same_generation = (
545
+ row.struck_fingerprint is not None
546
+ and credential_fingerprint(entry["creds_text"])
547
+ == row.struck_fingerprint
548
+ )
549
+ elif switcher._slot_token_dead(existing_slot, entry["email"]):
550
+ # Narrow auto-heal (issue #136): a plain import replaces a
551
+ # slot iff its identity-matched usage row is quarantined as
552
+ # refresh-token-dead. The verdict normally postdates the
553
+ # slot's last credential write, so the heal targets creds that
554
+ # failed after being stored (known exception and full
555
+ # trade-off: INVESTIGATION-import-dead-token.md). Identity-
556
+ # guarded — a stale row for a different account returns an
557
+ # empty entry — so healthy slots still require --force. Never
558
+ # triggered by the live store's "no credentials" state, which
559
+ # isn't attributable to the backup.
560
+ outcome = "replaced"
561
+ else:
562
+ _eprint(
563
+ f"Skipped {entry['email']} (already exists, use --force)"
564
+ )
565
+ skipped += 1
566
+ # Even when skipped, the envelope's active account exists
567
+ # locally — record where so we can seed activeAccountNumber.
568
+ if is_envelope_active:
569
+ resolved_active_slot = existing_slot
570
+ continue
571
+ target_num = existing_slot
572
+ # The credential write below invalidates the slot's non-live
573
+ # session profile (chokepoint in _write_account_credentials), so
574
+ # the next `cswap run` re-bootstraps from the imported creds. A
575
+ # live session keeps running on its own copy — warn about it.
576
+ live_pids = switcher._live_session_pids(target_num, entry["email"])
577
+ if live_pids:
578
+ _eprint(
579
+ f"Warning: {entry['email']} (slot {target_num}) has a live "
580
+ f"session-mode instance (PID {', '.join(map(str, live_pids))}); "
581
+ "its session profile keeps the pre-import credentials until "
582
+ "it is restarted via 'cswap run'."
583
+ )
584
+ else:
585
+ if entry["exported_num"] not in data.get("accounts", {}):
586
+ target_num = entry["exported_num"]
587
+ else:
588
+ target_num = str(switcher._get_next_account_number())
589
+ outcome = "imported"
590
+
591
+ switcher._write_account_credentials(
592
+ target_num, entry["email"], entry["creds_text"]
593
+ )
594
+ switcher._write_account_config(
595
+ target_num, entry["email"], entry["config_text"]
596
+ )
597
+ # Every successful import write introduces credential material whose
598
+ # previous auth verdict is no longer authoritative, so lift any
599
+ # dead-token quarantine on this slot (mirrors add_account / the
600
+ # add-token paths). This clears for both "imported" and "overwrote":
601
+ # account removal doesn't prune usage.json, so re-importing a removed
602
+ # identity into the same slot would otherwise stay quarantined and
603
+ # never re-fetch to prove the imported token — issue #138.
604
+ switcher._usage_store.clear_dead_token(
605
+ [target_num], {target_num: (entry["email"], entry["org_uuid"])}
606
+ )
607
+
608
+ data.setdefault("accounts", {})
609
+ data.setdefault("sequence", [])
610
+ new_record = {
611
+ "email": entry["email"],
612
+ "uuid": entry["uuid"],
613
+ "organizationUuid": entry["org_uuid"],
614
+ "organizationName": entry["org_name"],
615
+ "added": entry["added"],
616
+ }
617
+ if entry["kind"] == "api_key":
618
+ new_record["kind"] = "api_key"
619
+ if entry.get("alias"):
620
+ new_record["alias"] = entry["alias"]
621
+ data["accounts"][target_num] = new_record
622
+ if int(target_num) not in data["sequence"]:
623
+ data["sequence"].append(int(target_num))
624
+ data["sequence"].sort()
625
+ data["lastUpdated"] = get_timestamp()
626
+ switcher._write_json(switcher.sequence_file, data)
627
+
628
+ if is_envelope_active:
629
+ resolved_active_slot = target_num
630
+ written_slots.add(target_num)
631
+
632
+ if outcome == "overwrote":
633
+ _eprint(f"Overwrote {entry['email']} (slot {target_num})")
634
+ if had_strike:
635
+ # Store-fact wording on purpose: import rewrites the backup,
636
+ # so for the active slot the next poll may still exercise the
637
+ # live credentials — promise only what actually happened.
638
+ _eprint(" └ cleared this slot's stored dead-token strike")
639
+ if same_generation:
640
+ # "credential generation" / "permanent auth failure", not
641
+ # "refresh-token generation" / "invalid_grant": strikes
642
+ # also come from no_refresh_token, where the condemned
643
+ # blob has no refresh token and fingerprints by content.
644
+ _eprint(
645
+ " └ this import holds the same credential "
646
+ "generation the strike condemned; another permanent "
647
+ "auth failure will quarantine it again — recover "
648
+ "with a newer export or a re-login"
649
+ )
650
+ overwritten += 1
651
+ elif outcome == "replaced":
652
+ # Describe the observed trigger (the quarantine verdict), not the
653
+ # token itself — a stale verdict can sit over newer working creds.
654
+ _eprint(
655
+ f"Replaced {entry['email']} (slot {target_num} was "
656
+ "quarantined: refresh token dead)"
657
+ )
658
+ replaced += 1
659
+ else:
660
+ _eprint(f"Imported {entry['email']} → slot {target_num}")
661
+ imported += 1
662
+
663
+ # Migration UX: if the destination has no recorded active account
664
+ # (clean home, no prior preference), seed activeAccountNumber from the
665
+ # *resolved* slot of the envelope's active account — not the envelope's
666
+ # raw slot number, which may already be occupied locally by an unrelated
667
+ # account. If the user already has an active selection locally, leave it.
668
+ final = switcher._get_sequence_data()
669
+ if (
670
+ final is not None
671
+ and final.get("activeAccountNumber") in (None, 0)
672
+ and resolved_active_slot is not None
673
+ ):
674
+ final["activeAccountNumber"] = int(resolved_active_slot)
675
+ final["lastUpdated"] = get_timestamp()
676
+ switcher._write_json(switcher.sequence_file, final)
677
+
678
+ # "replaced" gets its own count — the user must be able to distinguish
679
+ # "I forced this" from "cswap healed this". Appended only when it
680
+ # happened, keeping the common-case summary stable.
681
+ summary = (
682
+ f"Done: {imported} imported, {overwritten} overwritten, {skipped} skipped"
683
+ )
684
+ if replaced:
685
+ summary += f", {replaced} replaced (dead token)"
686
+ _eprint(summary)
687
+
688
+ # If we just rewrote the stored backup for the account that is the current
689
+ # live login, a plain switch would back the (possibly stale) live
690
+ # credentials up over it (issue #79) — point at the explicit activation
691
+ # path instead.
692
+ identity = switcher._get_current_account()
693
+ if identity is not None and final is not None:
694
+ live_slot = switcher._active_slot(final, identity)[0]
695
+ if live_slot is not None and live_slot in written_slots:
696
+ live_email = final["accounts"][live_slot].get("email") or identity[0]
697
+ _eprint(
698
+ f"Note: {live_email} is your current live login — activate the "
699
+ f"imported credentials with: cswap --switch-to {live_slot} --force"
700
+ )
701
+
702
+
703
+ def import_usage(
704
+ switcher: ClaudeAccountSwitcher,
705
+ source: str,
706
+ hold_s: float | None = None,
707
+ ) -> None:
708
+ """Adopt usage readings another machine took, from its ``cswap list --json``.
709
+
710
+ For machines that hold the same accounts: when they share a login (moved
711
+ with ``export``/``import``) or the account is budgeted per account rather
712
+ than per token (see poll_policy), every machine polling it spends one
713
+ usage-endpoint budget, so a script can let one machine poll and hand its
714
+ readings to the rest.
715
+
716
+ Each row with decision-grade usage (``usageStatus`` "ok") is matched to a
717
+ local slot by (email, organizationUuid), the key ``import`` uses, and
718
+ handed to :meth:`UsageStore.adopt` with ``usageAgeSeconds`` as its age.
719
+ Rows without usage, and accounts not managed here, are skipped. With
720
+ ``hold_s``, no local collector fetches the matched accounts for that long
721
+ (bounded; see ``adopt``); 0 lifts an earlier hold, ``None`` keeps it.
722
+
723
+ Args:
724
+ switcher: Initialized ClaudeAccountSwitcher.
725
+ source: File path, or "-" for stdin.
726
+ hold_s: Seconds no local collector may fetch the matched accounts,
727
+ 0 to lift an earlier hold, None to leave it as it is.
728
+
729
+ Raises:
730
+ TransferError: malformed document or unsupported schema version.
731
+ """
732
+ if source == "-":
733
+ text = sys.stdin.read()
734
+ else:
735
+ in_path = Path(source).expanduser()
736
+ if not in_path.exists():
737
+ raise TransferError(f"usage file not found: {in_path}")
738
+ text = in_path.read_text(encoding="utf-8")
739
+
740
+ document = _parse_payload(text, "usage document")
741
+ version = document.get("schemaVersion")
742
+ if version != JSON_SCHEMA_VERSION:
743
+ raise TransferError(
744
+ f"unsupported usage document schemaVersion: {version!r} "
745
+ f"(expected {JSON_SCHEMA_VERSION}, as printed by 'cswap list --json')"
746
+ )
747
+ rows = document.get("accounts")
748
+ if not isinstance(rows, list):
749
+ raise TransferError("usage document has no accounts list")
750
+
751
+ # Validate every row before writing any, as import_accounts does: a
752
+ # malformed row later in the list must not leave earlier ones adopted.
753
+ local_data = switcher._get_sequence_data_migrated() or {}
754
+ readings: dict[str, tuple[dict, float]] = {}
755
+ identities: dict[str, tuple[str, str]] = {}
756
+ skipped = 0
757
+ for row in rows:
758
+ if not isinstance(row, dict):
759
+ raise TransferError("each account row must be a JSON object")
760
+ email = row.get("email")
761
+ org_uuid = row.get("organizationUuid") or ""
762
+ if not isinstance(email, str) or not email or not isinstance(org_uuid, str):
763
+ raise TransferError("each account row needs an email and an organizationUuid")
764
+ if row.get("usageStatus") != "ok":
765
+ skipped += 1
766
+ continue
767
+ age_s = row.get("usageAgeSeconds")
768
+ if (
769
+ not isinstance(age_s, (int, float))
770
+ or isinstance(age_s, bool)
771
+ or not math.isfinite(age_s)
772
+ or age_s < 0
773
+ ):
774
+ raise TransferError(
775
+ f"usageAgeSeconds for {email} must be a non-negative number"
776
+ )
777
+ try:
778
+ usage = usage_from_json(row.get("usage"))
779
+ except ValueError as exc:
780
+ raise TransferError(f"usage for {email}: {exc}")
781
+ num = switcher._find_account_slot(local_data, email, org_uuid)
782
+ if num is None:
783
+ skipped += 1
784
+ continue
785
+ if num in readings:
786
+ raise TransferError(
787
+ f"duplicate account in usage document: {email} "
788
+ f"(org={org_uuid or 'personal'})"
789
+ )
790
+ readings[num] = (usage, float(age_s))
791
+ identities[num] = (email, org_uuid)
792
+
793
+ adopted = switcher._usage_store.adopt(readings, identities, hold_s=hold_s)
794
+ for num, (email, _org_uuid) in identities.items():
795
+ if num in adopted:
796
+ _eprint(f"Adopted usage for {email} → slot {num}")
797
+ else:
798
+ _eprint(f"Kept slot {num}'s own reading for {email}: it is newer")
799
+ summary = (
800
+ f"Done: {len(adopted)} adopted, {len(readings) - len(adopted)} kept, "
801
+ f"{skipped} skipped"
802
+ )
803
+ if hold_s is not None and readings:
804
+ summary += (
805
+ f"; fetching held for up to {hold_s:.0f}s" if hold_s > 0 else "; holds lifted"
806
+ )
807
+ _eprint(summary)