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,619 @@
1
+ """The provider interface, and the generic implementation most providers share.
2
+
3
+ ``Provider`` is what every surface (CLI, TUI, menu bar, warm-up, rotation)
4
+ talks to. ``ProfileProvider`` implements it for a CLI whose login lives in
5
+ files under one home directory chosen by an environment variable: each account
6
+ gets a private home, and the default login is switched by swapping the login
7
+ files. A provider then only supplies facts about its CLI (the variable, which
8
+ files are the login, how to read the identity and the usage) and the commands
9
+ to sign in and to ping.
10
+
11
+ Rules this module holds for every provider built on it:
12
+
13
+ * The slot's home is the canonical copy of a login. The default home holds a
14
+ working copy that is captured back into the slot before another login
15
+ replaces it, because refresh tokens rotate and the working copy is the
16
+ newest one.
17
+ * A live login is written into a slot only when its identity matches that
18
+ slot. Anything else would overwrite another account's only refresh token.
19
+ * A login in the default home that matches no slot is never overwritten.
20
+ * Two processes never use one slot's login at once: ``llmswap run`` holds the
21
+ slot's lease for its whole life, and a switch, a ping or a usage read that
22
+ would touch the slot takes the lease too or gives up.
23
+ * A login file that cannot be read is treated as a login that may be someone's
24
+ only copy: it is not overwritten unless a saved slot holds identical bytes.
25
+ * Tokens are never printed or logged; only identities and short error codes.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import os
32
+ import shutil
33
+ import subprocess
34
+ import sys
35
+ import tempfile
36
+ import time
37
+ import uuid
38
+ from abc import ABC, abstractmethod
39
+ from concurrent.futures import ThreadPoolExecutor
40
+ from dataclasses import dataclass, field
41
+ from pathlib import Path
42
+
43
+ from claude_swap.fsutil import atomic_write_bytes
44
+
45
+ from llmswap.model import AccountView, Identity, UsageReading, Window
46
+ from llmswap.store import SlotRecord, SlotStore
47
+ from llmswap.usage_cache import UsageCache
48
+
49
+
50
+ class ProviderError(Exception):
51
+ """A failure the user can act on; the message is safe to print."""
52
+
53
+
54
+ class UsageError(ProviderError):
55
+ """A usage read failed. ``code`` is a short stable label, never a token."""
56
+
57
+ def __init__(self, code: str) -> None:
58
+ super().__init__(code)
59
+ self.code = code
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class RunSpec:
64
+ argv: list[str]
65
+ env: dict[str, str] = field(default_factory=dict)
66
+ unset: tuple[str, ...] = ()
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class WarmOutcome:
71
+ """``ambiguous`` means the request may have reached the provider (a timeout), so
72
+ the window may have started even though no success was seen."""
73
+
74
+ ok: bool
75
+ detail: str = ""
76
+ ambiguous: bool = False
77
+
78
+
79
+ class Provider(ABC):
80
+ id: str
81
+ display: str
82
+ binary: str
83
+ #: Subset of {"switch", "run", "usage", "warm"}.
84
+ capabilities: frozenset[str] = frozenset()
85
+
86
+ def installed(self) -> bool:
87
+ return shutil.which(self.binary) is not None
88
+
89
+ @abstractmethod
90
+ def accounts(self, *, refresh: bool = False) -> list[AccountView]: ...
91
+
92
+ @abstractmethod
93
+ def add(self, *, slot: str | None = None) -> AccountView:
94
+ """Save the login the CLI is signed in with now."""
95
+
96
+ @abstractmethod
97
+ def login(self, *, slot: str | None = None, device: bool = False) -> AccountView:
98
+ """Sign in to another account without disturbing the default login."""
99
+
100
+ @abstractmethod
101
+ def remove(self, ref: str) -> None: ...
102
+
103
+ @abstractmethod
104
+ def switch(self, ref: str | None = None) -> AccountView:
105
+ """Make ``ref`` (or the next account) the default login."""
106
+
107
+ def running_sessions(self) -> int:
108
+ """Processes of this CLI that may hold the default login in memory (0 when unknown)."""
109
+ return 0
110
+
111
+ @abstractmethod
112
+ def run_spec(self, ref: str, args: list[str]) -> RunSpec: ...
113
+
114
+ @abstractmethod
115
+ def run(self, ref: str, args: list[str]) -> None:
116
+ """Run the CLI as ``ref`` in this terminal and exit with its status."""
117
+
118
+ @abstractmethod
119
+ def set_alias(self, ref: str, alias: str) -> None: ...
120
+
121
+ @abstractmethod
122
+ def set_disabled(self, ref: str, disabled: bool) -> None: ...
123
+
124
+ @abstractmethod
125
+ def warm(self, ref: str, *, prompt: str, model: str | None = None) -> WarmOutcome:
126
+ """Send the smallest request through the CLI as ``ref``."""
127
+
128
+ def refresh_usage(self, refs: list[str] | None = None, *, force: bool = False) -> None:
129
+ """Read usage from the network for the accounts that are due."""
130
+
131
+ def find(self, ref: str) -> AccountView:
132
+ views = self.accounts()
133
+ hit = resolve_ref(views, ref)
134
+ if hit is None:
135
+ raise ProviderError(f"no {self.display} account matches {ref!r}")
136
+ return hit
137
+
138
+
139
+ def resolve_ref(views: list[AccountView], ref: str) -> AccountView | None:
140
+ """Match a slot number, an alias or an email (case-insensitive)."""
141
+ ref_l = ref.strip().lower()
142
+ for v in views:
143
+ if v.number == ref_l or (v.alias and v.alias.lower() == ref_l) or (
144
+ v.email and v.email.lower() == ref_l
145
+ ):
146
+ return v
147
+ return None
148
+
149
+
150
+ class ProfileProvider(Provider):
151
+ """A provider whose login is files under a home chosen by an env variable."""
152
+
153
+ home_env: str
154
+ extra_env: dict[str, str] = {}
155
+ #: Env variables that would override the file login; removed when running.
156
+ override_env: tuple[str, ...] = ()
157
+ #: Files (relative to a home) that together are the login.
158
+ auth_files: tuple[str, ...] = ()
159
+ #: Entries of the default home linked into a private home on ``run``.
160
+ shared_entries: tuple[str, ...] = ()
161
+ #: Whether the default login can be replaced by swapping ``auth_files``.
162
+ switchable: bool = True
163
+
164
+ def __init__(self, store: SlotStore | None = None) -> None:
165
+ self.store = store or SlotStore(self.id)
166
+ self.cache = UsageCache(self.store.base)
167
+
168
+ # -- facts about the CLI (override these) ------------------------------
169
+ @abstractmethod
170
+ def live_home(self) -> Path: ...
171
+
172
+ @abstractmethod
173
+ def read_identity(self, home: Path) -> Identity | None: ...
174
+
175
+ @abstractmethod
176
+ def login_argv(self, *, device: bool) -> list[str]: ...
177
+
178
+ def fetch_windows(
179
+ self, home: Path, *, may_refresh: bool
180
+ ) -> tuple[list[Window], str | None]:
181
+ """Read ``(windows, plan)`` for the login in ``home``; raise UsageError."""
182
+ raise UsageError("unsupported")
183
+
184
+ @abstractmethod
185
+ def warm_argv(self, prompt: str, model: str | None) -> list[str]: ...
186
+
187
+ def store_problem(self) -> str | None:
188
+ """Why the default login cannot be swapped as files, or None when it can."""
189
+ return None
190
+
191
+ def freshness(self, home: Path) -> float:
192
+ """How recent the login in ``home`` is (bigger is newer). The newest copy wins
193
+ when the live login is captured back into its slot."""
194
+ times = [(home / rel).stat().st_mtime for rel in self.auth_files if (home / rel).exists()]
195
+ return max(times, default=0.0)
196
+
197
+ #: Login files whose bytes are not JSON (encrypted by the CLI itself).
198
+ opaque_files: tuple[str, ...] = ()
199
+
200
+ # -- helpers -----------------------------------------------------------
201
+ def _env_for(self, home: Path) -> dict[str, str]:
202
+ env = {k: v for k, v in os.environ.items() if k not in self.override_env}
203
+ env[self.home_env] = str(home)
204
+ env.update(self.extra_env)
205
+ return env
206
+
207
+ def _auth_present(self, home: Path) -> bool:
208
+ return all((home / rel).is_file() for rel in self.auth_files)
209
+
210
+ def _copy_auth(self, src: Path, dst: Path) -> None:
211
+ """Copy the login files, each parsed first and published atomically.
212
+
213
+ The CLI may be writing a file as it is read; a truncated copy would
214
+ replace a good one, so a file that does not parse is read once more
215
+ and then refused.
216
+ """
217
+ blobs: dict[str, bytes] = {}
218
+ for rel in self.auth_files:
219
+ blobs[rel] = self._read_valid(src / rel, rel)
220
+ for rel, data in blobs.items():
221
+ target = dst / rel
222
+ target.parent.mkdir(parents=True, exist_ok=True)
223
+ atomic_write_bytes(target, data, mode=0o600)
224
+
225
+ def _read_valid(self, path: Path, rel: str) -> bytes:
226
+ for attempt in (1, 2):
227
+ data = path.read_bytes()
228
+ if rel in self.opaque_files or not rel.endswith(".json"):
229
+ return data
230
+ try:
231
+ json.loads(data)
232
+ return data
233
+ except ValueError:
234
+ if attempt == 1:
235
+ time.sleep(0.4)
236
+ raise ProviderError(f"{rel} is not readable right now (it may be mid-write); try again in a moment.")
237
+
238
+ def _same_bytes(self, a: Path, b: Path) -> bool:
239
+ try:
240
+ return all((a / rel).read_bytes() == (b / rel).read_bytes() for rel in self.auth_files)
241
+ except OSError:
242
+ return False
243
+
244
+ def _live_identity(self) -> Identity | None:
245
+ try:
246
+ return self.read_identity(self.live_home())
247
+ except Exception:
248
+ return None
249
+
250
+ def active_number(self) -> str | None:
251
+ live = self._live_identity()
252
+ if live is None:
253
+ return None
254
+ for rec in self.store.records():
255
+ if rec.identity.same_account(live):
256
+ return rec.number
257
+ return None
258
+
259
+ def _resolve(self, ref: str) -> SlotRecord:
260
+ ref_l = ref.strip().lower()
261
+ for rec in self.store.records():
262
+ if rec.number == ref_l or (rec.alias and rec.alias.lower() == ref_l) or (
263
+ rec.email and rec.email.lower() == ref_l
264
+ ):
265
+ return rec
266
+ raise ProviderError(f"no {self.display} account matches {ref!r}")
267
+
268
+ def _view(self, rec: SlotRecord, active: str | None) -> AccountView:
269
+ reading = self.cache.get(rec.number) or UsageReading()
270
+ note = ""
271
+ if reading.error:
272
+ note = reading.error
273
+ elif rec.kind == "api_key":
274
+ note = "api key (no subscription usage)"
275
+ return AccountView(
276
+ provider=self.id,
277
+ number=rec.number,
278
+ email=rec.email,
279
+ plan=rec.plan,
280
+ alias=rec.alias,
281
+ active=rec.number == active,
282
+ disabled=rec.disabled,
283
+ kind=rec.kind,
284
+ usage=reading,
285
+ note=note,
286
+ )
287
+
288
+ # -- Provider ----------------------------------------------------------
289
+ def accounts(self, *, refresh: bool = False) -> list[AccountView]:
290
+ if refresh:
291
+ self.refresh_usage()
292
+ active = self.active_number()
293
+ return [self._view(r, active) for r in self.store.records()]
294
+
295
+ def _store_login(self, src_home: Path, ident: Identity, slot: str | None) -> SlotRecord:
296
+ with self.store.lock():
297
+ rec = None
298
+ if slot:
299
+ rec = self._resolve(slot)
300
+ else:
301
+ rec = next(
302
+ (r for r in self.store.records() if r.identity.same_account(ident)),
303
+ None,
304
+ )
305
+ if rec is None:
306
+ rec = SlotRecord(number=self.store.next_number())
307
+ elif slot and not rec.identity.same_account(ident) and rec.email:
308
+ raise ProviderError(
309
+ f"slot {rec.number} holds {rec.email}; this login is {ident.email or 'another account'}. "
310
+ "Add it without --slot, or remove the slot first."
311
+ )
312
+ self._copy_auth(src_home, self.store.home(rec.number))
313
+ rec.email = ident.email or rec.email
314
+ rec.account_id = ident.account_id or rec.account_id
315
+ rec.plan = ident.plan or rec.plan
316
+ rec.kind = ident.kind
317
+ self.store.put(rec)
318
+ return rec
319
+
320
+ def add(self, *, slot: str | None = None) -> AccountView:
321
+ live = self.live_home()
322
+ problem = self.store_problem()
323
+ if problem:
324
+ raise ProviderError(problem)
325
+ ident = self.read_identity(live)
326
+ if ident is None or not self._auth_present(live):
327
+ raise ProviderError(
328
+ f"{self.display} is not signed in. Sign in with `{self.binary}` first, "
329
+ f"or use `llmswap {self.id} login` to sign in to a new account."
330
+ )
331
+ rec = self._store_login(live, ident, slot)
332
+ self.cache.forget(rec.number)
333
+ return self._view(rec, self.active_number())
334
+
335
+ def login(self, *, slot: str | None = None, device: bool = False) -> AccountView:
336
+ if not self.installed():
337
+ raise ProviderError(f"`{self.binary}` is not installed or not on PATH.")
338
+ scratch_root = self.store.base / "signin"
339
+ scratch_root.mkdir(parents=True, exist_ok=True)
340
+ scratch = scratch_root / uuid.uuid4().hex[:12] / "home"
341
+ scratch.mkdir(parents=True, mode=0o700)
342
+ try:
343
+ code = subprocess.call(
344
+ self.login_argv(device=device), env=self._env_for(scratch)
345
+ )
346
+ ident = self.read_identity(scratch) if code == 0 else None
347
+ if ident is None or not self._auth_present(scratch):
348
+ raise ProviderError(f"{self.display} sign-in did not complete.")
349
+ rec = self._store_login(scratch, ident, slot)
350
+ live = self._live_identity()
351
+ if live is not None and live.same_account(ident):
352
+ # The default login is this account: give it the new login so
353
+ # the two copies of one account do not drift apart.
354
+ self._copy_auth(scratch, self.live_home())
355
+ self.cache.forget(rec.number)
356
+ return self._view(rec, self.active_number())
357
+ finally:
358
+ shutil.rmtree(scratch.parent, ignore_errors=True)
359
+
360
+ def remove(self, ref: str) -> None:
361
+ with self.store.lock():
362
+ rec = self._resolve(ref)
363
+ # A running session has this slot's home as its working login; moving
364
+ # it away underneath would strand the session.
365
+ lease = self.store.lease(rec.number)
366
+ if not lease.acquire(timeout=0):
367
+ self._busy(rec)
368
+ try:
369
+ self.store.drop(rec.number)
370
+ finally:
371
+ lease.release()
372
+ self.cache.forget(rec.number)
373
+
374
+ def running_sessions(self) -> int:
375
+ """How many processes named like this CLI are running (0 when it cannot tell).
376
+
377
+ A running CLI holds its login in memory and may write a refreshed token
378
+ over the file a switch just replaced. It cannot tell whether the process
379
+ uses the default login or a ``llmswap run`` slot, so the count is a hint.
380
+ """
381
+ try:
382
+ if sys.platform == "win32":
383
+ out = subprocess.run(
384
+ ["tasklist", "/FI", f"IMAGENAME eq {self.binary}.exe", "/NH"],
385
+ capture_output=True, text=True, timeout=5,
386
+ ).stdout
387
+ return out.lower().count(f"{self.binary}.exe")
388
+ out = subprocess.run(["pgrep", "-x", self.binary], capture_output=True, text=True, timeout=5).stdout
389
+ return len([ln for ln in out.split() if ln.isdigit() and int(ln) != os.getpid()])
390
+ except (OSError, subprocess.SubprocessError):
391
+ return 0
392
+
393
+ def _capture_live(self) -> str | None:
394
+ """Copy the live login back into the slot that owns it, if the live copy is the newer."""
395
+ live = self._live_identity()
396
+ if live is None:
397
+ return None
398
+ for rec in self.store.records():
399
+ if rec.identity.same_account(live):
400
+ slot_home = self.store.home(rec.number)
401
+ if not self._auth_present(slot_home) or self.freshness(self.live_home()) >= self.freshness(slot_home):
402
+ self._copy_auth(self.live_home(), slot_home)
403
+ return rec.number
404
+ return None
405
+
406
+ def switch(self, ref: str | None = None) -> AccountView:
407
+ if not self.switchable:
408
+ raise ProviderError(
409
+ f"{self.display} keeps its default login where llmswap cannot swap it. "
410
+ f"Use `llmswap run {self.id}:<account>` to run as an account."
411
+ )
412
+ problem = self.store_problem()
413
+ if problem:
414
+ raise ProviderError(problem)
415
+ with self.store.lock():
416
+ records = [r for r in self.store.records() if not r.disabled or ref]
417
+ if not records:
418
+ raise ProviderError(f"no {self.display} accounts saved. Run `llmswap {self.id} add`.")
419
+ live = self._live_identity()
420
+ owner = self.active_number()
421
+ if owner is None and self._auth_present(self.live_home()):
422
+ if live is not None:
423
+ raise ProviderError(
424
+ f"{self.display} is signed in as {live.email or 'an account'} that llmswap has not saved. "
425
+ f"Run `llmswap {self.id} add` first so this login is not lost."
426
+ )
427
+ if not any(self._same_bytes(self.live_home(), self.store.home(r.number)) for r in self.store.records()):
428
+ raise ProviderError(
429
+ f"The {self.display} login file cannot be read, and no saved account holds a copy of it, "
430
+ "so it was left alone. Sign in again or restore it, then retry."
431
+ )
432
+ if ref is None:
433
+ nums = [r.number for r in records]
434
+ after = nums.index(owner) + 1 if owner in nums else 0
435
+ target = records[after % len(records)]
436
+ else:
437
+ target = self._resolve(ref)
438
+ if owner == target.number:
439
+ return self._view(target, owner)
440
+ lease = self.store.lease(target.number)
441
+ if not lease.acquire(timeout=0):
442
+ self._busy(target)
443
+ try:
444
+ if owner is not None:
445
+ self._capture_live()
446
+ slot_home = self.store.home(target.number)
447
+ if not self._auth_present(slot_home):
448
+ raise ProviderError(f"slot {target.number} has no saved login; sign in again with `llmswap {self.id} login --slot {target.number}`.")
449
+ self._copy_auth(slot_home, self.live_home())
450
+ self.store.set_active(target.number)
451
+ finally:
452
+ lease.release()
453
+ return self._view(target, target.number)
454
+
455
+ def _busy(self, rec: SlotRecord):
456
+ raise ProviderError(
457
+ f"{self.display} account {rec.number} is in use by a running `llmswap run` session (or a ping). "
458
+ "Close it first: two copies of one login would fight over its refresh token."
459
+ )
460
+
461
+ def _link_shared(self, home: Path) -> None:
462
+ live = self.live_home()
463
+ for name in self.shared_entries:
464
+ src, dst = live / name, home / name
465
+ if not src.exists() or dst.exists() or dst.is_symlink():
466
+ continue
467
+ try:
468
+ dst.symlink_to(src, target_is_directory=src.is_dir())
469
+ except OSError:
470
+ if src.is_file():
471
+ shutil.copy2(src, dst)
472
+
473
+ def run_spec(self, ref: str, args: list[str]) -> RunSpec:
474
+ rec = self._resolve(ref)
475
+ if rec.number == self.active_number():
476
+ return RunSpec(argv=[self.binary, *args])
477
+ home = self.store.home(rec.number)
478
+ if not self._auth_present(home):
479
+ raise ProviderError(f"slot {rec.number} has no saved login.")
480
+ home.mkdir(parents=True, exist_ok=True)
481
+ self._link_shared(home)
482
+ return RunSpec(
483
+ argv=[self.binary, *args],
484
+ env={self.home_env: str(home), **self.extra_env},
485
+ unset=self.override_env,
486
+ )
487
+
488
+ def run(self, ref: str, args: list[str]) -> None:
489
+ """Run the CLI as ``ref`` and exit with its status.
490
+
491
+ The CLI runs as a child so the slot's lease is held for as long as it
492
+ lives. The default login's account runs plain, with no lease.
493
+ """
494
+ spec = self.run_spec(ref, args)
495
+ env = {k: v for k, v in os.environ.items() if k not in spec.unset}
496
+ env.update(spec.env)
497
+ exe = shutil.which(spec.argv[0], path=env.get("PATH")) or spec.argv[0]
498
+ lease = None
499
+ if spec.env:
500
+ rec = self._resolve(ref)
501
+ lease = self.store.lease(rec.number)
502
+ if not lease.acquire(timeout=0):
503
+ self._busy(rec)
504
+ try:
505
+ code = subprocess.call([exe, *spec.argv[1:]], env=env)
506
+ except KeyboardInterrupt:
507
+ code = 130
508
+ finally:
509
+ if lease is not None:
510
+ lease.release()
511
+ raise SystemExit(code)
512
+
513
+ def set_alias(self, ref: str, alias: str) -> None:
514
+ with self.store.lock():
515
+ rec = self._resolve(ref)
516
+ clash = [r for r in self.store.records() if r.number != rec.number and alias and r.alias.lower() == alias.lower()]
517
+ if clash:
518
+ raise ProviderError(f"alias {alias!r} is already used by slot {clash[0].number}")
519
+ rec.alias = alias
520
+ self.store.put(rec)
521
+
522
+ def set_disabled(self, ref: str, disabled: bool) -> None:
523
+ with self.store.lock():
524
+ rec = self._resolve(ref)
525
+ rec.disabled = disabled
526
+ self.store.put(rec)
527
+
528
+ # -- usage -------------------------------------------------------------
529
+ def _read_one(self, rec: SlotRecord, active: str | None) -> UsageReading:
530
+ previous = self.cache.get(rec.number)
531
+ if rec.kind == "api_key":
532
+ return UsageReading(error=None, fetched_at=time.time())
533
+ is_active = rec.number == active
534
+ home = self.live_home() if is_active else self.store.home(rec.number)
535
+ lease = None if is_active else self.store.lease(rec.number)
536
+ if lease is not None and not lease.acquire(timeout=0):
537
+ kept = previous.windows if previous else ()
538
+ return UsageReading(windows=kept, fetched_at=previous.fetched_at if previous else None, error="in use")
539
+ try:
540
+ windows, plan = self.fetch_windows(home, may_refresh=not is_active)
541
+ except UsageError as exc:
542
+ kept = previous.windows if previous else ()
543
+ return UsageReading(windows=kept, fetched_at=previous.fetched_at if previous else None, error=exc.code)
544
+ except Exception:
545
+ kept = previous.windows if previous else ()
546
+ return UsageReading(windows=kept, fetched_at=previous.fetched_at if previous else None, error="read failed")
547
+ finally:
548
+ if lease is not None:
549
+ lease.release()
550
+ if plan and plan != rec.plan:
551
+ rec.plan = plan
552
+ self.store.put(rec)
553
+ return UsageReading(windows=tuple(windows), fetched_at=time.time())
554
+
555
+ def refresh_usage(self, refs: list[str] | None = None, *, force: bool = False) -> None:
556
+ if "usage" not in self.capabilities:
557
+ return
558
+ active = self.active_number()
559
+ wanted = [self._resolve(r) for r in refs] if refs else self.store.records()
560
+ todo = [r for r in wanted if force or self.cache.due(r.number)]
561
+ if not todo:
562
+ return
563
+
564
+ def work(rec: SlotRecord) -> None:
565
+ reading = self._read_one(rec, active)
566
+ self.cache.put(rec.number, reading)
567
+
568
+ with ThreadPoolExecutor(max_workers=min(4, len(todo))) as pool:
569
+ list(pool.map(work, todo))
570
+
571
+ # -- warm-up -----------------------------------------------------------
572
+ def warm(self, ref: str, *, prompt: str, model: str | None = None) -> WarmOutcome:
573
+ if "warm" not in self.capabilities:
574
+ return WarmOutcome(False, "warm-up is not supported for this provider")
575
+ rec = self._resolve(ref)
576
+ spec = self.run_spec(rec.number, [])
577
+ lease = self.store.lease(rec.number) if spec.env else None
578
+ if lease is not None and not lease.acquire(timeout=0):
579
+ return WarmOutcome(False, "account is in use by a running session")
580
+ try:
581
+ return self._ping(spec, prompt, model)
582
+ finally:
583
+ if lease is not None:
584
+ lease.release()
585
+
586
+ def _ping(self, spec: RunSpec, prompt: str, model: str | None) -> WarmOutcome:
587
+ argv = self.warm_argv(prompt, model)
588
+ env = {k: v for k, v in os.environ.items() if k not in spec.unset}
589
+ env.update(spec.env)
590
+ scratch = tempfile.mkdtemp(prefix="llmswap-warm-")
591
+ try:
592
+ proc = subprocess.run(
593
+ argv,
594
+ env=env,
595
+ cwd=scratch,
596
+ stdin=subprocess.DEVNULL,
597
+ stdout=subprocess.PIPE,
598
+ stderr=subprocess.PIPE,
599
+ timeout=180,
600
+ )
601
+ except FileNotFoundError:
602
+ return WarmOutcome(False, f"`{self.binary}` not found")
603
+ except subprocess.TimeoutExpired:
604
+ return WarmOutcome(False, "timed out", ambiguous=True)
605
+ finally:
606
+ shutil.rmtree(scratch, ignore_errors=True)
607
+ if proc.returncode == 0:
608
+ return WarmOutcome(True, "ok")
609
+ return WarmOutcome(False, f"exit {proc.returncode}")
610
+
611
+
612
+ def exec_spec(spec: RunSpec) -> None:
613
+ """Replace this process with the CLI (POSIX) or run it and exit (Windows)."""
614
+ env = {k: v for k, v in os.environ.items() if k not in spec.unset}
615
+ env.update(spec.env)
616
+ exe = shutil.which(spec.argv[0], path=env.get("PATH")) or spec.argv[0]
617
+ if sys.platform == "win32":
618
+ raise SystemExit(subprocess.call([exe, *spec.argv[1:]], env=env))
619
+ os.execvpe(exe, [exe, *spec.argv[1:]], env)