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
llmswap/render.py ADDED
@@ -0,0 +1,127 @@
1
+ """Text layout of the account list: bars on a terminal, plain text when piped."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import shutil
7
+ import sys
8
+ import time
9
+
10
+ from rich.console import Console
11
+ from rich.text import Text
12
+
13
+ from claude_swap import printer
14
+ from claude_swap.usage_bars import Palette, bar_cells
15
+
16
+ from llmswap.model import AccountView, Window
17
+
18
+
19
+ def countdown(seconds: float) -> str:
20
+ seconds = max(0, int(seconds))
21
+ d, rem = divmod(seconds, 86400)
22
+ h, rem = divmod(rem, 3600)
23
+ m = rem // 60
24
+ if d:
25
+ return f"{d}d {h}h"
26
+ if h:
27
+ return f"{h}h {m:02d}m"
28
+ return f"{m}m"
29
+
30
+
31
+ def window_text(w: Window, now: float) -> str:
32
+ pct = w.effective_pct(now)
33
+ figure = "?" if pct is None else f"{pct:.0f}%"
34
+ if w.resets_at is None:
35
+ tail = "idle (starts on first use)"
36
+ elif w.passed(now):
37
+ tail = "reset"
38
+ else:
39
+ tail = f"resets in {countdown(w.resets_at - now)}"
40
+ return f"{w.key:>4} {figure:>4} {tail}"
41
+
42
+
43
+ def header(v: AccountView) -> str:
44
+ bits = [v.number, v.alias or v.email or "(no email)"]
45
+ if v.alias and v.email:
46
+ bits.append(f"<{v.email}>")
47
+ if v.plan:
48
+ bits.append(f"[{v.plan}]")
49
+ if v.active:
50
+ bits.append("* active")
51
+ if v.disabled:
52
+ bits.append("(disabled)")
53
+ return " ".join(bits)
54
+
55
+
56
+ def render_plain(groups: list[tuple[str, list[AccountView], bool]], now: float | None = None) -> str:
57
+ now = time.time() if now is None else now
58
+ lines: list[str] = []
59
+ for display, views, installed in groups:
60
+ suffix = "" if installed else " (not installed)"
61
+ lines.append(f"{display}{suffix}")
62
+ if not views:
63
+ lines.append(" no accounts saved")
64
+ for v in views:
65
+ lines.append(" " + header(v))
66
+ for w in v.usage.windows:
67
+ lines.append(" " + window_text(w, now))
68
+ if v.note and not v.usage.windows:
69
+ lines.append(f" {v.note}")
70
+ elif v.note and v.usage.error:
71
+ lines.append(f" ! {v.note}")
72
+ lines.append("")
73
+ return "\n".join(lines).rstrip() + "\n"
74
+
75
+
76
+ def account_text(v: AccountView, now: float, bar_w: int = 24, pal: Palette = Palette.DARK) -> Text:
77
+ """One account as Rich text: a header line, then a bar per window."""
78
+ out = Text()
79
+ out.append(" ")
80
+ out.append(v.number, style=f"bold {pal.accent}")
81
+ out.append(" " + (v.alias or v.email or "(no email)"), style="bold" if v.active else "")
82
+ if v.alias and v.email:
83
+ out.append(f" <{v.email}>", style=pal.muted)
84
+ if v.plan:
85
+ out.append(f" [{v.plan}]", style=pal.info)
86
+ if v.active:
87
+ out.append(" ● active", style=pal.sev_ok)
88
+ if v.disabled:
89
+ out.append(" (disabled)", style=pal.muted)
90
+ out.append("\n")
91
+ for w in v.usage.windows:
92
+ pct = w.effective_pct(now)
93
+ out.append(f" {w.key:>4} ", style=pal.muted)
94
+ out.append_text(bar_cells(pct, bar_w, palette=pal))
95
+ out.append(f" {'?' if pct is None else f'{pct:.0f}%':>4}", style=pal.severity(pct))
96
+ tail = "idle" if w.resets_at is None else ("reset" if w.passed(now) else f"resets in {countdown(w.resets_at - now)}")
97
+ out.append(f" {tail}\n", style=pal.muted)
98
+ if v.note and (v.usage.error or not v.usage.windows):
99
+ out.append(f" {v.note}\n", style=pal.sev_warn if v.usage.error else pal.muted)
100
+ return out
101
+
102
+
103
+ def render_rich(groups: list[tuple[str, list[AccountView], bool]], now: float | None = None) -> str:
104
+ now = time.time() if now is None else now
105
+ pal = Palette.DARK
106
+ out = Text()
107
+ width = min(shutil.get_terminal_size((100, 24)).columns, 110)
108
+ bar_w = max(12, min(30, width - 50))
109
+ for display, views, installed in groups:
110
+ out.append(display, style=f"bold {pal.accent}")
111
+ if not installed:
112
+ out.append(" (not installed)", style=pal.muted)
113
+ out.append("\n")
114
+ if not views:
115
+ out.append(" no accounts saved\n", style=pal.muted)
116
+ for v in views:
117
+ out.append_text(account_text(v, now, bar_w, pal))
118
+ out.append("\n")
119
+ buf = io.StringIO()
120
+ Console(file=buf, force_terminal=printer.colors_enabled(), width=width, color_system="truecolor" if printer.colors_enabled() else None, highlight=False).print(out, end="")
121
+ return buf.getvalue().rstrip() + "\n"
122
+
123
+
124
+ def render(groups, now: float | None = None) -> str:
125
+ if sys.stdout.isatty():
126
+ return render_rich(groups, now)
127
+ return render_plain(groups, now)
llmswap/rotate.py ADDED
@@ -0,0 +1,102 @@
1
+ """Rotate to another account before the active one hits a limit.
2
+
3
+ Claude Code keeps claude-swap's auto-switch engine (``claude_swap.autoswitch``),
4
+ which knows its Keychain, session and cooldown rules. Every other switchable
5
+ provider uses the simple rule here: when the active account's fullest window
6
+ reaches the threshold, move to the account with the most headroom, skipping
7
+ disabled accounts, API-key accounts and any account that is itself at the
8
+ threshold. A cooldown stops two accounts bouncing.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import time
15
+ from dataclasses import dataclass
16
+
17
+ from claude_swap.fsutil import atomic_write_text
18
+
19
+ from llmswap.model import AccountView
20
+ from llmswap.providers.base import ProfileProvider, Provider
21
+
22
+ DEFAULT_THRESHOLD = 90.0
23
+ DEFAULT_COOLDOWN_S = 300.0
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class TickResult:
28
+ provider: str
29
+ action: str # "idle" | "switched" | "would-switch" | "skipped"
30
+ detail: str = ""
31
+ target: str | None = None
32
+
33
+
34
+ def pick_target(
35
+ views: list[AccountView], *, threshold: float, now: float | None = None
36
+ ) -> AccountView | None:
37
+ """The best account to move to, or None when none has room."""
38
+ now = time.time() if now is None else now
39
+ best: tuple[tuple[int, float, int], AccountView] | None = None
40
+ for v in views:
41
+ if v.active or v.disabled or v.kind != "oauth":
42
+ continue
43
+ worst = v.usage.worst_pct(now)
44
+ if worst is not None and worst >= threshold:
45
+ continue
46
+ # Known headroom beats unknown; among known, the emptiest wins.
47
+ key = (0 if worst is not None else 1, worst if worst is not None else 0.0, int(v.number))
48
+ if best is None or key < best[0]:
49
+ best = (key, v)
50
+ return best[1] if best else None
51
+
52
+
53
+ def _state_path(provider: Provider):
54
+ from llmswap import paths
55
+
56
+ return paths.provider_dir(provider.id) / "auto_state.json"
57
+
58
+
59
+ def _last_switch(provider: Provider) -> float:
60
+ try:
61
+ return float(json.loads(_state_path(provider).read_text())["last_switch"])
62
+ except (OSError, ValueError, KeyError):
63
+ return 0.0
64
+
65
+
66
+ def _record_switch(provider: Provider, now: float) -> None:
67
+ path = _state_path(provider)
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ atomic_write_text(path, json.dumps({"last_switch": now}))
70
+
71
+
72
+ def tick(
73
+ provider: Provider,
74
+ *,
75
+ threshold: float = DEFAULT_THRESHOLD,
76
+ cooldown_s: float = DEFAULT_COOLDOWN_S,
77
+ dry_run: bool = False,
78
+ now: float | None = None,
79
+ ) -> TickResult:
80
+ now = time.time() if now is None else now
81
+ if not isinstance(provider, ProfileProvider) or "switch" not in provider.capabilities:
82
+ return TickResult(provider.id, "skipped", "this provider rotates through its own engine or cannot switch")
83
+ provider.refresh_usage()
84
+ views = provider.accounts()
85
+ active = next((v for v in views if v.active), None)
86
+ if active is None:
87
+ return TickResult(provider.id, "skipped", "the default login is not a saved account")
88
+ worst = active.usage.worst_pct(now)
89
+ if worst is None:
90
+ return TickResult(provider.id, "idle", f"no usage reading for {active.label}")
91
+ if worst < threshold:
92
+ return TickResult(provider.id, "idle", f"{active.label} is at {worst:.0f}%")
93
+ target = pick_target(views, threshold=threshold, now=now)
94
+ if target is None:
95
+ return TickResult(provider.id, "skipped", f"{active.label} is at {worst:.0f}% and no other account has room")
96
+ if now - _last_switch(provider) < cooldown_s:
97
+ return TickResult(provider.id, "skipped", "cooling down after the last switch")
98
+ if dry_run:
99
+ return TickResult(provider.id, "would-switch", f"{active.label} at {worst:.0f}%", target.number)
100
+ provider.switch(target.number)
101
+ _record_switch(provider, now)
102
+ return TickResult(provider.id, "switched", f"{active.label} at {worst:.0f}%", target.number)
llmswap/store.py ADDED
@@ -0,0 +1,138 @@
1
+ """Slot storage for providers that keep one private home per account.
2
+
3
+ Layout under ``<root>/<provider>/``::
4
+
5
+ sequence.json slot roster: identity, alias, flags, active slot
6
+ slots/<n>/home/ the account's private home for the provider CLI
7
+ usage.json last usage reading per slot (see usage_cache.py)
8
+ .lock one lock for roster changes and credential swaps
9
+
10
+ The slot's home is the canonical copy of its login. A live login copied into
11
+ the provider's default home is a working copy that is captured back into the
12
+ slot before anything overwrites it (see ``providers/base.py``).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import shutil
19
+ import time
20
+ from dataclasses import dataclass, field, asdict
21
+ from pathlib import Path
22
+
23
+ from claude_swap.fsutil import atomic_write_text
24
+ from claude_swap.locking import FileLock
25
+
26
+ from llmswap import paths
27
+ from llmswap.model import Identity
28
+
29
+
30
+ @dataclass
31
+ class SlotRecord:
32
+ number: str
33
+ email: str = ""
34
+ account_id: str = ""
35
+ plan: str = ""
36
+ kind: str = "oauth"
37
+ alias: str = ""
38
+ disabled: bool = False
39
+ added_at: float = field(default_factory=time.time)
40
+
41
+ @property
42
+ def identity(self) -> Identity:
43
+ return Identity(
44
+ email=self.email, account_id=self.account_id, plan=self.plan, kind=self.kind
45
+ )
46
+
47
+
48
+ class SlotStore:
49
+ def __init__(self, provider_id: str, base: Path | None = None) -> None:
50
+ self.base = base or paths.provider_dir(provider_id)
51
+
52
+ # -- layout ---------------------------------------------------------
53
+ @property
54
+ def sequence_path(self) -> Path:
55
+ return self.base / "sequence.json"
56
+
57
+ def slot_dir(self, number: str) -> Path:
58
+ return self.base / "slots" / str(number)
59
+
60
+ def home(self, number: str) -> Path:
61
+ return self.slot_dir(number) / "home"
62
+
63
+ def lock(self, timeout: float = 15.0) -> FileLock:
64
+ return FileLock(self.base / ".lock", timeout=timeout)
65
+
66
+ def lease(self, number: str, timeout: float = 0.0) -> FileLock:
67
+ """The right to use a slot's private home.
68
+
69
+ One login has one refresh token that rotates, so two processes must not
70
+ run on the same slot's home at once. A ``llmswap run`` session holds the
71
+ lease for its whole life; a switch, a ping or a usage read that would
72
+ touch the slot's login takes it too, and gives up (``LockError``) when
73
+ it is held instead of racing.
74
+ """
75
+ # Outside the slot's folder: a removal moves that folder, and Windows
76
+ # will not move a folder that holds a locked file.
77
+ return FileLock(self.base / "leases" / f"{number}.lease", timeout=timeout)
78
+
79
+ # -- roster ---------------------------------------------------------
80
+ def load(self) -> dict:
81
+ try:
82
+ data = json.loads(self.sequence_path.read_text(encoding="utf-8"))
83
+ except (OSError, ValueError):
84
+ data = {}
85
+ data.setdefault("version", 1)
86
+ data.setdefault("accounts", {})
87
+ data.setdefault("active", None)
88
+ return data
89
+
90
+ def save(self, data: dict) -> None:
91
+ self.base.mkdir(parents=True, exist_ok=True)
92
+ atomic_write_text(self.sequence_path, json.dumps(data, indent=2, sort_keys=True))
93
+
94
+ def records(self) -> list[SlotRecord]:
95
+ data = self.load()
96
+ out = []
97
+ for num, rec in data["accounts"].items():
98
+ out.append(SlotRecord(number=num, **{k: v for k, v in rec.items() if k in _FIELDS}))
99
+ return sorted(out, key=lambda r: int(r.number))
100
+
101
+ def get(self, number: str) -> SlotRecord | None:
102
+ return next((r for r in self.records() if r.number == str(number)), None)
103
+
104
+ def put(self, rec: SlotRecord) -> None:
105
+ data = self.load()
106
+ body = asdict(rec)
107
+ body.pop("number")
108
+ data["accounts"][rec.number] = body
109
+ self.save(data)
110
+
111
+ def next_number(self) -> str:
112
+ used = [int(r.number) for r in self.records()]
113
+ return str(max(used, default=0) + 1)
114
+
115
+ def drop(self, number: str) -> None:
116
+ data = self.load()
117
+ data["accounts"].pop(str(number), None)
118
+ if data.get("active") == str(number):
119
+ data["active"] = None
120
+ self.save(data)
121
+ # A login made with `llmswap login` exists only in its slot, so a removal
122
+ # moves it aside instead of deleting it.
123
+ src = self.slot_dir(number)
124
+ if src.exists():
125
+ dest = self.base / "removed" / f"{number}-{int(time.time())}"
126
+ dest.parent.mkdir(parents=True, exist_ok=True)
127
+ shutil.move(str(src), str(dest))
128
+
129
+ def set_active(self, number: str | None) -> None:
130
+ data = self.load()
131
+ data["active"] = number
132
+ self.save(data)
133
+
134
+ def active(self) -> str | None:
135
+ return self.load().get("active")
136
+
137
+
138
+ _FIELDS = {"email", "account_id", "plan", "kind", "alias", "disabled", "added_at"}
llmswap/tui.py ADDED
@@ -0,0 +1,182 @@
1
+ """The unified dashboard: every provider's accounts and usage in one screen.
2
+
3
+ Keys: r refresh usage, s switch the default login to the highlighted account,
4
+ p ping (warm) it now, w add or remove it from the warm-up list, q quit.
5
+ Blocking work (usage reads, switches, pings) runs in thread workers; the UI
6
+ loop only paints. Textual is imported inside ``run`` so the plain CLI never
7
+ pays for it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+
14
+ from llmswap.model import AccountView
15
+ from llmswap.providers import registry
16
+ from llmswap.providers.base import ProviderError
17
+
18
+ REFRESH_EVERY_S = 60
19
+
20
+
21
+ def collect(refresh: bool) -> list[tuple[str, str, list[AccountView], bool]]:
22
+ """``(provider id, display, views, installed)`` for every provider worth showing."""
23
+ rows = []
24
+ for p in registry.all_providers():
25
+ installed = p.installed()
26
+ try:
27
+ views = p.accounts(refresh=refresh) if (installed or p.id != "claude") else []
28
+ except Exception:
29
+ views = []
30
+ if installed or views:
31
+ rows.append((p.id, p.display, views, installed))
32
+ return rows
33
+
34
+
35
+ def build_app():
36
+ from rich.text import Text
37
+ from textual import work
38
+ from textual.app import App, ComposeResult
39
+ from textual.widgets import Footer, Header, OptionList, Static
40
+ from textual.widgets.option_list import Option
41
+
42
+ from llmswap import config, render
43
+ from claude_swap.usage_bars import Palette
44
+
45
+ class LlmswapApp(App):
46
+ TITLE = "llmswap"
47
+ CSS = """
48
+ Screen { background: #141414; }
49
+ #status { height: 1; padding: 0 1; color: #8a8a8a; }
50
+ OptionList { background: #141414; border: none; }
51
+ OptionList > .option-list--option-highlighted { background: #262626; }
52
+ """
53
+ BINDINGS = [
54
+ ("r", "refresh", "Refresh"),
55
+ ("s", "switch", "Switch"),
56
+ ("p", "ping", "Ping now"),
57
+ ("w", "warm", "Warm-up on/off"),
58
+ ("q", "quit", "Quit"),
59
+ ]
60
+
61
+ def __init__(self) -> None:
62
+ super().__init__()
63
+ self.rows: list = []
64
+ self.by_option: dict[str, AccountView] = {}
65
+
66
+ def compose(self) -> ComposeResult:
67
+ yield Header()
68
+ yield OptionList(id="accounts")
69
+ yield Static("loading...", id="status")
70
+ yield Footer()
71
+
72
+ def on_mount(self) -> None:
73
+ self.load(refresh=False)
74
+ self.load(refresh=True)
75
+ self.set_interval(REFRESH_EVERY_S, lambda: self.load(refresh=True))
76
+
77
+ def say(self, message: str) -> None:
78
+ self.query_one("#status", Static).update(message)
79
+
80
+ @work(thread=True, exclusive=True, group="load")
81
+ def load(self, refresh: bool) -> None:
82
+ rows = collect(refresh)
83
+ self.call_from_thread(self.show, rows, refresh)
84
+
85
+ def show(self, rows, refreshed: bool) -> None:
86
+ self.rows = rows
87
+ ol = self.query_one("#accounts", OptionList)
88
+ keep = ol.highlighted
89
+ ol.clear_options()
90
+ self.by_option.clear()
91
+ now = time.time()
92
+ pal = Palette.DARK
93
+ warm = config.load_warm()
94
+ for pid, display, views, installed in rows:
95
+ head = Text(display, style=f"bold {pal.accent}")
96
+ if not installed:
97
+ head.append(" (not installed)", style=pal.muted)
98
+ ol.add_option(Option(head, disabled=True))
99
+ if not views:
100
+ ol.add_option(Option(Text(" no accounts saved", style=pal.muted), disabled=True))
101
+ for v in views:
102
+ text = render.account_text(v, now, 24, pal)
103
+ if f"{v.provider}:{v.number}" in warm.accounts and warm.accounts[f"{v.provider}:{v.number}"].enabled:
104
+ text.append(" warm-up: on\n", style=pal.info)
105
+ opt_id = f"{v.provider}:{v.number}"
106
+ self.by_option[opt_id] = v
107
+ ol.add_option(Option(text, id=opt_id))
108
+ if keep is not None and keep < ol.option_count:
109
+ ol.highlighted = keep
110
+ self.say(("updated " if refreshed else "cached ") + time.strftime("%H:%M:%S") + " · warm-up " + ("on" if warm.enabled else "off"))
111
+
112
+ def selected(self) -> AccountView | None:
113
+ ol = self.query_one("#accounts", OptionList)
114
+ if ol.highlighted is None:
115
+ return None
116
+ opt = ol.get_option_at_index(ol.highlighted)
117
+ return self.by_option.get(opt.id or "")
118
+
119
+ def action_refresh(self) -> None:
120
+ self.say("refreshing...")
121
+ self.load(refresh=True)
122
+
123
+ @work(thread=True, group="act")
124
+ def do(self, label: str, fn) -> None:
125
+ try:
126
+ msg = fn()
127
+ except ProviderError as exc:
128
+ msg = f"{label} failed: {exc}"
129
+ except Exception as exc:
130
+ msg = f"{label} failed: {exc.__class__.__name__}"
131
+ self.call_from_thread(self.say, msg)
132
+ self.load(refresh=False)
133
+
134
+ def action_switch(self) -> None:
135
+ v = self.selected()
136
+ if v is None:
137
+ return
138
+ if "switch" not in registry.get(v.provider).capabilities:
139
+ self.say(f"{v.provider} cannot switch the default login; use `llmswap run {v.ref}`")
140
+ return
141
+ self.say(f"switching to {v.label}...")
142
+
143
+ def go() -> str:
144
+ registry.get(v.provider).switch(v.number)
145
+ return f"now using {v.label}" + (" (restart Codex sessions)" if v.provider == "codex" else "")
146
+
147
+ self.do("switch", go)
148
+
149
+ def action_ping(self) -> None:
150
+ v = self.selected()
151
+ if v is None:
152
+ return
153
+ self.say(f"pinging {v.label}...")
154
+
155
+ def go() -> str:
156
+ out = registry.get(v.provider).warm(v.number, prompt=config.load_warm().prompt)
157
+ return f"pinged {v.label}" if out.ok else f"ping failed: {out.detail}"
158
+
159
+ self.do("ping", go)
160
+
161
+ def action_warm(self) -> None:
162
+ v = self.selected()
163
+ if v is None:
164
+ return
165
+ cfg = config.load_warm()
166
+ if v.ref in cfg.accounts:
167
+ del cfg.accounts[v.ref]
168
+ msg = f"{v.label}: warm-up removed"
169
+ else:
170
+ cfg.accounts[v.ref] = config.AccountWarm()
171
+ msg = f"{v.label}: warm-up added" + ("" if cfg.enabled else " (run `llmswap warm enable` to start the schedule)")
172
+ config.save_warm(cfg)
173
+ self.say(msg)
174
+ self.load(refresh=False)
175
+
176
+ return LlmswapApp()
177
+
178
+
179
+ def run() -> int:
180
+ app = build_app()
181
+ app.run()
182
+ return app.return_code or 0
llmswap/usage_cache.py ADDED
@@ -0,0 +1,72 @@
1
+ """Durable per-account usage readings and the rule for when to re-read.
2
+
3
+ A reading is kept across runs so a dashboard that repaints often, a cron tick
4
+ and ``llmswap list`` all share one measurement. A window whose reset time has
5
+ passed is no longer trusted (it reads as 0% via ``Window.effective_pct``) and
6
+ makes the reading due immediately, so a reset is noticed without waiting.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import time
13
+ from pathlib import Path
14
+
15
+ from claude_swap.fsutil import atomic_write_text
16
+ from claude_swap.locking import FileLock
17
+
18
+ from llmswap.model import UsageReading
19
+
20
+ MIN_INTERVAL_S = 90.0 # a healthy reading is reused this long
21
+ ERROR_BACKOFF_S = 300.0 # after a failed read, leave the endpoint alone this long
22
+ RESET_RECHECK_S = 20.0 # once a window has passed, re-read at most this often
23
+
24
+
25
+ class UsageCache:
26
+ def __init__(self, base: Path) -> None:
27
+ self.path = base / "usage.json"
28
+
29
+ def _locked(self) -> FileLock:
30
+ """A fresh lock per call: threads of one process and other processes both exclude each other."""
31
+ return FileLock(self.path.with_name("usage.lock"), timeout=10.0)
32
+
33
+ def _load(self) -> dict:
34
+ try:
35
+ return json.loads(self.path.read_text(encoding="utf-8"))
36
+ except (OSError, ValueError):
37
+ return {}
38
+
39
+ def get(self, number: str) -> UsageReading | None:
40
+ row = self._load().get(str(number))
41
+ return UsageReading.from_json(row["reading"]) if row else None
42
+
43
+ def put(self, number: str, reading: UsageReading, *, attempted_at: float | None = None) -> None:
44
+ self.path.parent.mkdir(parents=True, exist_ok=True)
45
+ with self._locked():
46
+ data = self._load()
47
+ data[str(number)] = {
48
+ "reading": reading.to_json(),
49
+ "attempted_at": attempted_at or time.time(),
50
+ }
51
+ atomic_write_text(self.path, json.dumps(data, indent=2))
52
+
53
+ def forget(self, number: str) -> None:
54
+ self.path.parent.mkdir(parents=True, exist_ok=True)
55
+ with self._locked():
56
+ data = self._load()
57
+ if data.pop(str(number), None) is not None:
58
+ atomic_write_text(self.path, json.dumps(data, indent=2))
59
+
60
+ def due(self, number: str, now: float | None = None) -> bool:
61
+ """True when a fresh network read is allowed for ``number``."""
62
+ now = time.time() if now is None else now
63
+ row = self._load().get(str(number))
64
+ if not row:
65
+ return True
66
+ reading = UsageReading.from_json(row["reading"])
67
+ age = now - float(row.get("attempted_at", 0))
68
+ if reading.error:
69
+ return age >= ERROR_BACKOFF_S
70
+ if any(w.passed(now) for w in reading.windows):
71
+ return age >= RESET_RECHECK_S
72
+ return age >= MIN_INTERVAL_S