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/AGENTS.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# src/llmswap
|
|
2
|
+
|
|
3
|
+
The provider layer: Codex, Gemini CLI and the Claude adapter behind one interface, plus the cross-provider surfaces and warm-up. It imports `claude_swap` for the Claude engine and a few leaf helpers (`fsutil`, `locking`, `usage_bars`); `claude_swap` never imports it.
|
|
4
|
+
|
|
5
|
+
- `model.py` is the vocabulary (`Window`, `Identity`, `UsageReading`, `AccountView`). Surfaces render these, never a provider's raw payload.
|
|
6
|
+
- `providers/` holds one module per provider ([providers/AGENTS.md](providers/AGENTS.md)). `store.py` and `usage_cache.py` are the slot roster and the durable usage reading they share.
|
|
7
|
+
- `cli.py`, `render.py`, `tui.py`, `menubar.py` parse and paint. No account logic.
|
|
8
|
+
- `rotate.py` is the rotation rule for non-Claude providers. `warm/` is warm-up: `plan.py` decides (pure), `runner.py` runs one pass, `schedule.py` installs it in launchd, systemd/cron or Task Scheduler.
|
|
9
|
+
- `--json` output (`list --json`) is a contract: add fields, never rename or remove.
|
|
10
|
+
- No token in any log, message, error code or JSON. Error codes are short fixed strings.
|
|
11
|
+
- Tests: `tests/llmswap/`, against temporary homes and fake providers. Never install a real scheduler job or call a real provider in a test.
|
llmswap/__init__.py
ADDED
llmswap/__main__.py
ADDED
llmswap/cli.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
"""The ``llmswap`` command line.
|
|
2
|
+
|
|
3
|
+
llmswap dashboard on a terminal, the list when piped
|
|
4
|
+
llmswap list [-r] [--json] every provider's accounts and usage
|
|
5
|
+
llmswap <provider> <command> add, login, remove, switch, run, alias, ...
|
|
6
|
+
llmswap switch <provider[:acct]> make an account the default login
|
|
7
|
+
llmswap run <provider:acct> run the CLI as an account, this terminal only
|
|
8
|
+
llmswap auto [--once] rotate before a limit
|
|
9
|
+
llmswap warm ... start 5-hour windows early, on a schedule
|
|
10
|
+
|
|
11
|
+
``llmswap claude ...`` hands everything to claude-swap's full command set.
|
|
12
|
+
This module parses and prints; account logic lives in ``providers/``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
from datetime import datetime
|
|
22
|
+
|
|
23
|
+
from llmswap import __version__
|
|
24
|
+
from llmswap.model import AccountView
|
|
25
|
+
from llmswap.providers import registry
|
|
26
|
+
from llmswap.providers.base import Provider, ProviderError, resolve_ref
|
|
27
|
+
|
|
28
|
+
JSON_VERSION = 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _err(msg: str) -> int:
|
|
32
|
+
print(f"llmswap: {msg}", file=sys.stderr)
|
|
33
|
+
return 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def split_ref(text: str, default_provider: str | None = None) -> tuple[str, str | None]:
|
|
37
|
+
"""``codex:2`` -> (codex, 2); ``codex`` -> (codex, None); ``2`` -> (default, 2)."""
|
|
38
|
+
if ":" in text:
|
|
39
|
+
prov, _, ref = text.partition(":")
|
|
40
|
+
if prov in registry.provider_ids():
|
|
41
|
+
return prov, ref or None
|
|
42
|
+
if text in registry.provider_ids():
|
|
43
|
+
return text, None
|
|
44
|
+
if default_provider:
|
|
45
|
+
return default_provider, text
|
|
46
|
+
raise ProviderError(f"{text!r} is not a provider; use e.g. codex:2 (providers: {', '.join(registry.provider_ids())})")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# list
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
def _groups(providers: list[Provider], refresh: bool, everything: bool):
|
|
53
|
+
groups = []
|
|
54
|
+
for p in providers:
|
|
55
|
+
installed = p.installed()
|
|
56
|
+
views = p.accounts(refresh=refresh) if (installed or p.id != "claude") else []
|
|
57
|
+
if not (installed or views or everything):
|
|
58
|
+
continue
|
|
59
|
+
groups.append((p, installed, views))
|
|
60
|
+
return groups
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
64
|
+
from llmswap import render
|
|
65
|
+
|
|
66
|
+
providers = [registry.get(i) for i in args.providers] if args.providers else registry.all_providers()
|
|
67
|
+
groups = _groups(providers, args.refresh, everything=bool(args.providers))
|
|
68
|
+
if args.json:
|
|
69
|
+
body = {
|
|
70
|
+
"version": JSON_VERSION,
|
|
71
|
+
"generated_at": time.time(),
|
|
72
|
+
"providers": [
|
|
73
|
+
{
|
|
74
|
+
"id": p.id,
|
|
75
|
+
"display": p.display,
|
|
76
|
+
"installed": installed,
|
|
77
|
+
"capabilities": sorted(p.capabilities),
|
|
78
|
+
"accounts": [v.to_json() for v in views],
|
|
79
|
+
}
|
|
80
|
+
for p, installed, views in groups
|
|
81
|
+
],
|
|
82
|
+
}
|
|
83
|
+
print(json.dumps(body, indent=2))
|
|
84
|
+
return 0
|
|
85
|
+
if not groups:
|
|
86
|
+
print("No supported coding CLI found. Install Claude Code, Codex or Gemini CLI, then run `llmswap add`.")
|
|
87
|
+
return 0
|
|
88
|
+
print(render.render([(p.display, views, installed) for p, installed, views in groups]), end="")
|
|
89
|
+
return 0
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def cmd_providers(args: argparse.Namespace) -> int:
|
|
93
|
+
for p in registry.all_providers():
|
|
94
|
+
mark = "installed" if p.installed() else "not installed"
|
|
95
|
+
print(f"{p.id:<10} {p.display:<14} {mark:<14} {', '.join(sorted(p.capabilities))}")
|
|
96
|
+
return 0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# per-provider commands
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
def _announce(v: AccountView, verb: str) -> None:
|
|
103
|
+
who = v.email or v.alias or f"account {v.number}"
|
|
104
|
+
print(f"{verb} {registry.get(v.provider).display} account {v.number}: {who}" + (f" [{v.plan}]" if v.plan else ""))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def provider_command(provider: Provider, verb: str, rest: list[str]) -> int:
|
|
108
|
+
p = provider
|
|
109
|
+
parser = argparse.ArgumentParser(prog=f"llmswap {p.id} {verb}")
|
|
110
|
+
if verb == "add":
|
|
111
|
+
parser.add_argument("--slot")
|
|
112
|
+
a = parser.parse_args(rest)
|
|
113
|
+
_announce(p.add(slot=a.slot), "Saved")
|
|
114
|
+
elif verb == "login":
|
|
115
|
+
parser.add_argument("--slot")
|
|
116
|
+
parser.add_argument("--device", action="store_true", help="device-code sign-in (no local browser callback)")
|
|
117
|
+
a = parser.parse_args(rest)
|
|
118
|
+
hint = getattr(p, "login_hint", None)
|
|
119
|
+
if hint:
|
|
120
|
+
print(hint)
|
|
121
|
+
_announce(p.login(slot=a.slot, device=a.device), "Signed in and saved")
|
|
122
|
+
elif verb in ("remove", "rm"):
|
|
123
|
+
parser.add_argument("account")
|
|
124
|
+
a = parser.parse_args(rest)
|
|
125
|
+
p.remove(a.account)
|
|
126
|
+
print(f"Removed {p.display} account {a.account}")
|
|
127
|
+
elif verb == "switch":
|
|
128
|
+
parser.add_argument("account", nargs="?")
|
|
129
|
+
a = parser.parse_args(rest)
|
|
130
|
+
v = p.switch(a.account)
|
|
131
|
+
_announce(v, "Now using")
|
|
132
|
+
n = p.running_sessions()
|
|
133
|
+
if n:
|
|
134
|
+
print(
|
|
135
|
+
f"Warning: {n} `{p.binary}` process(es) are running. A session on the default login keeps the old "
|
|
136
|
+
"login in memory and can write it back over this switch: restart it.",
|
|
137
|
+
file=sys.stderr,
|
|
138
|
+
)
|
|
139
|
+
elif p.id == "codex":
|
|
140
|
+
print("Restart any running Codex session to pick up the new login.")
|
|
141
|
+
elif verb == "run":
|
|
142
|
+
if "--" in rest:
|
|
143
|
+
i = rest.index("--")
|
|
144
|
+
head, tail = rest[:i], rest[i + 1:]
|
|
145
|
+
else:
|
|
146
|
+
head, tail = rest[:1], rest[1:]
|
|
147
|
+
if not head:
|
|
148
|
+
return _err(f"usage: llmswap {p.id} run <account> [-- args for {p.binary}]")
|
|
149
|
+
p.run(head[0], tail)
|
|
150
|
+
elif verb == "alias":
|
|
151
|
+
parser.add_argument("account")
|
|
152
|
+
parser.add_argument("alias")
|
|
153
|
+
a = parser.parse_args(rest)
|
|
154
|
+
p.set_alias(a.account, a.alias)
|
|
155
|
+
elif verb in ("disable", "enable"):
|
|
156
|
+
parser.add_argument("account")
|
|
157
|
+
a = parser.parse_args(rest)
|
|
158
|
+
p.set_disabled(a.account, verb == "disable")
|
|
159
|
+
elif verb in ("list", "ls", "usage", "status"):
|
|
160
|
+
parser.add_argument("--json", action="store_true")
|
|
161
|
+
a = parser.parse_args(rest)
|
|
162
|
+
ns = argparse.Namespace(providers=[p.id], refresh=verb in ("usage", "status"), json=a.json)
|
|
163
|
+
return cmd_list(ns)
|
|
164
|
+
elif verb == "warm":
|
|
165
|
+
parser.add_argument("account")
|
|
166
|
+
a = parser.parse_args(rest)
|
|
167
|
+
from llmswap.config import load_warm
|
|
168
|
+
|
|
169
|
+
v = p.find(a.account)
|
|
170
|
+
out = p.warm(v.number, prompt=load_warm().prompt)
|
|
171
|
+
print("pinged" if out.ok else f"ping failed: {out.detail}")
|
|
172
|
+
return 0 if out.ok else 1
|
|
173
|
+
else:
|
|
174
|
+
return _err(f"unknown command {verb!r} for {p.id}. Try: add, login, remove, switch, run, alias, enable, disable, list, usage, warm")
|
|
175
|
+
return 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cmd_provider(args: argparse.Namespace) -> int:
|
|
179
|
+
p = registry.get(args.provider)
|
|
180
|
+
if p.id == "claude":
|
|
181
|
+
return claude_passthrough(args.rest_all)
|
|
182
|
+
if not args.rest_all:
|
|
183
|
+
return provider_command(p, "list", [])
|
|
184
|
+
return provider_command(p, args.rest_all[0], args.rest_all[1:])
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def claude_passthrough(argv: list[str]) -> int:
|
|
188
|
+
"""Run claude-swap's own CLI with ``argv``; it has the full Claude feature set."""
|
|
189
|
+
from claude_swap import cli as cswap
|
|
190
|
+
|
|
191
|
+
sys.argv = ["llmswap claude", *argv]
|
|
192
|
+
cswap.main()
|
|
193
|
+
return 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def cmd_switch(args: argparse.Namespace) -> int:
|
|
197
|
+
pid, ref = split_ref(args.target)
|
|
198
|
+
return provider_command(registry.get(pid), "switch", [ref] if ref else [])
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
202
|
+
pid, ref = split_ref(args.target)
|
|
203
|
+
if ref is None:
|
|
204
|
+
return _err("name the account, e.g. llmswap run codex:2")
|
|
205
|
+
tail = args.rest[1:] if args.rest[:1] == ["--"] else args.rest
|
|
206
|
+
return provider_command(registry.get(pid), "run", [ref, "--", *tail])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def cmd_add(args: argparse.Namespace) -> int:
|
|
210
|
+
"""Save every installed provider's current login."""
|
|
211
|
+
targets = [registry.get(args.provider)] if args.provider else [p for p in registry.all_providers() if p.installed()]
|
|
212
|
+
if not targets:
|
|
213
|
+
return _err("no supported CLI found (claude, codex, gemini). Install one and sign in first.")
|
|
214
|
+
saved = 0
|
|
215
|
+
for p in targets:
|
|
216
|
+
try:
|
|
217
|
+
_announce(p.add(), "Saved")
|
|
218
|
+
saved += 1
|
|
219
|
+
except ProviderError as exc:
|
|
220
|
+
if args.provider:
|
|
221
|
+
return _err(str(exc))
|
|
222
|
+
print(f"{p.display}: {exc}", file=sys.stderr)
|
|
223
|
+
return 0 if saved else 1
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ---------------------------------------------------------------------------
|
|
227
|
+
# auto
|
|
228
|
+
# ---------------------------------------------------------------------------
|
|
229
|
+
def cmd_auto(args: argparse.Namespace) -> int:
|
|
230
|
+
from llmswap import rotate
|
|
231
|
+
|
|
232
|
+
def once() -> None:
|
|
233
|
+
for p in registry.all_providers():
|
|
234
|
+
if not p.installed():
|
|
235
|
+
continue
|
|
236
|
+
if p.id == "claude":
|
|
237
|
+
if args.dry_run:
|
|
238
|
+
continue
|
|
239
|
+
try:
|
|
240
|
+
from claude_swap import cli as cswap
|
|
241
|
+
|
|
242
|
+
cswap._auto_command(["--once"])
|
|
243
|
+
except SystemExit:
|
|
244
|
+
pass
|
|
245
|
+
continue
|
|
246
|
+
res = rotate.tick(p, threshold=args.threshold, dry_run=args.dry_run)
|
|
247
|
+
if res.action in ("switched", "would-switch"):
|
|
248
|
+
print(f"{p.display}: {res.action} to account {res.target} ({res.detail})")
|
|
249
|
+
elif not args.quiet:
|
|
250
|
+
print(f"{p.display}: {res.detail or res.action}")
|
|
251
|
+
|
|
252
|
+
if args.once:
|
|
253
|
+
once()
|
|
254
|
+
return 0
|
|
255
|
+
print(f"Watching every {args.interval}s; Ctrl+C to stop.")
|
|
256
|
+
try:
|
|
257
|
+
while True:
|
|
258
|
+
once()
|
|
259
|
+
time.sleep(args.interval)
|
|
260
|
+
except KeyboardInterrupt:
|
|
261
|
+
return 0
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---------------------------------------------------------------------------
|
|
265
|
+
# warm
|
|
266
|
+
# ---------------------------------------------------------------------------
|
|
267
|
+
TERMS = """\
|
|
268
|
+
Warm-up sends real requests with your own logins, on a schedule, with no one at the keyboard.
|
|
269
|
+
|
|
270
|
+
Anthropic's Consumer Terms (https://www.anthropic.com/legal/consumer-terms), section on what
|
|
271
|
+
you may not do: "Except when you are accessing our Services via an Anthropic API Key or where
|
|
272
|
+
we otherwise explicitly permit it, to access the Services through automated or non-human means,
|
|
273
|
+
whether through a bot, script, or otherwise."
|
|
274
|
+
A scheduled `claude -p` on a Pro or Max login can fall under that. Claude accounts on
|
|
275
|
+
Team or Enterprise terms, or with permission from Anthropic, are your own call.
|
|
276
|
+
|
|
277
|
+
OpenAI's Terms of Use (https://openai.com/policies/terms-of-use/) bar "automatically or
|
|
278
|
+
programmatically extracting data or Output" and sharing or making your account available to others.
|
|
279
|
+
|
|
280
|
+
Turning this on is your decision and your risk: llmswap does not check your plan's terms for you.
|
|
281
|
+
Only use accounts you own."""
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _confirm_terms(accepted_flag: bool) -> bool:
|
|
285
|
+
print(TERMS)
|
|
286
|
+
if accepted_flag:
|
|
287
|
+
return True
|
|
288
|
+
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
289
|
+
print("\nRe-run with --i-accept-provider-terms to confirm you have read this.", file=sys.stderr)
|
|
290
|
+
return False
|
|
291
|
+
return input("\nType 'yes' to confirm you have read this and want warm-up on: ").strip().lower() == "yes"
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _clock(epoch: float | None) -> str:
|
|
295
|
+
return "-" if epoch is None else datetime.fromtimestamp(epoch).astimezone().strftime("%a %H:%M")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _canon(ref_text: str) -> str:
|
|
299
|
+
pid, ref = split_ref(ref_text)
|
|
300
|
+
if ref is None:
|
|
301
|
+
raise ProviderError(f"name the account, e.g. {pid}:2")
|
|
302
|
+
p = registry.get(pid)
|
|
303
|
+
v = resolve_ref(p.accounts(), ref)
|
|
304
|
+
if v is None:
|
|
305
|
+
raise ProviderError(f"no {p.display} account matches {ref!r}")
|
|
306
|
+
return f"{pid}:{v.number}"
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def cmd_warm(args: argparse.Namespace) -> int:
|
|
310
|
+
from llmswap import config
|
|
311
|
+
from llmswap.warm import plan, runner, schedule
|
|
312
|
+
|
|
313
|
+
cfg = config.load_warm()
|
|
314
|
+
act = args.warm_cmd
|
|
315
|
+
if act in (None, "status"):
|
|
316
|
+
return _warm_status(cfg)
|
|
317
|
+
if act == "tick":
|
|
318
|
+
lines = runner.tick(dry_run=args.dry_run, force_enabled=args.dry_run)
|
|
319
|
+
if not args.quiet:
|
|
320
|
+
for ln in lines:
|
|
321
|
+
print(f"{ln.ref}: {ln.action} - {ln.detail}")
|
|
322
|
+
return 0 if all(l.action != "failed" for l in lines) else 1
|
|
323
|
+
if act == "add":
|
|
324
|
+
refs = [_canon(r) for r in args.accounts]
|
|
325
|
+
if args.all:
|
|
326
|
+
# Claude is left out of --all on purpose: Anthropic's terms are the
|
|
327
|
+
# strictest (see `llmswap warm enable`), so each Claude account is a
|
|
328
|
+
# deliberate, named choice.
|
|
329
|
+
refs = [f"{p.id}:{v.number}" for p in registry.all_providers()
|
|
330
|
+
if p.id != "claude" and "warm" in p.capabilities and p.installed()
|
|
331
|
+
for v in p.accounts() if v.kind == "oauth"]
|
|
332
|
+
for ref in refs:
|
|
333
|
+
if "warm" not in registry.get(ref.partition(":")[0]).capabilities:
|
|
334
|
+
return _err(f"{ref.partition(':')[0]} has no 5-hour window to warm")
|
|
335
|
+
cfg.accounts[ref] = config.AccountWarm(model=args.model, earliest=args.earliest)
|
|
336
|
+
config.save_warm(cfg)
|
|
337
|
+
print("Warm-up accounts: " + (", ".join(sorted(cfg.accounts)) or "none"))
|
|
338
|
+
if not cfg.enabled:
|
|
339
|
+
print("Warm-up is off. Turn it on with `llmswap warm enable`.")
|
|
340
|
+
return 0
|
|
341
|
+
if act == "remove":
|
|
342
|
+
for r in args.accounts:
|
|
343
|
+
cfg.accounts.pop(_canon(r), None)
|
|
344
|
+
config.save_warm(cfg)
|
|
345
|
+
return 0
|
|
346
|
+
if act == "quiet":
|
|
347
|
+
if args.off:
|
|
348
|
+
cfg.quiet_start = cfg.quiet_end = None
|
|
349
|
+
else:
|
|
350
|
+
config.parse_hhmm(args.start)
|
|
351
|
+
config.parse_hhmm(args.end)
|
|
352
|
+
cfg.quiet_start, cfg.quiet_end = args.start, args.end
|
|
353
|
+
config.save_warm(cfg)
|
|
354
|
+
return 0
|
|
355
|
+
if act == "enable":
|
|
356
|
+
if not cfg.accounts:
|
|
357
|
+
return _err("choose accounts first: llmswap warm add codex:1 claude:1 (or --all)")
|
|
358
|
+
if not cfg.terms_accepted:
|
|
359
|
+
if not _confirm_terms(args.i_accept_provider_terms):
|
|
360
|
+
return 1
|
|
361
|
+
cfg.terms_accepted = True
|
|
362
|
+
cfg.enabled = True
|
|
363
|
+
if args.interval:
|
|
364
|
+
cfg.interval_minutes = min(60, max(1, args.interval))
|
|
365
|
+
config.save_warm(cfg)
|
|
366
|
+
if not args.no_schedule:
|
|
367
|
+
kind = schedule.install(cfg.interval_minutes)
|
|
368
|
+
print(f"Warm-up on. Checking every {cfg.interval_minutes} min through {kind}.")
|
|
369
|
+
else:
|
|
370
|
+
print("Warm-up on. Run `llmswap warm tick` from your own scheduler.")
|
|
371
|
+
return 0
|
|
372
|
+
if act == "disable":
|
|
373
|
+
cfg.enabled = False
|
|
374
|
+
config.save_warm(cfg)
|
|
375
|
+
if not args.keep_schedule:
|
|
376
|
+
schedule.uninstall()
|
|
377
|
+
print("Warm-up off.")
|
|
378
|
+
return 0
|
|
379
|
+
if act == "now":
|
|
380
|
+
pid, ref = split_ref(args.account)
|
|
381
|
+
p = registry.get(pid)
|
|
382
|
+
v = p.find(ref or "")
|
|
383
|
+
out = p.warm(v.number, prompt=cfg.prompt)
|
|
384
|
+
print("pinged" if out.ok else f"ping failed: {out.detail}")
|
|
385
|
+
return 0 if out.ok else 1
|
|
386
|
+
return _err(f"unknown warm command {act!r}")
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _warm_status(cfg) -> int:
|
|
390
|
+
from llmswap.warm import plan, runner, schedule
|
|
391
|
+
|
|
392
|
+
on = "on" if cfg.enabled else "off"
|
|
393
|
+
sched = "installed" if schedule.installed() else "not installed"
|
|
394
|
+
print(f"Warm-up: {on}; scheduler {sched}; every {cfg.interval_minutes} min")
|
|
395
|
+
if cfg.quiet_start and cfg.quiet_end:
|
|
396
|
+
print(f"Quiet hours: {cfg.quiet_start}-{cfg.quiet_end}")
|
|
397
|
+
if not cfg.accounts:
|
|
398
|
+
print("No accounts chosen. Add some with: llmswap warm add codex:1 claude:1")
|
|
399
|
+
return 0
|
|
400
|
+
state = runner.load_state()
|
|
401
|
+
now = datetime.now().astimezone()
|
|
402
|
+
for ref, account in sorted(cfg.accounts.items()):
|
|
403
|
+
pid, _, num = ref.partition(":")
|
|
404
|
+
try:
|
|
405
|
+
p = registry.get(pid)
|
|
406
|
+
v = resolve_ref(p.accounts(), num)
|
|
407
|
+
except ProviderError:
|
|
408
|
+
v = None
|
|
409
|
+
if v is None:
|
|
410
|
+
print(f" {ref}: account not found")
|
|
411
|
+
continue
|
|
412
|
+
rec = state.get(ref, {})
|
|
413
|
+
d = plan.decide(v, account, cfg, now, last_warm=rec.get("last_warm"),
|
|
414
|
+
fail_count=int(rec.get("fail_count", 0)), last_attempt=rec.get("last_attempt"))
|
|
415
|
+
nxt = "due now" if d.ping else f"{d.reason}" + (f", next look {_clock(d.look_again_at)}" if d.look_again_at else "")
|
|
416
|
+
print(f" {ref} {v.email or ''}: {nxt}; last ping {_clock(rec.get('last_warm'))}")
|
|
417
|
+
return 0
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ---------------------------------------------------------------------------
|
|
421
|
+
# parser
|
|
422
|
+
# ---------------------------------------------------------------------------
|
|
423
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
424
|
+
ap = argparse.ArgumentParser(
|
|
425
|
+
prog="llmswap",
|
|
426
|
+
description="One account switcher for Claude Code, Codex and Gemini CLI.",
|
|
427
|
+
epilog="Per-provider commands: llmswap <provider> add|login|switch|run|remove|alias|enable|disable|usage",
|
|
428
|
+
)
|
|
429
|
+
ap.add_argument("--version", action="version", version=f"llmswap {__version__}")
|
|
430
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
431
|
+
|
|
432
|
+
s = sub.add_parser("list", aliases=["ls", "status"], help="accounts and usage for every provider")
|
|
433
|
+
s.add_argument("providers", nargs="*")
|
|
434
|
+
s.add_argument("-r", "--refresh", action="store_true", help="read usage from the network now")
|
|
435
|
+
s.add_argument("--json", action="store_true")
|
|
436
|
+
s.set_defaults(fn=cmd_list)
|
|
437
|
+
|
|
438
|
+
s = sub.add_parser("providers", help="which providers llmswap supports and what each can do")
|
|
439
|
+
s.set_defaults(fn=cmd_providers)
|
|
440
|
+
|
|
441
|
+
s = sub.add_parser("add", help="save the login each CLI is signed in with now")
|
|
442
|
+
s.add_argument("provider", nargs="?")
|
|
443
|
+
s.set_defaults(fn=cmd_add)
|
|
444
|
+
|
|
445
|
+
s = sub.add_parser("switch", help="make an account the default login: llmswap switch codex:2")
|
|
446
|
+
s.add_argument("target")
|
|
447
|
+
s.set_defaults(fn=cmd_switch)
|
|
448
|
+
|
|
449
|
+
s = sub.add_parser("run", help="run a CLI as an account in this terminal: llmswap run codex:2 -- args")
|
|
450
|
+
s.add_argument("target")
|
|
451
|
+
s.add_argument("rest", nargs=argparse.REMAINDER)
|
|
452
|
+
s.set_defaults(fn=cmd_run)
|
|
453
|
+
|
|
454
|
+
s = sub.add_parser("auto", help="rotate to another account before the active one hits a limit")
|
|
455
|
+
s.add_argument("--once", action="store_true")
|
|
456
|
+
s.add_argument("--dry-run", action="store_true")
|
|
457
|
+
s.add_argument("--threshold", type=float, default=90.0)
|
|
458
|
+
s.add_argument("--interval", type=int, default=60)
|
|
459
|
+
s.add_argument("--quiet", action="store_true")
|
|
460
|
+
s.set_defaults(fn=cmd_auto)
|
|
461
|
+
|
|
462
|
+
w = sub.add_parser("warm", help="start each account's 5-hour window early, on a schedule")
|
|
463
|
+
w.set_defaults(fn=cmd_warm, warm_cmd=None, dry_run=False, quiet=False)
|
|
464
|
+
ws = w.add_subparsers(dest="warm_cmd")
|
|
465
|
+
ws.add_parser("status")
|
|
466
|
+
t = ws.add_parser("tick", help="one pass; this is what the scheduler runs")
|
|
467
|
+
t.add_argument("--dry-run", action="store_true")
|
|
468
|
+
t.add_argument("--quiet", action="store_true")
|
|
469
|
+
t = ws.add_parser("add", help="choose accounts to warm: codex:1 claude:2")
|
|
470
|
+
t.add_argument("accounts", nargs="*")
|
|
471
|
+
t.add_argument("--all", action="store_true")
|
|
472
|
+
t.add_argument("--model")
|
|
473
|
+
t.add_argument("--earliest", help="HH:MM, never start a window before this time")
|
|
474
|
+
t = ws.add_parser("remove")
|
|
475
|
+
t.add_argument("accounts", nargs="+")
|
|
476
|
+
t = ws.add_parser("quiet", help="no pings between START and END, e.g. quiet 23:00 07:00")
|
|
477
|
+
t.add_argument("start", nargs="?")
|
|
478
|
+
t.add_argument("end", nargs="?")
|
|
479
|
+
t.add_argument("--off", action="store_true")
|
|
480
|
+
t = ws.add_parser("enable", help="turn warm-up on and install the scheduler")
|
|
481
|
+
t.add_argument("--i-accept-provider-terms", action="store_true", help="confirm you have read your providers' terms (asked once)")
|
|
482
|
+
t.add_argument("--interval", type=int)
|
|
483
|
+
t.add_argument("--no-schedule", action="store_true")
|
|
484
|
+
t = ws.add_parser("disable", help="turn warm-up off and remove the scheduler")
|
|
485
|
+
t.add_argument("--keep-schedule", action="store_true")
|
|
486
|
+
t = ws.add_parser("now", help="ping one account right now")
|
|
487
|
+
t.add_argument("account")
|
|
488
|
+
|
|
489
|
+
sub.add_parser("tui", help="the dashboard").set_defaults(fn=lambda a: cmd_tui())
|
|
490
|
+
s = sub.add_parser("menubar", help="macOS menu bar, kept running by launchd")
|
|
491
|
+
s.add_argument("--foreground", action="store_true", help="draw it in this process (what launchd runs)")
|
|
492
|
+
s.add_argument("--uninstall", action="store_true", help="stop it and remove the launchd job")
|
|
493
|
+
s.set_defaults(fn=cmd_menubar)
|
|
494
|
+
return ap
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def cmd_tui() -> int:
|
|
498
|
+
from llmswap import tui
|
|
499
|
+
|
|
500
|
+
return tui.run()
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def cmd_menubar(args: argparse.Namespace) -> int:
|
|
504
|
+
from llmswap import menubar
|
|
505
|
+
|
|
506
|
+
return menubar.run([f for f, on in (("--foreground", args.foreground), ("--uninstall", args.uninstall)) if on])
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def main(argv: list[str] | None = None) -> None:
|
|
510
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
511
|
+
try:
|
|
512
|
+
sys.exit(_dispatch(argv))
|
|
513
|
+
except ProviderError as exc:
|
|
514
|
+
sys.exit(_err(str(exc)))
|
|
515
|
+
except KeyboardInterrupt:
|
|
516
|
+
sys.exit(130)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _dispatch(argv: list[str]) -> int:
|
|
520
|
+
if argv and argv[0] in registry.provider_ids():
|
|
521
|
+
return cmd_provider(argparse.Namespace(provider=argv[0], rest_all=argv[1:]))
|
|
522
|
+
if not argv:
|
|
523
|
+
if sys.stdout.isatty() and sys.stdin.isatty():
|
|
524
|
+
return cmd_tui()
|
|
525
|
+
argv = ["list"]
|
|
526
|
+
ap = build_parser()
|
|
527
|
+
args = ap.parse_args(argv)
|
|
528
|
+
if not getattr(args, "fn", None):
|
|
529
|
+
ap.print_help()
|
|
530
|
+
return 0
|
|
531
|
+
return args.fn(args)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
if __name__ == "__main__":
|
|
535
|
+
main()
|
llmswap/config.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""llmswap's own settings (``config.json`` under the llmswap root).
|
|
2
|
+
|
|
3
|
+
Only warm-up settings live here today. Everything is opt-in: a fresh install
|
|
4
|
+
pings nothing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from claude_swap.fsutil import atomic_write_text
|
|
13
|
+
|
|
14
|
+
from llmswap import paths
|
|
15
|
+
|
|
16
|
+
DEFAULT_PROMPT = "Reply with the single word: ok"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class AccountWarm:
|
|
21
|
+
enabled: bool = True
|
|
22
|
+
model: str | None = None
|
|
23
|
+
earliest: str | None = None # "HH:MM": never start a window before this local time
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class WarmConfig:
|
|
28
|
+
enabled: bool = False
|
|
29
|
+
terms_accepted: bool = False # the user confirmed they read their providers' terms
|
|
30
|
+
interval_minutes: int = 5
|
|
31
|
+
quiet_start: str | None = None # "HH:MM" local; no pings from here ...
|
|
32
|
+
quiet_end: str | None = None # ... until here (may wrap midnight)
|
|
33
|
+
prompt: str = DEFAULT_PROMPT
|
|
34
|
+
accounts: dict[str, AccountWarm] = field(default_factory=dict) # "codex:2" -> settings
|
|
35
|
+
|
|
36
|
+
def to_json(self) -> dict:
|
|
37
|
+
return {
|
|
38
|
+
"enabled": self.enabled,
|
|
39
|
+
"terms_accepted": self.terms_accepted,
|
|
40
|
+
"interval_minutes": self.interval_minutes,
|
|
41
|
+
"quiet_hours": {"start": self.quiet_start, "end": self.quiet_end},
|
|
42
|
+
"prompt": self.prompt,
|
|
43
|
+
"accounts": {
|
|
44
|
+
ref: {"enabled": a.enabled, "model": a.model, "earliest": a.earliest}
|
|
45
|
+
for ref, a in sorted(self.accounts.items())
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_json(cls, data: dict) -> "WarmConfig":
|
|
51
|
+
quiet = data.get("quiet_hours") or {}
|
|
52
|
+
accounts = {}
|
|
53
|
+
for ref, body in (data.get("accounts") or {}).items():
|
|
54
|
+
body = body or {}
|
|
55
|
+
accounts[str(ref)] = AccountWarm(
|
|
56
|
+
enabled=bool(body.get("enabled", True)),
|
|
57
|
+
model=body.get("model"),
|
|
58
|
+
earliest=body.get("earliest"),
|
|
59
|
+
)
|
|
60
|
+
try:
|
|
61
|
+
interval = int(data.get("interval_minutes", 5))
|
|
62
|
+
except (TypeError, ValueError):
|
|
63
|
+
interval = 5
|
|
64
|
+
return cls(
|
|
65
|
+
enabled=bool(data.get("enabled", False)),
|
|
66
|
+
terms_accepted=bool(data.get("terms_accepted", False)),
|
|
67
|
+
interval_minutes=min(60, max(1, interval)),
|
|
68
|
+
quiet_start=quiet.get("start"),
|
|
69
|
+
quiet_end=quiet.get("end"),
|
|
70
|
+
prompt=str(data.get("prompt") or DEFAULT_PROMPT),
|
|
71
|
+
accounts=accounts,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_warm() -> WarmConfig:
|
|
76
|
+
try:
|
|
77
|
+
data = json.loads(paths.config_path().read_text(encoding="utf-8"))
|
|
78
|
+
except (OSError, ValueError):
|
|
79
|
+
data = {}
|
|
80
|
+
return WarmConfig.from_json(data.get("warmup") or {})
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def save_warm(cfg: WarmConfig) -> None:
|
|
84
|
+
try:
|
|
85
|
+
data = json.loads(paths.config_path().read_text(encoding="utf-8"))
|
|
86
|
+
except (OSError, ValueError):
|
|
87
|
+
data = {}
|
|
88
|
+
data["warmup"] = cfg.to_json()
|
|
89
|
+
paths.config_path().parent.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
atomic_write_text(paths.config_path(), json.dumps(data, indent=2, sort_keys=True))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_hhmm(text: str) -> tuple[int, int]:
|
|
94
|
+
try:
|
|
95
|
+
h, m = text.split(":")
|
|
96
|
+
hh, mm = int(h), int(m)
|
|
97
|
+
except ValueError:
|
|
98
|
+
raise ValueError(f"{text!r} is not a time like 07:30") from None
|
|
99
|
+
if not (0 <= hh < 24 and 0 <= mm < 60):
|
|
100
|
+
raise ValueError(f"{text!r} is not a time like 07:30")
|
|
101
|
+
return hh, mm
|