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.
- claude_swap/__init__.py +24 -0
- claude_swap/__main__.py +6 -0
- claude_swap/app_bundle.py +330 -0
- claude_swap/appearance.py +219 -0
- claude_swap/autoswitch.py +3065 -0
- claude_swap/cache.py +44 -0
- claude_swap/claude_locks.py +279 -0
- claude_swap/cli.py +2265 -0
- claude_swap/credentials.py +2156 -0
- claude_swap/exceptions.py +102 -0
- claude_swap/fsutil.py +409 -0
- claude_swap/json_output.py +455 -0
- claude_swap/launch_agent.py +862 -0
- claude_swap/lines.py +153 -0
- claude_swap/list_view.py +371 -0
- claude_swap/locking.py +87 -0
- claude_swap/logging_config.py +64 -0
- claude_swap/macos_keychain.py +240 -0
- claude_swap/mappings.py +127 -0
- claude_swap/menubar.py +1433 -0
- claude_swap/migrations.py +360 -0
- claude_swap/models.py +329 -0
- claude_swap/oauth.py +1628 -0
- claude_swap/pace.py +161 -0
- claude_swap/paths.py +250 -0
- claude_swap/poll_policy.py +337 -0
- claude_swap/printer.py +252 -0
- claude_swap/process_detection.py +370 -0
- claude_swap/session.py +2696 -0
- claude_swap/settings.py +827 -0
- claude_swap/signin.py +238 -0
- claude_swap/snapshot_source.py +121 -0
- claude_swap/spawn.py +135 -0
- claude_swap/subscription.py +349 -0
- claude_swap/switcher.py +9807 -0
- claude_swap/transfer.py +807 -0
- claude_swap/tui/__init__.py +43 -0
- claude_swap/tui/app.py +482 -0
- claude_swap/tui/autoview.py +381 -0
- claude_swap/tui/cswap.tcss +205 -0
- claude_swap/tui/dashboard.py +434 -0
- claude_swap/tui/data.py +194 -0
- claude_swap/tui/modals.py +159 -0
- claude_swap/tui/theme.py +88 -0
- claude_swap/tui/widgets.py +544 -0
- claude_swap/update_check.py +509 -0
- claude_swap/usage_bars.py +208 -0
- claude_swap/usage_rows.py +160 -0
- claude_swap/usage_store.py +1429 -0
- llmswap/AGENTS.md +11 -0
- llmswap/__init__.py +3 -0
- llmswap/__main__.py +4 -0
- llmswap/cli.py +535 -0
- llmswap/config.py +101 -0
- llmswap/httpjson.py +50 -0
- llmswap/jwt.py +20 -0
- llmswap/menubar.py +218 -0
- llmswap/model.py +172 -0
- llmswap/paths.py +41 -0
- llmswap/providers/AGENTS.md +12 -0
- llmswap/providers/base.py +619 -0
- llmswap/providers/claude.py +187 -0
- llmswap/providers/codex.py +274 -0
- llmswap/providers/gemini.py +80 -0
- llmswap/providers/registry.py +30 -0
- llmswap/render.py +127 -0
- llmswap/rotate.py +102 -0
- llmswap/store.py +138 -0
- llmswap/tui.py +182 -0
- llmswap/usage_cache.py +72 -0
- llmswap/warm/plan.py +118 -0
- llmswap/warm/runner.py +175 -0
- llmswap/warm/schedule.py +264 -0
- llmswap_cli-1.0.0.dist-info/METADATA +181 -0
- llmswap_cli-1.0.0.dist-info/RECORD +78 -0
- llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
- llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
- llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
llmswap/httpjson.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""One small JSON GET that never follows a redirect.
|
|
2
|
+
|
|
3
|
+
Provider usage calls carry the account's bearer token, so they must only go to
|
|
4
|
+
the address the provider module names. A redirect would hand the token to
|
|
5
|
+
another host; here it is an error instead.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class HttpFailure(Exception):
|
|
16
|
+
"""``status`` is the HTTP status, or 0 for a network failure."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, status: int) -> None:
|
|
19
|
+
super().__init__(f"http {status}" if status else "network")
|
|
20
|
+
self.status = status
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
24
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_OPENER = urllib.request.build_opener(_NoRedirect)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_json(url: str, headers: dict[str, str], *, timeout: float = 20.0) -> dict:
|
|
32
|
+
return _request(url, headers, None, timeout)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def post_json(url: str, headers: dict[str, str], body: dict, *, timeout: float = 20.0) -> dict:
|
|
36
|
+
return _request(url, headers, json.dumps(body).encode(), timeout)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _request(url: str, headers: dict[str, str], data: bytes | None, timeout: float) -> dict:
|
|
40
|
+
hdrs = {"Accept": "application/json", "User-Agent": "llmswap", **headers}
|
|
41
|
+
if data is not None:
|
|
42
|
+
hdrs.setdefault("Content-Type", "application/json")
|
|
43
|
+
req = urllib.request.Request(url, headers=hdrs, data=data)
|
|
44
|
+
try:
|
|
45
|
+
with _OPENER.open(req, timeout=timeout) as resp:
|
|
46
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
47
|
+
except urllib.error.HTTPError as exc:
|
|
48
|
+
raise HttpFailure(exc.code) from None
|
|
49
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError):
|
|
50
|
+
raise HttpFailure(0) from None
|
llmswap/jwt.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Read the claims of a JWT without verifying it.
|
|
2
|
+
|
|
3
|
+
Used only to show who a stored login belongs to and when its access token
|
|
4
|
+
expires. Nothing here trusts a claim for a security decision.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def claims(token: str) -> dict:
|
|
14
|
+
try:
|
|
15
|
+
payload = token.split(".")[1]
|
|
16
|
+
payload += "=" * (-len(payload) % 4)
|
|
17
|
+
data = json.loads(base64.urlsafe_b64decode(payload))
|
|
18
|
+
except (IndexError, ValueError):
|
|
19
|
+
return {}
|
|
20
|
+
return data if isinstance(data, dict) else {}
|
llmswap/menubar.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""The macOS menu bar: every provider's usage one click away.
|
|
2
|
+
|
|
3
|
+
``menu_model`` turns the accounts into a plain tree and is tested without a
|
|
4
|
+
display. ``run_foreground`` draws it with rumps (the optional ``menubar``
|
|
5
|
+
extra). ``llmswap menubar`` keeps that process alive under launchd, reusing
|
|
6
|
+
claude-swap's launchd helpers.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import plistlib
|
|
13
|
+
import shutil
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from llmswap import paths
|
|
20
|
+
from llmswap.model import AccountView
|
|
21
|
+
from llmswap.providers.base import ProviderError
|
|
22
|
+
from llmswap.render import countdown
|
|
23
|
+
|
|
24
|
+
LABEL = "com.llmswap.menubar"
|
|
25
|
+
REFRESH_S = 60
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Item:
|
|
30
|
+
title: str
|
|
31
|
+
action: tuple[str, str, str] | None = None # ("switch" | "ping", provider, number)
|
|
32
|
+
children: list["Item"] = field(default_factory=list)
|
|
33
|
+
enabled: bool = True
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def title_for(rows: list[tuple[str, str, list[AccountView], bool]], now: float) -> str:
|
|
37
|
+
"""The status-item text: the fullest window of any active account."""
|
|
38
|
+
worst = None
|
|
39
|
+
for _pid, _name, views, _installed in rows:
|
|
40
|
+
for v in views:
|
|
41
|
+
if v.active:
|
|
42
|
+
pct = v.usage.worst_pct(now)
|
|
43
|
+
if pct is not None and (worst is None or pct > worst):
|
|
44
|
+
worst = pct
|
|
45
|
+
return "llmswap" if worst is None else f"{worst:.0f}%"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _summary(v: AccountView, now: float) -> str:
|
|
49
|
+
bits = []
|
|
50
|
+
for w in v.usage.windows:
|
|
51
|
+
pct = w.effective_pct(now)
|
|
52
|
+
bits.append(f"{w.key} {'?' if pct is None else f'{pct:.0f}%'}")
|
|
53
|
+
return " ".join(bits) or (v.note or "no usage")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def menu_model(rows: list[tuple[str, str, list[AccountView], bool]], now: float) -> list[Item]:
|
|
57
|
+
out: list[Item] = []
|
|
58
|
+
for pid, display, views, installed in rows:
|
|
59
|
+
out.append(Item(display + ("" if installed else " (not installed)"), enabled=False))
|
|
60
|
+
if not views:
|
|
61
|
+
out.append(Item(" no accounts saved", enabled=False))
|
|
62
|
+
for v in views:
|
|
63
|
+
mark = "● " if v.active else " "
|
|
64
|
+
sub = [
|
|
65
|
+
Item(" " + (f"{w.key}: " + (f"{p:.0f}% used" if (p := w.effective_pct(now)) is not None else "?")
|
|
66
|
+
+ ("" if w.resets_at is None else f", resets in {countdown(w.resets_at - now)}" if not w.passed(now) else ", reset")),
|
|
67
|
+
enabled=False)
|
|
68
|
+
for w in v.usage.windows
|
|
69
|
+
]
|
|
70
|
+
if v.note and v.usage.error:
|
|
71
|
+
sub.append(Item(f" ! {v.note}", enabled=False))
|
|
72
|
+
sub.append(Item("Switch to this account", ("switch", pid, v.number), enabled=not v.active))
|
|
73
|
+
sub.append(Item("Ping now (start 5h window)", ("ping", pid, v.number)))
|
|
74
|
+
out.append(Item(f"{mark}{v.number} {v.label} {_summary(v, now)}", children=sub))
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# -- service ------------------------------------------------------------------
|
|
79
|
+
def _program() -> list[str]:
|
|
80
|
+
which = shutil.which("llmswap")
|
|
81
|
+
return [str(Path(os.path.abspath(which)))] if which else [sys.executable, "-m", "llmswap"]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def service_plist() -> bytes:
|
|
85
|
+
from claude_swap import launch_agent as la
|
|
86
|
+
|
|
87
|
+
prog = _program()
|
|
88
|
+
out = paths.logs_dir() / "menubar.log"
|
|
89
|
+
return plistlib.dumps(
|
|
90
|
+
{
|
|
91
|
+
"Label": LABEL,
|
|
92
|
+
"ProgramArguments": [*prog, "menubar", "--foreground"],
|
|
93
|
+
"RunAtLoad": True,
|
|
94
|
+
"KeepAlive": {"SuccessfulExit": False},
|
|
95
|
+
"ProcessType": "Interactive",
|
|
96
|
+
"EnvironmentVariables": {"PATH": la._path_env(prog)},
|
|
97
|
+
"StandardOutPath": str(out),
|
|
98
|
+
"StandardErrorPath": str(out),
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def install_service() -> Path:
|
|
104
|
+
from claude_swap import launch_agent as la
|
|
105
|
+
from claude_swap.fsutil import atomic_write_bytes
|
|
106
|
+
|
|
107
|
+
if sys.platform != "darwin":
|
|
108
|
+
raise ProviderError("the menu bar is macOS only")
|
|
109
|
+
target = la.plist_path(LABEL)
|
|
110
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
paths.logs_dir().mkdir(parents=True, exist_ok=True)
|
|
112
|
+
atomic_write_bytes(target, service_plist())
|
|
113
|
+
la._reload(target, LABEL, None)
|
|
114
|
+
return target
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def uninstall_service() -> None:
|
|
118
|
+
from claude_swap import launch_agent as la
|
|
119
|
+
|
|
120
|
+
if la.is_loaded(LABEL):
|
|
121
|
+
la._launchctl("bootout", la.service_target(LABEL))
|
|
122
|
+
la.plist_path(LABEL).unlink(missing_ok=True)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# -- the app --------------------------------------------------------------------
|
|
126
|
+
def run_foreground() -> int:
|
|
127
|
+
try:
|
|
128
|
+
import AppKit
|
|
129
|
+
import rumps
|
|
130
|
+
except ImportError:
|
|
131
|
+
raise ProviderError("the menu bar needs rumps: uv tool install --force 'llmswap-cli[menubar]'") from None
|
|
132
|
+
import threading
|
|
133
|
+
|
|
134
|
+
from llmswap import tui
|
|
135
|
+
from llmswap.providers import registry
|
|
136
|
+
|
|
137
|
+
from claude_swap.menubar import ensure_notification_identity
|
|
138
|
+
|
|
139
|
+
ensure_notification_identity()
|
|
140
|
+
AppKit.NSApplication.sharedApplication().setActivationPolicy_(AppKit.NSApplicationActivationPolicyAccessory)
|
|
141
|
+
|
|
142
|
+
class App(rumps.App):
|
|
143
|
+
def __init__(self) -> None:
|
|
144
|
+
super().__init__("llmswap", quit_button=None)
|
|
145
|
+
self.rows: list = []
|
|
146
|
+
self._busy = threading.Lock()
|
|
147
|
+
self.timer = rumps.Timer(lambda _t: self.refresh(), REFRESH_S)
|
|
148
|
+
self.timer.start()
|
|
149
|
+
self.refresh(initial=True)
|
|
150
|
+
|
|
151
|
+
def refresh(self, initial: bool = False) -> None:
|
|
152
|
+
def work() -> None:
|
|
153
|
+
if not self._busy.acquire(blocking=False):
|
|
154
|
+
return
|
|
155
|
+
try:
|
|
156
|
+
self.rows = tui.collect(refresh=not initial)
|
|
157
|
+
finally:
|
|
158
|
+
self._busy.release()
|
|
159
|
+
self.rebuild()
|
|
160
|
+
|
|
161
|
+
threading.Thread(target=work, daemon=True).start()
|
|
162
|
+
|
|
163
|
+
def rebuild(self) -> None:
|
|
164
|
+
now = time.time()
|
|
165
|
+
self.title = title_for(self.rows, now)
|
|
166
|
+
self.menu.clear()
|
|
167
|
+
for item in menu_model(self.rows, now):
|
|
168
|
+
self.menu.add(self._menu_item(item))
|
|
169
|
+
self.menu.add(rumps.separator)
|
|
170
|
+
self.menu.add(rumps.MenuItem("Refresh now", callback=lambda _s: self.refresh()))
|
|
171
|
+
self.menu.add(rumps.MenuItem("Quit", callback=lambda _s: rumps.quit_application()))
|
|
172
|
+
|
|
173
|
+
def _menu_item(self, item: Item):
|
|
174
|
+
mi = rumps.MenuItem(item.title, callback=self._callback(item) if item.action else None)
|
|
175
|
+
if not item.enabled:
|
|
176
|
+
mi.set_callback(None)
|
|
177
|
+
for child in item.children:
|
|
178
|
+
mi.add(self._menu_item(child))
|
|
179
|
+
return mi
|
|
180
|
+
|
|
181
|
+
def _callback(self, item: Item):
|
|
182
|
+
kind, pid, number = item.action
|
|
183
|
+
|
|
184
|
+
def go(_sender) -> None:
|
|
185
|
+
def work() -> None:
|
|
186
|
+
try:
|
|
187
|
+
p = registry.get(pid)
|
|
188
|
+
if kind == "switch":
|
|
189
|
+
p.switch(number)
|
|
190
|
+
rumps.notification("llmswap", "Switched", f"{p.display} account {number} is now the default.")
|
|
191
|
+
else:
|
|
192
|
+
from llmswap import config
|
|
193
|
+
|
|
194
|
+
out = p.warm(number, prompt=config.load_warm().prompt)
|
|
195
|
+
rumps.notification("llmswap", "Ping", "sent" if out.ok else f"failed: {out.detail}")
|
|
196
|
+
except ProviderError as exc:
|
|
197
|
+
rumps.notification("llmswap", "Could not do that", str(exc)[:120])
|
|
198
|
+
self.refresh()
|
|
199
|
+
|
|
200
|
+
threading.Thread(target=work, daemon=True).start()
|
|
201
|
+
|
|
202
|
+
return go
|
|
203
|
+
|
|
204
|
+
App().run()
|
|
205
|
+
return 0
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def run(argv: list[str] | None = None) -> int:
|
|
209
|
+
argv = list(sys.argv[2:] if argv is None else argv)
|
|
210
|
+
if "--foreground" in argv:
|
|
211
|
+
return run_foreground()
|
|
212
|
+
if "--uninstall" in argv:
|
|
213
|
+
uninstall_service()
|
|
214
|
+
print("Menu bar service removed.")
|
|
215
|
+
return 0
|
|
216
|
+
path = install_service()
|
|
217
|
+
print(f"Menu bar running under launchd ({path}). It starts at login; `llmswap menubar --uninstall` removes it.")
|
|
218
|
+
return 0
|
llmswap/model.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""The provider-neutral shapes every surface renders.
|
|
2
|
+
|
|
3
|
+
A provider turns whatever its CLI exposes into these. Surfaces (CLI, TUI,
|
|
4
|
+
menu bar, warm-up) never see a provider's raw payload.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
FIVE_HOUR_S = 5 * 3600
|
|
13
|
+
WEEK_S = 7 * 24 * 3600
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Window:
|
|
18
|
+
"""One rate-limit window of one account.
|
|
19
|
+
|
|
20
|
+
``used_pct`` is 0-100 or None when the provider reports a window without a
|
|
21
|
+
figure. ``resets_at`` is epoch seconds or None when no window is running
|
|
22
|
+
(a cold window: the next request starts one).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
key: str # "5h", "7d", or e.g. "daily", "300m"
|
|
26
|
+
used_pct: float | None = None
|
|
27
|
+
resets_at: float | None = None
|
|
28
|
+
seconds: int | None = None
|
|
29
|
+
label: str = ""
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def key_for_seconds(seconds: int | None) -> str:
|
|
33
|
+
if seconds is None:
|
|
34
|
+
return "window"
|
|
35
|
+
if abs(seconds - FIVE_HOUR_S) <= 60:
|
|
36
|
+
return "5h"
|
|
37
|
+
if abs(seconds - WEEK_S) <= 3600:
|
|
38
|
+
return "7d"
|
|
39
|
+
if seconds % 86400 == 0:
|
|
40
|
+
return f"{seconds // 86400}d"
|
|
41
|
+
if seconds % 3600 == 0:
|
|
42
|
+
return f"{seconds // 3600}h"
|
|
43
|
+
return f"{max(1, seconds // 60)}m"
|
|
44
|
+
|
|
45
|
+
def passed(self, now: float | None = None) -> bool:
|
|
46
|
+
"""True when the window this reading described has already reset."""
|
|
47
|
+
now = time.time() if now is None else now
|
|
48
|
+
return self.resets_at is not None and self.resets_at <= now
|
|
49
|
+
|
|
50
|
+
def running(self, now: float | None = None) -> bool:
|
|
51
|
+
now = time.time() if now is None else now
|
|
52
|
+
return self.resets_at is not None and self.resets_at > now
|
|
53
|
+
|
|
54
|
+
def effective_pct(self, now: float | None = None) -> float | None:
|
|
55
|
+
"""Used percent now: a window that has reset reads as 0."""
|
|
56
|
+
if self.passed(now):
|
|
57
|
+
return 0.0
|
|
58
|
+
return self.used_pct
|
|
59
|
+
|
|
60
|
+
def to_json(self) -> dict:
|
|
61
|
+
return {
|
|
62
|
+
"key": self.key,
|
|
63
|
+
"used_pct": self.used_pct,
|
|
64
|
+
"resets_at": self.resets_at,
|
|
65
|
+
"seconds": self.seconds,
|
|
66
|
+
"label": self.label,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def from_json(cls, data: dict) -> "Window":
|
|
71
|
+
return cls(
|
|
72
|
+
key=str(data.get("key", "window")),
|
|
73
|
+
used_pct=data.get("used_pct"),
|
|
74
|
+
resets_at=data.get("resets_at"),
|
|
75
|
+
seconds=data.get("seconds"),
|
|
76
|
+
label=str(data.get("label", "")),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Identity:
|
|
82
|
+
"""Who a stored login belongs to. Never holds a token."""
|
|
83
|
+
|
|
84
|
+
email: str = ""
|
|
85
|
+
account_id: str = ""
|
|
86
|
+
plan: str = ""
|
|
87
|
+
kind: str = "oauth" # "oauth" | "api_key"
|
|
88
|
+
|
|
89
|
+
def same_account(self, other: "Identity") -> bool:
|
|
90
|
+
"""Whether two logins are one account.
|
|
91
|
+
|
|
92
|
+
When either side names an account (workspace) id, both must, and they
|
|
93
|
+
must match: one email can sit in two workspaces (personal and Team) that
|
|
94
|
+
are different accounts with different quotas. The email decides only
|
|
95
|
+
when neither side has an id.
|
|
96
|
+
"""
|
|
97
|
+
if self.account_id or other.account_id:
|
|
98
|
+
return self.account_id == other.account_id
|
|
99
|
+
return bool(self.email) and self.email == other.email
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class UsageReading:
|
|
104
|
+
"""The last usage measurement for one account.
|
|
105
|
+
|
|
106
|
+
``error`` is a short code ("token expired", "http 429", "unsupported"),
|
|
107
|
+
never a message that could carry a token.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
windows: tuple[Window, ...] = ()
|
|
111
|
+
fetched_at: float | None = None
|
|
112
|
+
error: str | None = None
|
|
113
|
+
|
|
114
|
+
def window(self, key: str) -> Window | None:
|
|
115
|
+
return next((w for w in self.windows if w.key == key), None)
|
|
116
|
+
|
|
117
|
+
def worst_pct(self, now: float | None = None) -> float | None:
|
|
118
|
+
vals = [p for w in self.windows if (p := w.effective_pct(now)) is not None]
|
|
119
|
+
return max(vals) if vals else None
|
|
120
|
+
|
|
121
|
+
def to_json(self) -> dict:
|
|
122
|
+
return {
|
|
123
|
+
"windows": [w.to_json() for w in self.windows],
|
|
124
|
+
"fetched_at": self.fetched_at,
|
|
125
|
+
"error": self.error,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def from_json(cls, data: dict) -> "UsageReading":
|
|
130
|
+
return cls(
|
|
131
|
+
windows=tuple(Window.from_json(w) for w in data.get("windows", [])),
|
|
132
|
+
fetched_at=data.get("fetched_at"),
|
|
133
|
+
error=data.get("error"),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class AccountView:
|
|
139
|
+
"""One account as a surface shows it."""
|
|
140
|
+
|
|
141
|
+
provider: str
|
|
142
|
+
number: str
|
|
143
|
+
email: str = ""
|
|
144
|
+
plan: str = ""
|
|
145
|
+
alias: str = ""
|
|
146
|
+
active: bool = False
|
|
147
|
+
disabled: bool = False
|
|
148
|
+
kind: str = "oauth"
|
|
149
|
+
usage: UsageReading = field(default_factory=UsageReading)
|
|
150
|
+
note: str = "" # short state such as "re-login needed"
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def ref(self) -> str:
|
|
154
|
+
return f"{self.provider}:{self.number}"
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def label(self) -> str:
|
|
158
|
+
return self.alias or self.email or f"account {self.number}"
|
|
159
|
+
|
|
160
|
+
def to_json(self) -> dict:
|
|
161
|
+
return {
|
|
162
|
+
"provider": self.provider,
|
|
163
|
+
"number": self.number,
|
|
164
|
+
"email": self.email,
|
|
165
|
+
"plan": self.plan,
|
|
166
|
+
"alias": self.alias,
|
|
167
|
+
"active": self.active,
|
|
168
|
+
"disabled": self.disabled,
|
|
169
|
+
"kind": self.kind,
|
|
170
|
+
"usage": self.usage.to_json(),
|
|
171
|
+
"note": self.note,
|
|
172
|
+
}
|
llmswap/paths.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Where llmswap keeps its own data.
|
|
2
|
+
|
|
3
|
+
``LLMSWAP_HOME`` wins (tests and portable installs). Otherwise the root is
|
|
4
|
+
``$XDG_DATA_HOME/llmswap`` (default ``~/.local/share/llmswap``) on Linux and
|
|
5
|
+
``~/.llmswap`` on macOS and Windows, the same split claude-swap uses for its own
|
|
6
|
+
backup root. Claude Code accounts stay in claude-swap's root (see
|
|
7
|
+
``providers/claude.py``); everything else lives here, one folder per provider.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def root() -> Path:
|
|
18
|
+
env = os.environ.get("LLMSWAP_HOME")
|
|
19
|
+
if env:
|
|
20
|
+
return Path(env)
|
|
21
|
+
if sys.platform.startswith("linux"):
|
|
22
|
+
xdg = os.environ.get("XDG_DATA_HOME", "")
|
|
23
|
+
base = Path(xdg) if xdg and Path(xdg).is_absolute() else Path.home() / ".local" / "share"
|
|
24
|
+
return base / "llmswap"
|
|
25
|
+
return Path.home() / ".llmswap"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def provider_dir(provider_id: str) -> Path:
|
|
29
|
+
return root() / provider_id
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def config_path() -> Path:
|
|
33
|
+
return root() / "config.json"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def warmup_state_path() -> Path:
|
|
37
|
+
return root() / "warmup_state.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def logs_dir() -> Path:
|
|
41
|
+
return root() / "logs"
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# providers
|
|
2
|
+
|
|
3
|
+
One module per CLI. To add one: subclass `ProfileProvider` (or `Provider` when the CLI needs its own engine, as Claude does), register it in `registry.py`, add a row to [docs/providers.md](../../../docs/providers.md).
|
|
4
|
+
|
|
5
|
+
Rules that hold for every provider:
|
|
6
|
+
|
|
7
|
+
- Every fact about the CLI's storage or usage endpoint has evidence in the module docstring: the CLI version read or what was measured. Do not guess.
|
|
8
|
+
- A login is written into a slot only when its identity matches that slot, and the default login is never overwritten when it is not saved. Capture the live login back before replacing it.
|
|
9
|
+
- Never run a logout: it revokes the refresh token on the provider's side.
|
|
10
|
+
- Never post a refresh token yourself when the CLI can refresh its own login; read usage through the CLI where possible.
|
|
11
|
+
- A bearer token goes only to the host the module names, and redirects are refused (`httpjson.py`).
|
|
12
|
+
- `UsageError` carries a short fixed code, never a message that could contain a token.
|