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,240 @@
1
+ """macOS Keychain access via the ``security`` CLI.
2
+
3
+ A small wrapper around the system ``security`` tool for storing generic
4
+ passwords, used instead of the third-party ``keyring`` library. Two reasons:
5
+
6
+ - The macOS hot path no longer needs the ``keyring`` dependency.
7
+ - Keychain items are created and read by the same stable ``security`` binary, so
8
+ reads stay silent across upgrades. ``keyring`` (and any in-process
9
+ Security.framework call) anchors the item's access to the *Python interpreter*,
10
+ which ``uv tool upgrade`` rebuilds — at which point macOS can show the "wants to
11
+ use your keychain" prompt. ``security`` never changes, so creator == reader and
12
+ there is no prompt.
13
+
14
+ The read/write/delete shapes mirror Claude Code's own implementation
15
+ (``utils/secureStorage/macOsKeychainStorage.ts``):
16
+
17
+ - ``set_password`` hex-encodes the value (``-X``) and pipes the command through
18
+ ``security -i`` (stdin) so the secret never appears in process argv (a
19
+ process-monitor / CrowdStrike concern). It falls back to argv only when the
20
+ command would overflow ``security -i``'s 4096-byte stdin line buffer, which
21
+ would otherwise truncate mid-argument and silently corrupt the entry.
22
+ - ``get_password`` uses ``find-generic-password ... -w`` and treats exit code 44
23
+ as "not found" (returns ``None``); any *other* non-zero exit raises so callers
24
+ can tell a genuine miss apart from a locked/denied/unavailable Keychain.
25
+
26
+ Caveat: values must be printable text. ``find-generic-password -w`` prints the
27
+ stored data raw only when it is printable; data with non-printable bytes comes
28
+ back *hex-encoded*, so a write/read round-trip would not be identity. Fine for
29
+ this codebase (credentials are ASCII JSON), but don't reuse this wrapper for
30
+ arbitrary binary data. Claude Code's ``-w`` reads share the same constraint.
31
+
32
+ This module is import-safe on every platform (it only shells out at call time);
33
+ its functions are only meaningful on macOS.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import os
39
+ import subprocess
40
+
41
+ from claude_swap import spawn
42
+
43
+ # ``security -i`` reads stdin with a 4096-byte fgets() buffer (BUFSIZ on darwin).
44
+ # A command line longer than this is truncated mid-argument: it fails to write
45
+ # while leaving any previous entry intact (Claude Code #30337). 64 bytes of
46
+ # headroom guards against line-terminator accounting differences.
47
+ SECURITY_STDIN_LINE_LIMIT = 4096 - 64
48
+
49
+ _NOT_FOUND_RC = 44 # errSecItemNotFound surfaced by find/delete-generic-password
50
+
51
+ # Bound every ``security`` spawn so a wedged Keychain (a locked login keychain
52
+ # prompting for an unlock that never comes on a headless/SSH host) can't hang the
53
+ # CLI. 5s, deliberately short: a credential op that has to fall back to the file
54
+ # may be followed by a best-effort cleanup spawn, so the per-op budget doubles in
55
+ # the worst case. A healthy Keychain answers in well under 100ms.
56
+ _TIMEOUT = 5.0
57
+
58
+ # Pin the absolute path to Apple's system binary rather than resolving via PATH:
59
+ # this is a credential tool, so an attacker-controlled ``security`` earlier on
60
+ # PATH must not be able to intercept secrets. ``/usr/bin/security`` is present on
61
+ # every macOS.
62
+ _SECURITY = "/usr/bin/security"
63
+
64
+
65
+ class KeychainError(Exception):
66
+ """A ``security`` invocation failed for a reason other than "not found"."""
67
+
68
+
69
+ class KeychainTimeout(KeychainError):
70
+ """A ``security`` invocation did not finish within its time limit."""
71
+
72
+
73
+ # The exceptions a Keychain operation may raise that callers should treat as
74
+ # "Keychain unusable" (→ fall back to file storage) rather than a programming
75
+ # bug: a wrapper failure (KeychainError, incl. a converted timeout), a raw
76
+ # subprocess timeout, or a missing ``security`` binary (OSError). Catching this
77
+ # tuple — never bare ``Exception`` — keeps a real bug loud instead of silently
78
+ # routing to the file backend mid-invocation.
79
+ KEYCHAIN_ERRORS = (KeychainError, subprocess.TimeoutExpired, OSError)
80
+
81
+
82
+ def keychain_account_name() -> str:
83
+ """Account name for the active-credential Keychain item, mirroring Claude
84
+ Code's ``getUsername()`` (``utils/secureStorage/macOsKeychainHelpers.ts``).
85
+
86
+ ``$USER`` first, then the OS username, then a stable final fallback. Matching
87
+ this exactly matters on headless/launchd/cron hosts where ``$USER`` is unset:
88
+ a divergent default (e.g. ``"user"``) would key a *different* Keychain item
89
+ than Claude Code, so the two could not see each other's active credential.
90
+ """
91
+ user = os.environ.get("USER")
92
+ if user:
93
+ return user
94
+ try:
95
+ import pwd # POSIX-only; the account-name call sites are macOS-only
96
+
97
+ return pwd.getpwuid(os.geteuid()).pw_name
98
+ except Exception:
99
+ return "claude-code-user"
100
+
101
+
102
+ def _quote(value: str) -> str:
103
+ """Quote a value for a ``security -i`` stdin command line.
104
+
105
+ ``security -i`` re-parses each line shell-style, so wrap the value in double
106
+ quotes and backslash-escape any embedded ``"``/``\\`` (e.g. the active-
107
+ credential service name contains a space).
108
+ """
109
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
110
+ return f'"{escaped}"'
111
+
112
+
113
+ def get_password(
114
+ service: str, account: str, timeout: float | None = None
115
+ ) -> str | None:
116
+ """Return the stored password, or ``None`` if no such item exists (rc 44).
117
+
118
+ Raises :class:`KeychainError` on any other non-zero exit (locked / denied /
119
+ unavailable) and :class:`KeychainTimeout` on a timeout, so a genuine miss is
120
+ not confused with a transient failure.
121
+
122
+ ``timeout`` replaces the default bound for a read that waits on a person
123
+ (see :func:`claude_swap.migrations.migrate_macos_keyring_to_security`).
124
+ """
125
+ limit = _TIMEOUT if timeout is None else timeout
126
+ try:
127
+ result = spawn.run(
128
+ [_SECURITY, "find-generic-password", "-a", account, "-w", "-s", service],
129
+ capture_output=True,
130
+ text=True,
131
+ timeout=limit,
132
+ )
133
+ except subprocess.TimeoutExpired as e:
134
+ raise KeychainTimeout(
135
+ f"security find-generic-password timed out after {limit}s"
136
+ ) from e
137
+ if result.returncode == 0:
138
+ # `-w` prints the value followed by one newline; strip exactly that so
139
+ # values with meaningful leading/trailing whitespace survive intact.
140
+ return result.stdout.removesuffix("\n")
141
+ if result.returncode == _NOT_FOUND_RC:
142
+ return None
143
+ raise KeychainError(
144
+ f"security find-generic-password failed (rc={result.returncode}): "
145
+ f"{result.stderr.strip()}"
146
+ )
147
+
148
+
149
+ def item_exists(service: str, account: str) -> bool:
150
+ """Whether a generic-password item exists, without touching its secret.
151
+
152
+ Attribute-only lookup (no ``-w``): nothing is decrypted, so this can never
153
+ trigger a Keychain prompt, even for items owned by another app. Returns
154
+ ``True`` only on rc 0; "not found" (rc 44), error exits, a timeout, and a
155
+ missing binary all return ``False``. Deliberately **non-raising**: callers use
156
+ it for cleanup verification, not access decisions, so it must never feed the
157
+ capability cache (a timeout here means "couldn't tell", not "Keychain works").
158
+ """
159
+ try:
160
+ result = spawn.run(
161
+ [_SECURITY, "find-generic-password", "-a", account, "-s", service],
162
+ capture_output=True,
163
+ text=True,
164
+ timeout=_TIMEOUT,
165
+ )
166
+ except (subprocess.TimeoutExpired, OSError):
167
+ return False
168
+ return result.returncode == 0
169
+
170
+
171
+ def set_password(service: str, account: str, password: str) -> None:
172
+ """Create or update a generic-password item (``-U``).
173
+
174
+ Prefers ``security -i`` stdin so the secret stays out of argv; falls back to
175
+ argv only for payloads that would overflow the stdin line buffer. Raises
176
+ :class:`KeychainError` on a non-zero exit and :class:`KeychainTimeout` on a
177
+ timeout.
178
+ """
179
+ hex_value = password.encode("utf-8").hex()
180
+ # `-X` passes the value as hex, avoiding any escaping issues for the secret.
181
+ command = (
182
+ f"add-generic-password -U -a {_quote(account)} -s {_quote(service)} "
183
+ f"-X {hex_value}\n"
184
+ )
185
+ try:
186
+ if len(command.encode("utf-8")) <= SECURITY_STDIN_LINE_LIMIT:
187
+ result = spawn.run(
188
+ [_SECURITY, "-i"],
189
+ input=command,
190
+ capture_output=True,
191
+ text=True,
192
+ timeout=_TIMEOUT,
193
+ )
194
+ else:
195
+ # Overflows the stdin line buffer; fall back to argv. Hex in argv is
196
+ # recoverable by a determined observer but defeats naive plaintext-grep
197
+ # rules, and the alternative — silent corruption — is strictly worse.
198
+ result = spawn.run(
199
+ [
200
+ _SECURITY, "add-generic-password", "-U",
201
+ "-a", account, "-s", service, "-X", hex_value,
202
+ ],
203
+ capture_output=True,
204
+ text=True,
205
+ timeout=_TIMEOUT,
206
+ )
207
+ except subprocess.TimeoutExpired as e:
208
+ raise KeychainTimeout(
209
+ f"security add-generic-password timed out after {_TIMEOUT}s"
210
+ ) from e
211
+ if result.returncode != 0:
212
+ raise KeychainError(
213
+ f"security add-generic-password failed (rc={result.returncode}): "
214
+ f"{result.stderr.strip()}"
215
+ )
216
+
217
+
218
+ def delete_password(service: str, account: str) -> None:
219
+ """Delete a generic-password item. rc 44 (already absent) counts as success.
220
+
221
+ Raises :class:`KeychainError` on any other non-zero exit and
222
+ :class:`KeychainTimeout` on a timeout.
223
+ """
224
+ try:
225
+ result = spawn.run(
226
+ [_SECURITY, "delete-generic-password", "-a", account, "-s", service],
227
+ capture_output=True,
228
+ text=True,
229
+ timeout=_TIMEOUT,
230
+ )
231
+ except subprocess.TimeoutExpired as e:
232
+ raise KeychainTimeout(
233
+ f"security delete-generic-password timed out after {_TIMEOUT}s"
234
+ ) from e
235
+ if result.returncode in (0, _NOT_FOUND_RC):
236
+ return
237
+ raise KeychainError(
238
+ f"security delete-generic-password failed (rc={result.returncode}): "
239
+ f"{result.stderr.strip()}"
240
+ )
@@ -0,0 +1,127 @@
1
+ """Directory → account mappings for `cswap run` auto-resolution.
2
+
3
+ Maps a normalized absolute directory path to a stored account identity
4
+ (email + organizationUuid). `cswap run` with no account argument resolves the
5
+ current working directory to the nearest mapped ancestor and launches that
6
+ account in session mode.
7
+
8
+ Persisted to ``<backup_dir>/mappings.json``. Identity is stored as the stable
9
+ (email, organizationUuid) composite rather than the slot number, since slot
10
+ numbers are reused when accounts are removed and re-added. This module is
11
+ deliberately decoupled from ``switcher`` (it never imports it): callers resolve
12
+ an entry's (email, org) to a live slot via the switcher themselves.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from claude_swap.fsutil import atomic_write_text
23
+ from claude_swap.models import get_timestamp
24
+
25
+ SCHEMA_VERSION = 1
26
+
27
+
28
+ def normalize_path(p: str | Path) -> str:
29
+ """Normalize a path to a stable, comparable mapping key.
30
+
31
+ Expands ``~``, makes the path absolute, resolves symlinks, and applies
32
+ ``os.path.normcase`` (case-folding on Windows, a no-op on POSIX) so the
33
+ same directory always produces the same key regardless of how it was typed.
34
+ """
35
+ resolved = Path(p).expanduser().resolve()
36
+ return os.path.normcase(str(resolved))
37
+
38
+
39
+ class MappingStore:
40
+ """Reads and writes ``<backup_dir>/mappings.json``."""
41
+
42
+ def __init__(self, backup_dir: Path):
43
+ self.path = Path(backup_dir) / "mappings.json"
44
+
45
+ def load(self) -> dict[str, dict]:
46
+ """Return the normalized-path → entry map (empty on missing/corrupt)."""
47
+ if not self.path.exists():
48
+ return {}
49
+ try:
50
+ data = json.loads(self.path.read_text(encoding="utf-8"))
51
+ except (json.JSONDecodeError, UnicodeDecodeError, OSError):
52
+ return {}
53
+ if not isinstance(data, dict):
54
+ return {}
55
+ mappings = data.get("mappings", {})
56
+ return mappings if isinstance(mappings, dict) else {}
57
+
58
+ def all(self) -> dict[str, dict]:
59
+ """Public alias for the full mapping table."""
60
+ return self.load()
61
+
62
+ def get(self, path: str | Path) -> dict | None:
63
+ """Exact-match lookup for a normalized path (no ancestor walk)."""
64
+ return self.load().get(normalize_path(path))
65
+
66
+ def set(self, path: str | Path, email: str, org_uuid: str) -> None:
67
+ """Upsert a mapping for ``path`` and persist atomically."""
68
+ mappings = self.load()
69
+ mappings[normalize_path(path)] = {
70
+ "email": email,
71
+ "organizationUuid": org_uuid or "",
72
+ "added": get_timestamp(),
73
+ }
74
+ self._write(mappings)
75
+
76
+ def remove(self, path: str | Path) -> bool:
77
+ """Delete the mapping for ``path``; return whether one was removed."""
78
+ mappings = self.load()
79
+ if mappings.pop(normalize_path(path), None) is None:
80
+ return False
81
+ self._write(mappings)
82
+ return True
83
+
84
+ def prune_account(self, email: str, org_uuid: str) -> int:
85
+ """Drop every mapping pointing at (email, org_uuid). Return count removed."""
86
+ mappings = self.load()
87
+ org = org_uuid or ""
88
+ doomed = [
89
+ key
90
+ for key, entry in mappings.items()
91
+ if entry.get("email") == email
92
+ and (entry.get("organizationUuid", "") or "") == org
93
+ ]
94
+ for key in doomed:
95
+ del mappings[key]
96
+ if doomed:
97
+ self._write(mappings)
98
+ return len(doomed)
99
+
100
+ def resolve(self, cwd: str | Path) -> tuple[str, dict] | None:
101
+ """Return (key, entry) of the longest mapped ancestor of ``cwd``.
102
+
103
+ A mapping matches when its directory equals ``cwd`` or is an ancestor
104
+ of it. The most specific (longest path) match wins, so nested folders
105
+ inherit the closest mapping. All candidates lie on the single
106
+ root→cwd chain, so the longest key string is the deepest match.
107
+ """
108
+ target = Path(normalize_path(cwd))
109
+ best: tuple[str, dict] | None = None
110
+ best_len = -1
111
+ for key, entry in self.load().items():
112
+ candidate = Path(key)
113
+ if candidate == target or candidate in target.parents:
114
+ if len(key) > best_len:
115
+ best = (key, entry)
116
+ best_len = len(key)
117
+ return best
118
+
119
+ def _write(self, mappings: dict[str, dict]) -> None:
120
+ """Atomically write the mappings file (temp beside it + rename)."""
121
+ self.path.parent.mkdir(parents=True, exist_ok=True)
122
+ if sys.platform != "win32":
123
+ os.chmod(self.path.parent, 0o700)
124
+ payload = json.dumps(
125
+ {"schemaVersion": SCHEMA_VERSION, "mappings": mappings}, indent=2
126
+ )
127
+ atomic_write_text(self.path, payload)