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,187 @@
1
+ """Claude Code, through claude-swap's own machinery.
2
+
3
+ Everything claude-swap does stays in the ``claude_swap`` package (slots, the
4
+ Keychain, locks shared with Claude Code, usage polling, auto-switch, session
5
+ mode). This adapter only maps it onto the provider interface. Claude accounts
6
+ live in claude-swap's backup root, so an existing claude-swap install's
7
+ accounts show up here unchanged.
8
+
9
+ Usage windows are Claude's ``five_hour`` and ``seven_day`` entries
10
+ (``utilization`` 0-100 and an ISO ``resets_at``), as ``oauth.py`` documents.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import io
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import tempfile
21
+ from datetime import datetime
22
+
23
+ from llmswap.model import AccountView, UsageReading, Window
24
+ from llmswap.providers.base import Provider, ProviderError, RunSpec, WarmOutcome, resolve_ref
25
+
26
+ _WINDOWS = (("five_hour", "5h", 18000), ("seven_day", "7d", 604800))
27
+
28
+
29
+ def _iso_epoch(value) -> float | None:
30
+ try:
31
+ return datetime.fromisoformat(value).timestamp()
32
+ except (TypeError, ValueError):
33
+ return None
34
+
35
+
36
+ def windows_from_usage(usage: dict | None) -> tuple[Window, ...]:
37
+ if not isinstance(usage, dict):
38
+ return ()
39
+ out = []
40
+ for key, short, seconds in _WINDOWS:
41
+ w = usage.get(key)
42
+ if not isinstance(w, dict):
43
+ continue
44
+ util = w.get("utilization")
45
+ out.append(
46
+ Window(
47
+ key=short,
48
+ used_pct=float(util) if util is not None else None,
49
+ resets_at=_iso_epoch(w.get("resets_at")),
50
+ seconds=seconds,
51
+ )
52
+ )
53
+ return tuple(out)
54
+
55
+
56
+ class ClaudeProvider(Provider):
57
+ id = "claude"
58
+ display = "Claude Code"
59
+ binary = "claude"
60
+ capabilities = frozenset({"switch", "run", "usage", "warm"})
61
+
62
+ def _switcher(self):
63
+ from claude_swap.switcher import ClaudeAccountSwitcher
64
+
65
+ return ClaudeAccountSwitcher()
66
+
67
+ def _snapshot(self, *, refresh: bool):
68
+ from claude_swap.snapshot_source import SnapshotSource
69
+
70
+ return SnapshotSource(self._switcher()).take(store_only=not refresh)
71
+
72
+ def accounts(self, *, refresh: bool = False) -> list[AccountView]:
73
+ try:
74
+ snap = self._snapshot(refresh=refresh)
75
+ except Exception:
76
+ return []
77
+ out = []
78
+ for acc in snap.accounts:
79
+ usage = acc.usage
80
+ note = usage.sentinel or ""
81
+ reading = UsageReading(
82
+ windows=windows_from_usage(usage.last_good),
83
+ fetched_at=usage.fetched_at,
84
+ error=usage.sentinel or usage.last_error,
85
+ )
86
+ from claude_swap import subscription
87
+
88
+ plan = subscription.plan_label(acc.subscription_plan) or ""
89
+ out.append(
90
+ AccountView(
91
+ provider=self.id,
92
+ number=str(acc.number),
93
+ email=acc.email,
94
+ plan=plan or acc.org_name,
95
+ alias=acc.alias,
96
+ active=acc.is_active,
97
+ disabled=acc.disabled,
98
+ kind=acc.kind,
99
+ usage=reading,
100
+ note=note,
101
+ )
102
+ )
103
+ return out
104
+
105
+ def refresh_usage(self, refs=None, *, force: bool = False) -> None:
106
+ with contextlib.suppress(Exception):
107
+ self._snapshot(refresh=True)
108
+
109
+ def _quiet(self, fn, *args, **kwargs):
110
+ buf = io.StringIO()
111
+ with contextlib.redirect_stdout(buf):
112
+ try:
113
+ return fn(*args, **kwargs)
114
+ except SystemExit as exc:
115
+ raise ProviderError(buf.getvalue().strip() or "claude-swap refused") from exc
116
+ except ProviderError:
117
+ raise
118
+ except Exception as exc:
119
+ raise ProviderError(str(exc) or exc.__class__.__name__) from exc
120
+
121
+ def add(self, *, slot: str | None = None) -> AccountView:
122
+ self._quiet(self._switcher().add_account, int(slot) if slot else None, True)
123
+ views = self.accounts()
124
+ return next((v for v in views if v.active), views[-1])
125
+
126
+ def login(self, *, slot: str | None = None, device: bool = False) -> AccountView:
127
+ self._quiet(self._switcher().login_account, slot)
128
+ views = self.accounts()
129
+ return views[-1]
130
+
131
+ def remove(self, ref: str) -> None:
132
+ self._quiet(self._switcher().remove_account, ref, True)
133
+
134
+ def switch(self, ref: str | None = None) -> AccountView:
135
+ sw = self._switcher()
136
+ self._quiet(sw.switch_to, ref) if ref else self._quiet(sw.switch)
137
+ return next((v for v in self.accounts() if v.active), None) or self.accounts()[0]
138
+
139
+ def run_spec(self, ref: str, args: list[str]) -> RunSpec:
140
+ raise ProviderError("claude runs through claude-swap's session mode; use run()")
141
+
142
+ def run(self, ref: str, args: list[str]) -> None:
143
+ from claude_swap import cli
144
+
145
+ cli._run_command([ref, "--", *args] if args else [ref])
146
+
147
+ def set_alias(self, ref: str, alias: str) -> None:
148
+ self._quiet(self._switcher().set_alias, ref, alias)
149
+
150
+ def set_disabled(self, ref: str, disabled: bool) -> None:
151
+ self._quiet(self._switcher().set_account_disabled, ref, disabled)
152
+
153
+ def warm(self, ref: str, *, prompt: str, model: str | None = None) -> WarmOutcome:
154
+ """Ping as ``ref`` through a session profile, so the live login stays put."""
155
+ from claude_swap.session import SessionManager
156
+
157
+ sw = self._switcher()
158
+ view = resolve_ref(self.accounts(), ref)
159
+ if view is None:
160
+ return WarmOutcome(False, "account not found")
161
+ if view.kind == "api_key":
162
+ return WarmOutcome(False, "api key account has no window")
163
+ env = dict(os.environ)
164
+ env.pop("ANTHROPIC_API_KEY", None)
165
+ if not view.active:
166
+ try:
167
+ session_dir, _, _ = self._quiet(SessionManager(sw).setup_session, view.number, False)
168
+ except ProviderError as exc:
169
+ return WarmOutcome(False, str(exc)[:120])
170
+ env["CLAUDE_CONFIG_DIR"] = str(session_dir)
171
+ argv = [
172
+ "claude", "-p", prompt, "--model", model or "haiku", "--output-format", "text",
173
+ "--no-session-persistence", "--disable-slash-commands",
174
+ ]
175
+ scratch = tempfile.mkdtemp(prefix="llmswap-warm-")
176
+ try:
177
+ proc = subprocess.run(
178
+ argv, env=env, cwd=scratch, stdin=subprocess.DEVNULL,
179
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180,
180
+ )
181
+ except FileNotFoundError:
182
+ return WarmOutcome(False, "`claude` not found")
183
+ except subprocess.TimeoutExpired:
184
+ return WarmOutcome(False, "timed out", ambiguous=True)
185
+ finally:
186
+ shutil.rmtree(scratch, ignore_errors=True)
187
+ return WarmOutcome(proc.returncode == 0, "ok" if proc.returncode == 0 else f"exit {proc.returncode}")
@@ -0,0 +1,274 @@
1
+ """OpenAI Codex CLI.
2
+
3
+ Evidence (Codex CLI 0.174.0 and the ``openai/codex`` source of 5 Dec 2026):
4
+
5
+ * The home is ``$CODEX_HOME`` or ``~/.codex``. With the default
6
+ ``cli_auth_credentials_store = "file"`` the login is ``<home>/auth.json``
7
+ (``AuthDotJson``: ``auth_mode``, ``OPENAI_API_KEY``, ``tokens{id_token,
8
+ access_token, refresh_token, account_id}``, ``last_refresh``). ``keyring`` and
9
+ ``auto`` keep it in the OS keyring instead, which llmswap cannot swap; such a
10
+ login is reported with a hint.
11
+ * The id token's claims carry the email and, under
12
+ ``https://api.openai.com/auth``, ``chatgpt_plan_type`` and
13
+ ``chatgpt_account_id``.
14
+ * Usage is ``GET https://chatgpt.com/backend-api/wham/usage`` with the access
15
+ token as bearer and ``ChatGPT-Account-Id``. ``rate_limit.primary_window`` and
16
+ ``secondary_window`` hold ``used_percent``, ``limit_window_seconds`` and
17
+ ``reset_at`` (epoch seconds); the window is 5 h or 7 d by its length.
18
+ * ``codex app-server`` (stdio JSON lines) answers ``account/rateLimits/read``
19
+ with the same numbers, and refreshes and saves the login itself. That is how
20
+ an idle account with an expired access token is read: Codex rotates its own
21
+ refresh token, llmswap never does.
22
+ * ``codex logout`` revokes the refresh token on the server, so llmswap never
23
+ runs it.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import queue
32
+ import subprocess
33
+ import threading
34
+ import time
35
+ import tomllib
36
+ from datetime import datetime
37
+ from pathlib import Path
38
+
39
+ from llmswap import __version__
40
+ from llmswap.httpjson import HttpFailure, get_json
41
+ from llmswap.jwt import claims
42
+ from llmswap.model import Identity, Window
43
+ from llmswap.providers.base import ProfileProvider, UsageError
44
+
45
+ USAGE_URL = "https://chatgpt.com/backend-api/wham/usage"
46
+ EXPIRY_SKEW_S = 120
47
+
48
+
49
+ def codex_home() -> Path:
50
+ env = os.environ.get("CODEX_HOME")
51
+ return Path(env) if env else Path.home() / ".codex"
52
+
53
+
54
+ def _read_auth(home: Path) -> dict | None:
55
+ try:
56
+ data = json.loads((home / "auth.json").read_text(encoding="utf-8"))
57
+ except (OSError, ValueError):
58
+ return None
59
+ return data if isinstance(data, dict) else None
60
+
61
+
62
+ COLD_SLACK_S = 90
63
+
64
+
65
+ def _window(used, seconds, reset_at, now: float) -> Window:
66
+ """A window as the account's usage shows it.
67
+
68
+ Codex reports a window nobody has started as 0% used with a reset a full
69
+ window away (ccswap documents the same reading). That is a cold window: no
70
+ ``resets_at``, so the next request is what starts it.
71
+ """
72
+ cold = (
73
+ used == 0
74
+ and seconds
75
+ and reset_at
76
+ and reset_at - now >= seconds - COLD_SLACK_S
77
+ )
78
+ return Window(
79
+ key=Window.key_for_seconds(seconds),
80
+ used_pct=float(used) if used is not None else None,
81
+ resets_at=None if cold or not reset_at else float(reset_at),
82
+ seconds=seconds,
83
+ )
84
+
85
+
86
+ def windows_from_payload(payload: dict, now: float | None = None) -> tuple[list[Window], str | None]:
87
+ """Turn a ``wham/usage`` payload into windows and the plan label."""
88
+ now = time.time() if now is None else now
89
+ out: list[Window] = []
90
+ limit = payload.get("rate_limit") or {}
91
+ for name in ("primary_window", "secondary_window"):
92
+ w = limit.get(name)
93
+ if not isinstance(w, dict):
94
+ continue
95
+ out.append(_window(w.get("used_percent"), w.get("limit_window_seconds"), w.get("reset_at"), now))
96
+ return out, payload.get("plan_type")
97
+
98
+
99
+ def windows_from_rpc(result: dict, now: float | None = None) -> list[Window]:
100
+ now = time.time() if now is None else now
101
+ snap = result.get("rateLimits") or {}
102
+ by_id = result.get("rateLimitsByLimitId") or {}
103
+ snap = by_id.get("codex") or snap
104
+ out = []
105
+ for name in ("primary", "secondary"):
106
+ w = snap.get(name)
107
+ if not isinstance(w, dict):
108
+ continue
109
+ mins = w.get("windowDurationMins")
110
+ out.append(_window(w.get("usedPercent"), mins * 60 if mins else None, w.get("resetsAt"), now))
111
+ return out
112
+
113
+
114
+ def rpc_rate_limits(home: Path, *, timeout: float = 25.0) -> dict:
115
+ """Ask a short-lived ``codex app-server`` for ``account/rateLimits/read``."""
116
+ env = dict(os.environ, CODEX_HOME=str(home))
117
+ try:
118
+ proc = subprocess.Popen(
119
+ ["codex", "-c", 'cli_auth_credentials_store="file"', "app-server"],
120
+ stdin=subprocess.PIPE,
121
+ stdout=subprocess.PIPE,
122
+ stderr=subprocess.DEVNULL,
123
+ text=True,
124
+ env=env,
125
+ )
126
+ except OSError:
127
+ raise UsageError("codex not installed") from None
128
+
129
+ def send(obj: dict) -> None:
130
+ assert proc.stdin
131
+ proc.stdin.write(json.dumps(obj) + "\n")
132
+ proc.stdin.flush()
133
+
134
+ lines: queue.Queue[str | None] = queue.Queue()
135
+
136
+ def pump() -> None: # a thread, because pipes cannot be select()ed on Windows
137
+ assert proc.stdout
138
+ for line in proc.stdout:
139
+ lines.put(line)
140
+ lines.put(None)
141
+
142
+ threading.Thread(target=pump, daemon=True).start()
143
+
144
+ def read_until(msg_id: int) -> dict:
145
+ deadline = time.monotonic() + timeout
146
+ while True:
147
+ try:
148
+ line = lines.get(timeout=max(0.0, deadline - time.monotonic()))
149
+ except queue.Empty:
150
+ raise UsageError("read failed") from None
151
+ if line is None:
152
+ raise UsageError("read failed")
153
+ try:
154
+ msg = json.loads(line)
155
+ except ValueError:
156
+ continue
157
+ if msg.get("id") == msg_id:
158
+ return msg
159
+
160
+ try:
161
+ send({"id": 1, "method": "initialize", "params": {"clientInfo": {"name": "llmswap", "title": "llmswap", "version": __version__}}})
162
+ read_until(1)
163
+ send({"method": "initialized"})
164
+ send({"id": 2, "method": "account/rateLimits/read"})
165
+ reply = read_until(2)
166
+ finally:
167
+ proc.kill()
168
+ proc.wait(timeout=5)
169
+ if "error" in reply:
170
+ raise UsageError("token expired")
171
+ return reply.get("result") or {}
172
+
173
+
174
+ class CodexProvider(ProfileProvider):
175
+ id = "codex"
176
+ display = "Codex"
177
+ binary = "codex"
178
+ capabilities = frozenset({"switch", "run", "usage", "warm"})
179
+ home_env = "CODEX_HOME"
180
+ override_env = ("OPENAI_API_KEY", "CODEX_API_KEY")
181
+ auth_files = ("auth.json",)
182
+ shared_entries = ("config.toml", "AGENTS.md", "AGENTS.override.md", "rules", "prompts", "skills")
183
+
184
+ def live_home(self) -> Path:
185
+ return codex_home()
186
+
187
+ def read_identity(self, home: Path) -> Identity | None:
188
+ auth = _read_auth(home)
189
+ if not auth:
190
+ return None
191
+ tokens = auth.get("tokens")
192
+ if isinstance(tokens, dict) and tokens.get("id_token"):
193
+ c = claims(tokens["id_token"])
194
+ auth_claims = c.get("https://api.openai.com/auth") or {}
195
+ profile = c.get("https://api.openai.com/profile") or {}
196
+ return Identity(
197
+ email=str(c.get("email") or profile.get("email") or ""),
198
+ account_id=str(tokens.get("account_id") or auth_claims.get("chatgpt_account_id") or ""),
199
+ plan=str(auth_claims.get("chatgpt_plan_type") or ""),
200
+ kind="oauth",
201
+ )
202
+ key = auth.get("OPENAI_API_KEY")
203
+ if key:
204
+ digest = hashlib.sha256(str(key).encode()).hexdigest()[:12]
205
+ return Identity(email="", account_id=f"key-{digest}", plan="api key", kind="api_key")
206
+ return None
207
+
208
+ def store_problem(self) -> str | None:
209
+ """Codex keeps its login in the OS keyring when `config.toml` says so; llmswap swaps files."""
210
+ try:
211
+ cfg = tomllib.loads((self.live_home() / "config.toml").read_text(encoding="utf-8"))
212
+ except (OSError, ValueError):
213
+ return None
214
+ mode = cfg.get("cli_auth_credentials_store")
215
+ if mode in ("keyring", "auto"):
216
+ return (
217
+ f'Codex is set to keep its login in the OS keyring (cli_auth_credentials_store = "{mode}" in '
218
+ f'{self.live_home() / "config.toml"}), so there is no auth.json for llmswap to save or swap. '
219
+ 'Set it to "file", run `codex login` again, then retry.'
220
+ )
221
+ return None
222
+
223
+ def freshness(self, home: Path) -> float:
224
+ auth = _read_auth(home) or {}
225
+ stamp = auth.get("last_refresh")
226
+ if isinstance(stamp, str):
227
+ try:
228
+ return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp()
229
+ except ValueError:
230
+ pass
231
+ return super().freshness(home)
232
+
233
+ def login_argv(self, *, device: bool) -> list[str]:
234
+ argv = ["codex", "-c", 'cli_auth_credentials_store="file"', "login"]
235
+ if device:
236
+ argv.append("--device-auth")
237
+ return argv
238
+
239
+ def run_spec(self, ref, args):
240
+ spec = super().run_spec(ref, args)
241
+ if spec.env: # a private home: force the file store so nothing lands in the keyring
242
+ spec.argv[1:1] = ["-c", 'cli_auth_credentials_store="file"']
243
+ return spec
244
+
245
+ def fetch_windows(self, home: Path, *, may_refresh: bool):
246
+ auth = _read_auth(home)
247
+ tokens = (auth or {}).get("tokens")
248
+ if not isinstance(tokens, dict) or not tokens.get("access_token"):
249
+ raise UsageError("no usage for api key" if (auth or {}).get("OPENAI_API_KEY") else "not signed in")
250
+ exp = claims(tokens["access_token"]).get("exp")
251
+ fresh = isinstance(exp, (int, float)) and exp > time.time() + EXPIRY_SKEW_S
252
+ if fresh:
253
+ headers = {"Authorization": f"Bearer {tokens['access_token']}"}
254
+ if tokens.get("account_id"):
255
+ headers["ChatGPT-Account-Id"] = str(tokens["account_id"])
256
+ try:
257
+ windows, plan = windows_from_payload(get_json(USAGE_URL, headers))
258
+ return windows, plan
259
+ except HttpFailure as exc:
260
+ if exc.status not in (401, 403):
261
+ raise UsageError(f"http {exc.status}" if exc.status else "network") from None
262
+ if not may_refresh:
263
+ raise UsageError("token expired")
264
+ return windows_from_rpc(rpc_rate_limits(home)), None
265
+
266
+ def warm_argv(self, prompt: str, model: str | None) -> list[str]:
267
+ argv = [
268
+ "codex", "-c", 'cli_auth_credentials_store="file"',
269
+ "-c", 'model_reasoning_effort="low"',
270
+ "exec", "--skip-git-repo-check", "--ephemeral", "-s", "read-only", "--color", "never",
271
+ ]
272
+ if model:
273
+ argv += ["-m", model]
274
+ return [*argv, prompt]
@@ -0,0 +1,80 @@
1
+ """Google Gemini CLI.
2
+
3
+ Evidence (Gemini CLI 0.72.0, read from its bundled source):
4
+
5
+ * ``GEMINI_CLI_HOME``, when set, replaces the user's home directory; the CLI
6
+ keeps its state in ``<home>/.gemini``. So an account's private home is a
7
+ directory that holds a ``.gemini`` folder.
8
+ * The OAuth login is kept in the OS keychain (service ``gemini-cli-oauth``) by
9
+ default, one entry for the whole machine, which cannot hold two accounts.
10
+ With ``GEMINI_FORCE_FILE_STORAGE=true`` it is kept instead in
11
+ ``<home>/.gemini/gemini-credentials.json``, AES-256-GCM encrypted with a key
12
+ derived from the host name and user name, so a copy only opens on the same
13
+ machine and user.
14
+ * ``<home>/.gemini/google_accounts.json`` is plain JSON and names the signed-in
15
+ account (``{"active": "<email>", "old": [...]}``).
16
+
17
+ Consequences: every llmswap Gemini account lives in a private home with file
18
+ storage forced, and is used with ``llmswap run gemini <account>``. The default
19
+ login sits in the keychain where llmswap does not write, so ``switch`` is not
20
+ offered. Gemini reports quota per model per day rather than in a 5-hour
21
+ window, so there is no window to warm.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ from pathlib import Path
29
+
30
+ from llmswap.model import Identity
31
+ from llmswap.providers.base import ProfileProvider
32
+
33
+
34
+ class GeminiProvider(ProfileProvider):
35
+ id = "gemini"
36
+ display = "Gemini CLI"
37
+ binary = "gemini"
38
+ capabilities = frozenset({"run"})
39
+ home_env = "GEMINI_CLI_HOME"
40
+ extra_env = {"GEMINI_FORCE_FILE_STORAGE": "true"}
41
+ override_env = ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GENAI_USE_VERTEXAI")
42
+ auth_files = (".gemini/gemini-credentials.json", ".gemini/google_accounts.json")
43
+ shared_entries = (".gemini/settings.json", ".gemini/GEMINI.md", ".gemini/commands", ".gemini/extensions")
44
+ switchable = False
45
+ opaque_files = (".gemini/gemini-credentials.json",)
46
+ login_hint = "Gemini opens its sign-in. Choose 'Login with Google', finish in the browser, then type /quit."
47
+
48
+ def live_home(self) -> Path:
49
+ env = os.environ.get("GEMINI_CLI_HOME")
50
+ return Path(env) if env else Path.home()
51
+
52
+ def read_identity(self, home: Path) -> Identity | None:
53
+ try:
54
+ data = json.loads((home / ".gemini" / "google_accounts.json").read_text(encoding="utf-8"))
55
+ except (OSError, ValueError):
56
+ return None
57
+ email = data.get("active") if isinstance(data, dict) else None
58
+ return Identity(email=str(email), kind="oauth") if email else None
59
+
60
+ def add(self, *, slot=None):
61
+ from llmswap.providers.base import ProviderError
62
+
63
+ raise ProviderError(
64
+ "Gemini CLI keeps its default login in the system keychain, which llmswap does not copy. "
65
+ "Use `llmswap gemini login` to sign in to an account; it is stored in its own home."
66
+ )
67
+
68
+ def login_argv(self, *, device: bool) -> list[str]:
69
+ # The CLI signs in on first start; `--prompt-interactive` is not needed
70
+ # because it opens the sign-in chooser when there is no login.
71
+ return ["gemini"]
72
+
73
+ def run_spec(self, ref, args):
74
+ spec = super().run_spec(ref, args)
75
+ spec.env.setdefault(self.home_env, str(self.store.home(self._resolve(ref).number)))
76
+ spec.env.update(self.extra_env)
77
+ return spec
78
+
79
+ def warm_argv(self, prompt, model):
80
+ raise NotImplementedError
@@ -0,0 +1,30 @@
1
+ """The providers llmswap knows. Adding one is one module plus one line here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from llmswap.providers.base import Provider, ProviderError
6
+
7
+
8
+ def _factories() -> dict[str, type[Provider]]:
9
+ from llmswap.providers.claude import ClaudeProvider
10
+ from llmswap.providers.codex import CodexProvider
11
+ from llmswap.providers.gemini import GeminiProvider
12
+
13
+ return {p.id: p for p in (ClaudeProvider, CodexProvider, GeminiProvider)}
14
+
15
+
16
+ def provider_ids() -> list[str]:
17
+ return list(_factories())
18
+
19
+
20
+ def get(provider_id: str) -> Provider:
21
+ try:
22
+ return _factories()[provider_id]()
23
+ except KeyError:
24
+ raise ProviderError(
25
+ f"unknown provider {provider_id!r}; choose one of: {', '.join(provider_ids())}"
26
+ ) from None
27
+
28
+
29
+ def all_providers() -> list[Provider]:
30
+ return [cls() for cls in _factories().values()]