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
claude_swap/cli.py
ADDED
|
@@ -0,0 +1,2265 @@
|
|
|
1
|
+
"""Command-line interface for Claude Swap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from claude_swap import __version__, paths, printer
|
|
13
|
+
from claude_swap.exceptions import ClaudeSwitchError, SessionError
|
|
14
|
+
from claude_swap.json_output import error_envelope
|
|
15
|
+
from claude_swap.models import (
|
|
16
|
+
ACCOUNT_PRIORITY_MAX,
|
|
17
|
+
ACCOUNT_THRESHOLD_MAX,
|
|
18
|
+
ACCOUNT_THRESHOLD_MIN,
|
|
19
|
+
)
|
|
20
|
+
from claude_swap.printer import (
|
|
21
|
+
accent,
|
|
22
|
+
bolded,
|
|
23
|
+
dimmed,
|
|
24
|
+
error,
|
|
25
|
+
force_utf8_output,
|
|
26
|
+
muted,
|
|
27
|
+
warning,
|
|
28
|
+
)
|
|
29
|
+
from claude_swap.settings import (
|
|
30
|
+
AUTOSWITCH_STRATEGIES,
|
|
31
|
+
load_ui_settings,
|
|
32
|
+
load_update_settings,
|
|
33
|
+
)
|
|
34
|
+
from claude_swap.switcher import ClaudeAccountSwitcher
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _prog_name() -> str:
|
|
38
|
+
"""The command name to show in usage/help.
|
|
39
|
+
|
|
40
|
+
argparse otherwise defaults to ``os.path.basename(sys.argv[0])``, which for
|
|
41
|
+
an installed entry-point shim renders as an ugly absolute path (e.g.
|
|
42
|
+
``python.exe C:\\Users\\me\\.local\\bin\\cswap``). We strip that down to the
|
|
43
|
+
bare command the user typed (``cswap`` / ``claude-swap``), falling back to
|
|
44
|
+
``cswap`` for ``python -m claude_swap`` and odd launchers.
|
|
45
|
+
"""
|
|
46
|
+
name = os.path.basename(sys.argv[0] or "")
|
|
47
|
+
for ext in (".exe", ".pyw", ".py"):
|
|
48
|
+
if name.lower().endswith(ext):
|
|
49
|
+
name = name[: -len(ext)]
|
|
50
|
+
break
|
|
51
|
+
if not name or name in {"__main__", "python", "python3", "py"}:
|
|
52
|
+
return "cswap"
|
|
53
|
+
return name
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# Memorable subcommand aliases → the long-standing flags they expand to. Lets
|
|
57
|
+
# users type `cswap list`, `cswap status`, `cswap add`, etc. instead of `--list`
|
|
58
|
+
# / `--status` / `--add-account`, which all still work. `switch` is special-cased
|
|
59
|
+
# below (a bare `switch` rotates; `switch <target>` jumps to one account) and
|
|
60
|
+
# `run`/`rc`/`auto` keep their own pre-dispatch parsers, so none of those are listed here.
|
|
61
|
+
_SUBCOMMAND_FLAGS = {
|
|
62
|
+
"help": "--help",
|
|
63
|
+
"list": "--list",
|
|
64
|
+
"ls": "--list",
|
|
65
|
+
"status": "--status",
|
|
66
|
+
"add": "--add-account",
|
|
67
|
+
"login": "--login",
|
|
68
|
+
"add-token": "--add-token",
|
|
69
|
+
"remove": "--remove-account",
|
|
70
|
+
"rm": "--remove-account",
|
|
71
|
+
"disable": "--disable-account",
|
|
72
|
+
"enable": "--enable-account",
|
|
73
|
+
"export": "--export",
|
|
74
|
+
"import": "--import",
|
|
75
|
+
"import-usage": "--import-usage",
|
|
76
|
+
"purge": "--purge",
|
|
77
|
+
"upgrade": "--upgrade",
|
|
78
|
+
"update": "--upgrade",
|
|
79
|
+
"tui": "--tui",
|
|
80
|
+
"watch": "--watch",
|
|
81
|
+
"menubar": "--menubar",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _translate_subcommand(argv: list[str]) -> list[str]:
|
|
86
|
+
"""Rewrite a leading memorable subcommand into the equivalent flag argv.
|
|
87
|
+
|
|
88
|
+
``argv`` is the args after the program name. The rewrite only fires when the
|
|
89
|
+
first token is a recognized verb (which never starts with '-'), so the
|
|
90
|
+
established ``--flag`` interface — and every existing test that drives it —
|
|
91
|
+
is left untouched. Tokens after the verb pass through verbatim, so flags
|
|
92
|
+
like ``--json``, ``--strategy``, ``--slot``, and ``--force`` keep combining
|
|
93
|
+
exactly as before (e.g. ``cswap switch --strategy best``, ``cswap list --json``).
|
|
94
|
+
"""
|
|
95
|
+
if not argv:
|
|
96
|
+
return argv
|
|
97
|
+
|
|
98
|
+
verb, rest = argv[0], argv[1:]
|
|
99
|
+
|
|
100
|
+
if verb == "switch":
|
|
101
|
+
# Bare `switch` rotates; `switch <num|email>` jumps to that account.
|
|
102
|
+
if rest and not rest[0].startswith("-"):
|
|
103
|
+
return ["--switch-to", *rest]
|
|
104
|
+
return ["--switch", *rest]
|
|
105
|
+
|
|
106
|
+
flag = _SUBCOMMAND_FLAGS.get(verb)
|
|
107
|
+
if flag is not None:
|
|
108
|
+
return [flag, *rest]
|
|
109
|
+
|
|
110
|
+
return argv
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _run_command(argv: list[str]) -> None:
|
|
114
|
+
"""Handle `cswap run NUM|EMAIL [--no-share] [-- <claude args>]`.
|
|
115
|
+
|
|
116
|
+
Pre-dispatched before the main parser is built: a positional subcommand
|
|
117
|
+
can't coexist with main()'s mutually-exclusive flag group, and this keeps
|
|
118
|
+
the existing parser untouched. Limitation: `run` must be the
|
|
119
|
+
first argument (`cswap --debug run 2` is not supported; use
|
|
120
|
+
`cswap run 2 --debug`).
|
|
121
|
+
|
|
122
|
+
On POSIX this execs claude and never returns; on Windows it exits with
|
|
123
|
+
claude's return code. Either way the post-dispatch update check in
|
|
124
|
+
main() is unreachable, which is intended.
|
|
125
|
+
"""
|
|
126
|
+
# Everything after the first `--` is forwarded to claude verbatim.
|
|
127
|
+
if "--" in argv:
|
|
128
|
+
split = argv.index("--")
|
|
129
|
+
head, tail = argv[:split], argv[split + 1 :]
|
|
130
|
+
else:
|
|
131
|
+
head, tail = argv, []
|
|
132
|
+
|
|
133
|
+
parser = argparse.ArgumentParser(
|
|
134
|
+
prog=f"{_prog_name()} run",
|
|
135
|
+
description=(
|
|
136
|
+
"[EXPERIMENTAL] Launch Claude Code as a stored account in this "
|
|
137
|
+
"terminal only (the default login and other terminals are "
|
|
138
|
+
"unaffected)."
|
|
139
|
+
),
|
|
140
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
141
|
+
epilog="""
|
|
142
|
+
Examples:
|
|
143
|
+
cswap run 2
|
|
144
|
+
cswap run user@example.com
|
|
145
|
+
cswap run 2 --no-share
|
|
146
|
+
cswap run 2 --no-share-history
|
|
147
|
+
cswap run 2 --require-session
|
|
148
|
+
cswap run 2 -- --resume
|
|
149
|
+
""",
|
|
150
|
+
)
|
|
151
|
+
parser.add_argument(
|
|
152
|
+
"account",
|
|
153
|
+
nargs="?",
|
|
154
|
+
metavar="NUM|EMAIL",
|
|
155
|
+
help="Account to run (number or email). Omit to use the current "
|
|
156
|
+
"directory's mapping (see `cswap map`).",
|
|
157
|
+
)
|
|
158
|
+
_add_session_options(parser)
|
|
159
|
+
args = parser.parse_args(head)
|
|
160
|
+
|
|
161
|
+
# The parser's --help belongs on stdout. Nothing printed after it does:
|
|
162
|
+
# see _run_launch.
|
|
163
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
164
|
+
_run_launch(args, tail)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _add_session_options(parser: argparse.ArgumentParser) -> None:
|
|
168
|
+
"""Add the options `cswap run` and `cswap rc` share."""
|
|
169
|
+
parser.add_argument(
|
|
170
|
+
"--no-share",
|
|
171
|
+
action="store_true",
|
|
172
|
+
help=(
|
|
173
|
+
"Don't share settings/keybindings/CLAUDE.md/skills/commands/agents/rules "
|
|
174
|
+
"from ~/.claude into the session profile (and remove previously "
|
|
175
|
+
"shared items). Chat history is not affected: see "
|
|
176
|
+
"--no-share-history"
|
|
177
|
+
),
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument(
|
|
180
|
+
"--share-history",
|
|
181
|
+
action=argparse.BooleanOptionalAction,
|
|
182
|
+
default=None,
|
|
183
|
+
help=(
|
|
184
|
+
"Share conversation history (projects/ and history.jsonl) from "
|
|
185
|
+
"~/.claude into the session profile, so every account sees one "
|
|
186
|
+
"unified history. This is the default; history the profile "
|
|
187
|
+
"already accumulated is merged into ~/.claude first. "
|
|
188
|
+
"--no-share-history keeps this account's history separate for "
|
|
189
|
+
"this launch, `cswap config set run.shareHistory false` for "
|
|
190
|
+
"every launch. On Windows, projects/ is shared either way and "
|
|
191
|
+
"history.jsonl only when symlinks are allowed (Developer Mode, "
|
|
192
|
+
"or an elevated terminal)."
|
|
193
|
+
),
|
|
194
|
+
)
|
|
195
|
+
parser.add_argument(
|
|
196
|
+
"--require-session",
|
|
197
|
+
action="store_true",
|
|
198
|
+
help=(
|
|
199
|
+
"Refuse to launch when the launch would run plain claude on the "
|
|
200
|
+
"default login (which a later switch could pull out from under "
|
|
201
|
+
"the session) instead of in a session profile: the account is "
|
|
202
|
+
"already the active default login, or no account is given and "
|
|
203
|
+
"the current directory has no mapped account"
|
|
204
|
+
),
|
|
205
|
+
)
|
|
206
|
+
parser.add_argument(
|
|
207
|
+
"--debug",
|
|
208
|
+
action="store_true",
|
|
209
|
+
help="Enable debug logging",
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
_RC_DESCRIPTION = """\
|
|
214
|
+
[EXPERIMENTAL] Start Claude Code Remote Control as a stored account: short
|
|
215
|
+
for `cswap run NUM|EMAIL -- remote-control`, with the launch rules of
|
|
216
|
+
`cswap run`. `rc` and `remote-control` are one command.
|
|
217
|
+
|
|
218
|
+
NUM|EMAIL Account (number or email). Omit to use the current directory's
|
|
219
|
+
mapping (see `cswap map`).
|
|
220
|
+
NAME Session name, as claude.ai/code shows it. A single argument is
|
|
221
|
+
always the account: with the mapping, use -n.
|
|
222
|
+
|
|
223
|
+
An option not listed below goes to `claude remote-control` as typed, with the
|
|
224
|
+
arguments after it, so the account and the name come first. `--debug` is
|
|
225
|
+
cswap's own: claude's is `-d`, or goes after `--`.
|
|
226
|
+
|
|
227
|
+
Examples:
|
|
228
|
+
cswap rc 2 laptop
|
|
229
|
+
cswap rc -n laptop -w -c
|
|
230
|
+
cswap rc 2 --capacity 4
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _rc_command(verb: str, argv: list[str]) -> None:
|
|
235
|
+
"""Handle `cswap rc [NUM|EMAIL] [NAME] [options] [-- <claude args>]`.
|
|
236
|
+
|
|
237
|
+
`cswap run` with ``remote-control`` in front of the forwarded arguments,
|
|
238
|
+
under either spelling (``verb``). `claude rc` is the short form of that
|
|
239
|
+
subcommand, and the shortcuts stand for options its help lists (Claude
|
|
240
|
+
Code 2.1.333).
|
|
241
|
+
|
|
242
|
+
The parser has no positional and no abbreviation, on purpose. What it
|
|
243
|
+
does not know is forwarded, so a positional would take the value of a
|
|
244
|
+
claude option (``--spawn worktree``) for the account or the name, and an
|
|
245
|
+
abbreviation would take a claude option that starts like one of ours. An
|
|
246
|
+
option claude does not know is claude's to refuse: it prints ``Error:
|
|
247
|
+
Unknown argument`` and exits 1.
|
|
248
|
+
"""
|
|
249
|
+
split = argv.index("--") if "--" in argv else len(argv)
|
|
250
|
+
parser = argparse.ArgumentParser(
|
|
251
|
+
prog=f"{_prog_name()} {verb}",
|
|
252
|
+
usage="%(prog)s [NUM|EMAIL] [NAME] [options] [claude options] [-- claude args]",
|
|
253
|
+
description=_RC_DESCRIPTION,
|
|
254
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
255
|
+
allow_abbrev=False,
|
|
256
|
+
)
|
|
257
|
+
parser.add_argument("-n", "--name", metavar="NAME", help="Same as NAME")
|
|
258
|
+
parser.add_argument(
|
|
259
|
+
"-c",
|
|
260
|
+
"--continue",
|
|
261
|
+
dest="continue_last",
|
|
262
|
+
action="store_true",
|
|
263
|
+
help="Reattach to the session last recorded for this directory",
|
|
264
|
+
)
|
|
265
|
+
parser.add_argument(
|
|
266
|
+
"-w",
|
|
267
|
+
"--worktree",
|
|
268
|
+
action="store_true",
|
|
269
|
+
help="A git worktree per session started on demand (`--spawn worktree`)",
|
|
270
|
+
)
|
|
271
|
+
_add_session_options(parser)
|
|
272
|
+
args, rest = parser.parse_known_args(argv[:split])
|
|
273
|
+
|
|
274
|
+
# In front of the first forwarded option: the account, then the name.
|
|
275
|
+
first_option = next(
|
|
276
|
+
(index for index, arg in enumerate(rest) if arg.startswith("-")), len(rest)
|
|
277
|
+
)
|
|
278
|
+
positionals, forwarded = rest[:first_option], rest[first_option:]
|
|
279
|
+
if len(positionals) > 2:
|
|
280
|
+
parser.error(f"unexpected argument: {positionals[2]}")
|
|
281
|
+
if len(positionals) == 2 and args.name is not None:
|
|
282
|
+
parser.error("the name is given twice: as NAME and with -n/--name")
|
|
283
|
+
args.account = positionals[0] if positionals else None
|
|
284
|
+
name = positionals[1] if len(positionals) == 2 else args.name
|
|
285
|
+
|
|
286
|
+
claude_args = ["remote-control"]
|
|
287
|
+
if name is not None:
|
|
288
|
+
claude_args += ["--name", name]
|
|
289
|
+
if args.continue_last:
|
|
290
|
+
claude_args.append("--continue")
|
|
291
|
+
if args.worktree:
|
|
292
|
+
claude_args += ["--spawn", "worktree"]
|
|
293
|
+
# Stdout is claude's here as well: see _run_launch.
|
|
294
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
295
|
+
_run_launch(args, [*claude_args, *forwarded, *argv[split + 1 :]])
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _run_launch(args: argparse.Namespace, tail: list[str]) -> None:
|
|
299
|
+
"""Resolve the account for `cswap run` or `cswap rc` and hand the terminal to claude.
|
|
300
|
+
|
|
301
|
+
With no account given, the current directory's mapping names it. When
|
|
302
|
+
that resolves to no account, what is left to launch is plain claude on
|
|
303
|
+
the default login, which ``--require-session`` refuses here, as
|
|
304
|
+
``SessionManager.run`` refuses its same-account fast path.
|
|
305
|
+
|
|
306
|
+
Runs with stdout redirected to stderr. Stdout belongs to claude, and a
|
|
307
|
+
caller may be reading it as data (`cswap run 2 -- -p ... --output-format
|
|
308
|
+
stream-json`), so a notice printed there lands in that stream: ahead of
|
|
309
|
+
claude's output when stdout is unbuffered, after it on Windows, where
|
|
310
|
+
cswap stays resident and flushes its buffer at exit. On a POSIX pipe it
|
|
311
|
+
is lost instead, because the exec discards what is still buffered.
|
|
312
|
+
|
|
313
|
+
The redirect covers every print on the way to the launch, the session
|
|
314
|
+
bootstrap's included, and rebinds only Python's ``sys.stdout``: claude
|
|
315
|
+
inherits the real stream.
|
|
316
|
+
"""
|
|
317
|
+
try:
|
|
318
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
319
|
+
_guard_root(switcher)
|
|
320
|
+
|
|
321
|
+
from claude_swap.session import SessionManager
|
|
322
|
+
|
|
323
|
+
manager = SessionManager(switcher)
|
|
324
|
+
|
|
325
|
+
# share_history goes through as given: None (neither flag) leaves it
|
|
326
|
+
# to run.shareHistory, which SessionManager.run resolves.
|
|
327
|
+
if args.account is not None:
|
|
328
|
+
manager.run(
|
|
329
|
+
args.account,
|
|
330
|
+
tail,
|
|
331
|
+
share=not args.no_share,
|
|
332
|
+
share_history=args.share_history,
|
|
333
|
+
require_session=args.require_session,
|
|
334
|
+
)
|
|
335
|
+
return # only reachable in tests where exec/exit is mocked
|
|
336
|
+
|
|
337
|
+
# No account given: resolve from the current directory's mapping.
|
|
338
|
+
# The mapping names an account and the slot is only where that
|
|
339
|
+
# account sat a moment ago, so the identity goes along: run refuses
|
|
340
|
+
# to launch when the slot holds another account by then.
|
|
341
|
+
slot, email, org_uuid = switcher.account_for_directory(os.getcwd())
|
|
342
|
+
if slot is not None and email is not None:
|
|
343
|
+
manager.run(
|
|
344
|
+
slot,
|
|
345
|
+
tail,
|
|
346
|
+
share=not args.no_share,
|
|
347
|
+
share_history=args.share_history,
|
|
348
|
+
require_session=args.require_session,
|
|
349
|
+
expected_identity=(email, org_uuid),
|
|
350
|
+
)
|
|
351
|
+
return # only reachable in tests
|
|
352
|
+
if args.require_session:
|
|
353
|
+
reason = (
|
|
354
|
+
f"Mapped account {email} no longer exists"
|
|
355
|
+
if email is not None
|
|
356
|
+
else f"No account is mapped for {os.getcwd()}"
|
|
357
|
+
)
|
|
358
|
+
raise SessionError(
|
|
359
|
+
f"{reason}, so this launch would run plain claude on the "
|
|
360
|
+
"default login rather than in a session profile, which "
|
|
361
|
+
"--require-session refuses. Pass an account (number or "
|
|
362
|
+
"email), or map this directory with `cswap map <NUM|EMAIL>`."
|
|
363
|
+
)
|
|
364
|
+
if email is not None:
|
|
365
|
+
warning(
|
|
366
|
+
f"Mapped account {email} no longer exists — "
|
|
367
|
+
"launching the default account."
|
|
368
|
+
)
|
|
369
|
+
else:
|
|
370
|
+
print(
|
|
371
|
+
dimmed(
|
|
372
|
+
f"No account mapped for {os.getcwd()} — "
|
|
373
|
+
"launching the default account."
|
|
374
|
+
)
|
|
375
|
+
)
|
|
376
|
+
manager.exec_default(tail)
|
|
377
|
+
except ClaudeSwitchError as e:
|
|
378
|
+
error(f"Error: {e}")
|
|
379
|
+
sys.exit(1)
|
|
380
|
+
except KeyboardInterrupt:
|
|
381
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
382
|
+
sys.exit(130)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _guard_root(switcher: ClaudeAccountSwitcher) -> None:
|
|
386
|
+
"""Refuse to run as root outside a container (shared by run/map/unmap)."""
|
|
387
|
+
if sys.platform != "win32":
|
|
388
|
+
if os.geteuid() == 0 and not switcher._is_running_in_container():
|
|
389
|
+
error("Error: Do not run this script as root (unless running in a container)")
|
|
390
|
+
sys.exit(1)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _person_at_terminal(args: argparse.Namespace) -> bool:
|
|
394
|
+
"""Whether a person is running this command and can answer a system prompt.
|
|
395
|
+
|
|
396
|
+
The switcher's ``interactive`` flag: it lets the macOS Keychain migration
|
|
397
|
+
wait for the permission window. False for ``--json`` (a program reads the
|
|
398
|
+
result, even from a terminal) and for the menu bar app (launchd runs it),
|
|
399
|
+
and otherwise true only when stdin and stderr are both terminals: stderr
|
|
400
|
+
carries the notice that says what the window is for.
|
|
401
|
+
"""
|
|
402
|
+
if args.json or args.menubar:
|
|
403
|
+
return False
|
|
404
|
+
try:
|
|
405
|
+
return sys.stdin.isatty() and sys.stderr.isatty()
|
|
406
|
+
except (AttributeError, ValueError): # a closed or replaced stream
|
|
407
|
+
return False
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _map_command(argv: list[str]) -> None:
|
|
411
|
+
"""Handle `cswap map [NUM|EMAIL] [PATH]`.
|
|
412
|
+
|
|
413
|
+
With no NUM|EMAIL, lists all mappings. Otherwise maps PATH (default: the
|
|
414
|
+
current directory) to the given account. Pre-dispatched before the main
|
|
415
|
+
parser for the same reason as `run` (the main parser's required
|
|
416
|
+
mutually-exclusive group can't hold a positional subcommand).
|
|
417
|
+
"""
|
|
418
|
+
parser = argparse.ArgumentParser(
|
|
419
|
+
prog="cswap map",
|
|
420
|
+
description=(
|
|
421
|
+
"Map a stored account to a directory so `cswap run` (with no "
|
|
422
|
+
"account) auto-launches it there. With no arguments, lists all "
|
|
423
|
+
"mappings."
|
|
424
|
+
),
|
|
425
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
426
|
+
epilog="""
|
|
427
|
+
Examples:
|
|
428
|
+
cswap map 2 ~/work/client-app
|
|
429
|
+
cswap map user@example.com # map the current directory
|
|
430
|
+
cswap map # list all mappings
|
|
431
|
+
""",
|
|
432
|
+
)
|
|
433
|
+
parser.add_argument(
|
|
434
|
+
"account",
|
|
435
|
+
nargs="?",
|
|
436
|
+
metavar="NUM|EMAIL",
|
|
437
|
+
help="Account to map (number or email). Omit to list mappings.",
|
|
438
|
+
)
|
|
439
|
+
parser.add_argument(
|
|
440
|
+
"path",
|
|
441
|
+
nargs="?",
|
|
442
|
+
metavar="PATH",
|
|
443
|
+
help="Directory to map (default: current directory)",
|
|
444
|
+
)
|
|
445
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
446
|
+
args = parser.parse_args(argv)
|
|
447
|
+
|
|
448
|
+
try:
|
|
449
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
450
|
+
_guard_root(switcher)
|
|
451
|
+
|
|
452
|
+
if args.account is None:
|
|
453
|
+
switcher.list_mappings()
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
from claude_swap.mappings import MappingStore, normalize_path
|
|
457
|
+
|
|
458
|
+
store = MappingStore(switcher.backup_dir)
|
|
459
|
+
account_num, email, org_uuid = switcher.resolve_account(args.account)
|
|
460
|
+
target = args.path or os.getcwd()
|
|
461
|
+
if not os.path.isdir(target):
|
|
462
|
+
warning(f"Warning: {target} is not an existing directory (mapping it anyway)")
|
|
463
|
+
previous = store.get(target)
|
|
464
|
+
store.set(target, email, org_uuid)
|
|
465
|
+
|
|
466
|
+
shown = normalize_path(target)
|
|
467
|
+
if previous and previous.get("email") != email:
|
|
468
|
+
prev_email = previous.get("email")
|
|
469
|
+
print(
|
|
470
|
+
f"{accent('Mapped')} {shown} → Account-{account_num} ({email}) "
|
|
471
|
+
f"{muted(f'(was {prev_email})')}"
|
|
472
|
+
)
|
|
473
|
+
else:
|
|
474
|
+
print(f"{accent('Mapped')} {shown} → Account-{account_num} ({email})")
|
|
475
|
+
except ClaudeSwitchError as e:
|
|
476
|
+
error(f"Error: {e}")
|
|
477
|
+
sys.exit(1)
|
|
478
|
+
except KeyboardInterrupt:
|
|
479
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
480
|
+
sys.exit(130)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _unmap_command(argv: list[str]) -> None:
|
|
484
|
+
"""Handle `cswap unmap [PATH]` — remove a directory→account mapping."""
|
|
485
|
+
parser = argparse.ArgumentParser(
|
|
486
|
+
prog="cswap unmap",
|
|
487
|
+
description="Remove a directory → account mapping (default: current directory).",
|
|
488
|
+
)
|
|
489
|
+
parser.add_argument(
|
|
490
|
+
"path",
|
|
491
|
+
nargs="?",
|
|
492
|
+
metavar="PATH",
|
|
493
|
+
help="Directory to unmap (default: current directory)",
|
|
494
|
+
)
|
|
495
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
496
|
+
args = parser.parse_args(argv)
|
|
497
|
+
|
|
498
|
+
try:
|
|
499
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
500
|
+
_guard_root(switcher)
|
|
501
|
+
|
|
502
|
+
from claude_swap.mappings import MappingStore, normalize_path
|
|
503
|
+
|
|
504
|
+
store = MappingStore(switcher.backup_dir)
|
|
505
|
+
target = args.path or os.getcwd()
|
|
506
|
+
shown = normalize_path(target)
|
|
507
|
+
if store.remove(target):
|
|
508
|
+
print(f"{accent('Unmapped')} {shown}")
|
|
509
|
+
else:
|
|
510
|
+
print(dimmed(f"No mapping for {shown}"))
|
|
511
|
+
except ClaudeSwitchError as e:
|
|
512
|
+
error(f"Error: {e}")
|
|
513
|
+
sys.exit(1)
|
|
514
|
+
except KeyboardInterrupt:
|
|
515
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
516
|
+
sys.exit(130)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _unclaimed_command(argv: list[str]) -> None:
|
|
520
|
+
"""Handle `cswap unclaimed [--purge ID]` — inspect or drop a stash row.
|
|
521
|
+
|
|
522
|
+
The stash holds credential bytes a switch or a consume gate could not
|
|
523
|
+
attribute to a slot. Rows normally clear themselves (the next gate pass
|
|
524
|
+
adopts or retires them), but two states need a human: a row whose bytes
|
|
525
|
+
are unreadable until a keychain is unlocked or a mode is fixed, and one
|
|
526
|
+
whose metadata was lost, which no pass can ever adopt. ``--json`` lists
|
|
527
|
+
only bare ids, so without this there is nothing to look at and nothing to
|
|
528
|
+
drop short of hand-editing the manifest.
|
|
529
|
+
"""
|
|
530
|
+
parser = argparse.ArgumentParser(
|
|
531
|
+
prog=f"{_prog_name()} unclaimed",
|
|
532
|
+
description=(
|
|
533
|
+
"List stashed credential entries, or purge one by id. "
|
|
534
|
+
"Purging deletes the bytes — recovery is `cswap login`."
|
|
535
|
+
),
|
|
536
|
+
)
|
|
537
|
+
parser.add_argument(
|
|
538
|
+
"--purge",
|
|
539
|
+
metavar="ID",
|
|
540
|
+
help="Delete this entry's bytes and manifest row",
|
|
541
|
+
)
|
|
542
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
543
|
+
args = parser.parse_args(argv)
|
|
544
|
+
|
|
545
|
+
try:
|
|
546
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
547
|
+
_guard_root(switcher)
|
|
548
|
+
entries = switcher.list_unclaimed_credentials()
|
|
549
|
+
|
|
550
|
+
if args.purge:
|
|
551
|
+
if args.purge not in entries:
|
|
552
|
+
error(f"Error: no unclaimed entry {args.purge}")
|
|
553
|
+
sys.exit(1)
|
|
554
|
+
switcher._store._remove_unclaimed_credential(args.purge)
|
|
555
|
+
print(f"{accent('Purged')} {args.purge}")
|
|
556
|
+
return
|
|
557
|
+
|
|
558
|
+
if not entries:
|
|
559
|
+
print(dimmed("No unclaimed credential entries"))
|
|
560
|
+
return
|
|
561
|
+
for entry_id, meta in sorted(entries.items()):
|
|
562
|
+
slot = meta.get("configSlot") or "?"
|
|
563
|
+
reason = meta.get("reason") or "orphaned (no manifest row)"
|
|
564
|
+
print(f"{entry_id} slot {slot} {reason}")
|
|
565
|
+
except ClaudeSwitchError as e:
|
|
566
|
+
error(f"Error: {e}")
|
|
567
|
+
sys.exit(1)
|
|
568
|
+
except KeyboardInterrupt:
|
|
569
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
570
|
+
sys.exit(130)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _swap_command(argv: list[str]) -> None:
|
|
574
|
+
"""Handle `cswap swap NUM|EMAIL|ALIAS NUM|EMAIL|ALIAS`.
|
|
575
|
+
|
|
576
|
+
Exchanges the two accounts' slot numbers (list order and numeric
|
|
577
|
+
targets). Pre-dispatched before the main parser for the same reason as
|
|
578
|
+
`alias` (the main parser's required mutually-exclusive group can't hold
|
|
579
|
+
a positional subcommand).
|
|
580
|
+
"""
|
|
581
|
+
parser = argparse.ArgumentParser(
|
|
582
|
+
prog=f"{_prog_name()} swap",
|
|
583
|
+
description=(
|
|
584
|
+
"Exchange two accounts' slot numbers, so they trade places in "
|
|
585
|
+
"`cswap list` and as numeric targets. Aliases, backups, and "
|
|
586
|
+
"session history move with their account."
|
|
587
|
+
),
|
|
588
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
589
|
+
epilog="""
|
|
590
|
+
Examples:
|
|
591
|
+
cswap swap 1 2
|
|
592
|
+
cswap swap dev user@example.com
|
|
593
|
+
""",
|
|
594
|
+
)
|
|
595
|
+
parser.add_argument("first", metavar="NUM|EMAIL|ALIAS", help="One account")
|
|
596
|
+
parser.add_argument("second", metavar="NUM|EMAIL|ALIAS", help="The other account")
|
|
597
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
598
|
+
args = parser.parse_args(argv)
|
|
599
|
+
|
|
600
|
+
try:
|
|
601
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
602
|
+
_guard_root(switcher)
|
|
603
|
+
num_a, num_b = switcher.swap_accounts(args.first, args.second)
|
|
604
|
+
print(f"{accent('Swapped')} Account {num_a} and Account {num_b}:")
|
|
605
|
+
data = switcher._get_sequence_data() or {}
|
|
606
|
+
accounts = data.get("accounts", {})
|
|
607
|
+
for num in sorted((num_a, num_b), key=int):
|
|
608
|
+
email = accounts.get(num, {}).get("email", "")
|
|
609
|
+
print(f" {num}: {email}")
|
|
610
|
+
except ClaudeSwitchError as e:
|
|
611
|
+
error(f"Error: {e}")
|
|
612
|
+
sys.exit(1)
|
|
613
|
+
except KeyboardInterrupt:
|
|
614
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
615
|
+
sys.exit(130)
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def _move_command(argv: list[str]) -> None:
|
|
619
|
+
"""Handle `cswap move NUM|EMAIL|ALIAS SLOT`.
|
|
620
|
+
|
|
621
|
+
Assigns an account to a specific slot number. If the slot is empty the
|
|
622
|
+
account is relocated there (its old slot is freed); if it is occupied the
|
|
623
|
+
two accounts trade places. `swap a b` is exactly `move a <b's slot>`.
|
|
624
|
+
Pre-dispatched before the main parser for the same reason as `alias`.
|
|
625
|
+
"""
|
|
626
|
+
parser = argparse.ArgumentParser(
|
|
627
|
+
prog=f"{_prog_name()} move",
|
|
628
|
+
description=(
|
|
629
|
+
"Assign an account to a slot number. An empty slot relocates the "
|
|
630
|
+
"account there and frees its old slot; an occupied slot swaps the "
|
|
631
|
+
"two. Aliases, backups, and session history move with the account."
|
|
632
|
+
),
|
|
633
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
634
|
+
epilog="""
|
|
635
|
+
Examples:
|
|
636
|
+
cswap move user@example.com 1 move an account onto shortcut 1
|
|
637
|
+
cswap move dev 1 by alias
|
|
638
|
+
cswap move 2 1 by number (swaps if slot 1 is taken)
|
|
639
|
+
""",
|
|
640
|
+
)
|
|
641
|
+
parser.add_argument("account", metavar="NUM|EMAIL|ALIAS", help="Account to move")
|
|
642
|
+
parser.add_argument("slot", metavar="SLOT", help="Destination slot number")
|
|
643
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
644
|
+
args = parser.parse_args(argv)
|
|
645
|
+
|
|
646
|
+
try:
|
|
647
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
648
|
+
_guard_root(switcher)
|
|
649
|
+
num_src, num_target, swapped = switcher.move_account(args.account, args.slot)
|
|
650
|
+
data = switcher._get_sequence_data() or {}
|
|
651
|
+
accounts = data.get("accounts", {})
|
|
652
|
+
if num_src == num_target:
|
|
653
|
+
email = accounts.get(num_target, {}).get("email", "")
|
|
654
|
+
print(f"{dimmed('Already in')} slot {num_target}: {email}")
|
|
655
|
+
elif swapped:
|
|
656
|
+
print(f"{accent('Swapped')} Account {num_src} and Account {num_target}:")
|
|
657
|
+
for num in sorted((num_src, num_target), key=int):
|
|
658
|
+
email = accounts.get(num, {}).get("email", "")
|
|
659
|
+
print(f" {num}: {email}")
|
|
660
|
+
else:
|
|
661
|
+
email = accounts.get(num_target, {}).get("email", "")
|
|
662
|
+
print(f"{accent('Moved')} {email} to slot {num_target}")
|
|
663
|
+
except ClaudeSwitchError as e:
|
|
664
|
+
error(f"Error: {e}")
|
|
665
|
+
sys.exit(1)
|
|
666
|
+
except KeyboardInterrupt:
|
|
667
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
668
|
+
sys.exit(130)
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _alias_command(argv: list[str]) -> None:
|
|
672
|
+
"""Handle `cswap alias [NUM|EMAIL] [NAME] [--unset]`.
|
|
673
|
+
|
|
674
|
+
With no arguments, lists all aliases. Otherwise sets (or, with --unset,
|
|
675
|
+
removes) the alias for the given account. Pre-dispatched before the main
|
|
676
|
+
parser for the same reason as `map` (the main parser's required
|
|
677
|
+
mutually-exclusive group can't hold a positional subcommand).
|
|
678
|
+
"""
|
|
679
|
+
parser = argparse.ArgumentParser(
|
|
680
|
+
prog="cswap alias",
|
|
681
|
+
description=(
|
|
682
|
+
"Set, remove, or list a short display alias for an account. "
|
|
683
|
+
"Once set, the alias can be used anywhere an account number or "
|
|
684
|
+
"email is accepted (switch, remove, run, map)."
|
|
685
|
+
),
|
|
686
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
687
|
+
epilog="""
|
|
688
|
+
Examples:
|
|
689
|
+
cswap alias 2 dev
|
|
690
|
+
cswap alias user@example.com dev
|
|
691
|
+
cswap alias 2 --unset
|
|
692
|
+
cswap alias # list all aliases
|
|
693
|
+
""",
|
|
694
|
+
)
|
|
695
|
+
parser.add_argument(
|
|
696
|
+
"account",
|
|
697
|
+
nargs="?",
|
|
698
|
+
metavar="NUM|EMAIL",
|
|
699
|
+
help="Account to alias (number or email). Omit to list aliases.",
|
|
700
|
+
)
|
|
701
|
+
parser.add_argument(
|
|
702
|
+
"alias_name",
|
|
703
|
+
nargs="?",
|
|
704
|
+
metavar="NAME",
|
|
705
|
+
help="Alias to set (letters, digits, ., -, _; not purely numeric).",
|
|
706
|
+
)
|
|
707
|
+
parser.add_argument("--unset", action="store_true", help="Remove the account's alias")
|
|
708
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
709
|
+
args = parser.parse_args(argv)
|
|
710
|
+
|
|
711
|
+
if args.unset and args.alias_name:
|
|
712
|
+
parser.error("--unset does not take a NAME argument")
|
|
713
|
+
if args.unset and args.account is None:
|
|
714
|
+
parser.error("NUM|EMAIL is required with --unset")
|
|
715
|
+
if args.account is not None and not args.unset and not args.alias_name:
|
|
716
|
+
parser.error("NAME is required (or pass --unset to remove the alias)")
|
|
717
|
+
|
|
718
|
+
try:
|
|
719
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
720
|
+
_guard_root(switcher)
|
|
721
|
+
|
|
722
|
+
if args.account is None:
|
|
723
|
+
rows = switcher.list_aliases()
|
|
724
|
+
if not rows:
|
|
725
|
+
print(dimmed("No aliases set"))
|
|
726
|
+
return
|
|
727
|
+
print(bolded("Aliases:"))
|
|
728
|
+
for num, alias_name, email in rows:
|
|
729
|
+
print(f" {num}: {alias_name} {muted(f'({email})')}")
|
|
730
|
+
return
|
|
731
|
+
|
|
732
|
+
if args.unset:
|
|
733
|
+
account_num = switcher.unset_alias(args.account)
|
|
734
|
+
print(f"{accent('Removed alias')} for Account {account_num}")
|
|
735
|
+
else:
|
|
736
|
+
account_num, normalized = switcher.set_alias(args.account, args.alias_name)
|
|
737
|
+
print(f"{accent('Set alias')} '{normalized}' for Account {account_num}")
|
|
738
|
+
except ClaudeSwitchError as e:
|
|
739
|
+
error(f"Error: {e}")
|
|
740
|
+
sys.exit(1)
|
|
741
|
+
except KeyboardInterrupt:
|
|
742
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
743
|
+
sys.exit(130)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _threshold_command(argv: list[str]) -> None:
|
|
747
|
+
"""Handle `cswap threshold [NUM|EMAIL|ALIAS] [PCT] [--unset]`.
|
|
748
|
+
|
|
749
|
+
With no arguments, prints the global `autoswitch.threshold` and every
|
|
750
|
+
per-account override. Otherwise sets (or, with --unset, removes) one
|
|
751
|
+
account's own switch-away threshold. Pre-dispatched before the main parser
|
|
752
|
+
for the same reason as `alias`: the main parser's required
|
|
753
|
+
mutually-exclusive group cannot hold a positional subcommand.
|
|
754
|
+
|
|
755
|
+
The value is validated inside `set_account_threshold`, before any file is
|
|
756
|
+
touched, so a rejected value leaves `sequence.json` byte-identical.
|
|
757
|
+
"""
|
|
758
|
+
parser = argparse.ArgumentParser(
|
|
759
|
+
prog="cswap threshold",
|
|
760
|
+
description=(
|
|
761
|
+
"Set, remove, or list a per-account switch-away threshold. The "
|
|
762
|
+
"per-account value replaces autoswitch.threshold for that account "
|
|
763
|
+
"only, so one shared account can reserve headroom without capping "
|
|
764
|
+
"the whole fleet."
|
|
765
|
+
),
|
|
766
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
767
|
+
epilog=f"""
|
|
768
|
+
Examples:
|
|
769
|
+
cswap threshold 2 85
|
|
770
|
+
cswap threshold user@example.com 99.9
|
|
771
|
+
cswap threshold 2 --unset # back to the global default
|
|
772
|
+
cswap threshold # list the global default and overrides
|
|
773
|
+
|
|
774
|
+
Valid range: {ACCOUNT_THRESHOLD_MIN:g}-{ACCOUNT_THRESHOLD_MAX:g} (percent used).
|
|
775
|
+
""",
|
|
776
|
+
)
|
|
777
|
+
parser.add_argument(
|
|
778
|
+
"account",
|
|
779
|
+
nargs="?",
|
|
780
|
+
metavar="NUM|EMAIL",
|
|
781
|
+
help="Account to set (number, email, or alias). Omit to list.",
|
|
782
|
+
)
|
|
783
|
+
parser.add_argument(
|
|
784
|
+
"threshold",
|
|
785
|
+
nargs="?",
|
|
786
|
+
metavar="PCT",
|
|
787
|
+
help=(
|
|
788
|
+
f"Percent used at which to switch away "
|
|
789
|
+
f"({ACCOUNT_THRESHOLD_MIN:g}-{ACCOUNT_THRESHOLD_MAX:g})."
|
|
790
|
+
),
|
|
791
|
+
)
|
|
792
|
+
parser.add_argument(
|
|
793
|
+
"--unset", action="store_true", help="Remove the account's override"
|
|
794
|
+
)
|
|
795
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
796
|
+
args = parser.parse_args(argv)
|
|
797
|
+
|
|
798
|
+
if args.unset and args.threshold:
|
|
799
|
+
parser.error("--unset does not take a PCT argument")
|
|
800
|
+
if args.unset and args.account is None:
|
|
801
|
+
parser.error("NUM|EMAIL is required with --unset")
|
|
802
|
+
if args.account is not None and not args.unset and args.threshold is None:
|
|
803
|
+
parser.error("PCT is required (or pass --unset to remove the override)")
|
|
804
|
+
|
|
805
|
+
try:
|
|
806
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
807
|
+
_guard_root(switcher)
|
|
808
|
+
|
|
809
|
+
if args.account is None:
|
|
810
|
+
_print_threshold_table(switcher)
|
|
811
|
+
return
|
|
812
|
+
|
|
813
|
+
switcher.set_account_threshold(
|
|
814
|
+
args.account, None if args.unset else args.threshold
|
|
815
|
+
)
|
|
816
|
+
except ValueError as e:
|
|
817
|
+
# normalize_account_threshold's message; it always names the range.
|
|
818
|
+
error(f"Error: {e}")
|
|
819
|
+
sys.exit(1)
|
|
820
|
+
except ClaudeSwitchError as e:
|
|
821
|
+
error(f"Error: {e}")
|
|
822
|
+
sys.exit(1)
|
|
823
|
+
except KeyboardInterrupt:
|
|
824
|
+
print(f"\n{dimmed('Operation cancelled')}")
|
|
825
|
+
sys.exit(130)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _print_threshold_table(switcher: ClaudeAccountSwitcher) -> None:
|
|
829
|
+
"""Print the global switch-away threshold and every per-account override.
|
|
830
|
+
|
|
831
|
+
The global line is printed unconditionally: an operator reading a list of
|
|
832
|
+
overrides needs to know what the accounts *without* one are using.
|
|
833
|
+
"""
|
|
834
|
+
from claude_swap.settings import load_settings
|
|
835
|
+
|
|
836
|
+
default = load_settings(switcher.backup_dir).threshold
|
|
837
|
+
print(bolded("Switch-away thresholds:"))
|
|
838
|
+
print(f" {dimmed('global default')} {default:g}%")
|
|
839
|
+
|
|
840
|
+
rows = sorted(
|
|
841
|
+
(
|
|
842
|
+
(num, policy.threshold)
|
|
843
|
+
for num, policy in switcher.account_policies().items()
|
|
844
|
+
if policy.threshold is not None
|
|
845
|
+
),
|
|
846
|
+
key=lambda row: (not row[0].isdigit(), int(row[0]) if row[0].isdigit() else 0),
|
|
847
|
+
)
|
|
848
|
+
if not rows:
|
|
849
|
+
print(dimmed(" No per-account overrides set"))
|
|
850
|
+
return
|
|
851
|
+
for num, value in rows:
|
|
852
|
+
print(f" Account-{num} {value:g}%")
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def _priority_command(argv: list[str]) -> None:
|
|
856
|
+
"""Set, clear, or inspect tiers without enabling the strategy implicitly."""
|
|
857
|
+
parser = argparse.ArgumentParser(
|
|
858
|
+
prog="cswap priority",
|
|
859
|
+
description=(
|
|
860
|
+
"Set or list account priority tiers for the optional "
|
|
861
|
+
"priority-consume-first strategy. Higher numbers are used first; "
|
|
862
|
+
"accounts in the same tier are ordered by soonest weekly reset."
|
|
863
|
+
),
|
|
864
|
+
)
|
|
865
|
+
parser.add_argument("account", nargs="?", metavar="NUM|EMAIL|ALIAS")
|
|
866
|
+
parser.add_argument(
|
|
867
|
+
"priority", nargs="?", metavar="TIER",
|
|
868
|
+
help=f"Integer from 0 to {ACCOUNT_PRIORITY_MAX} (default 0)",
|
|
869
|
+
)
|
|
870
|
+
parser.add_argument("--unset", action="store_true", help="Return to priority 0")
|
|
871
|
+
parser.add_argument("--debug", action="store_true")
|
|
872
|
+
args = parser.parse_args(argv)
|
|
873
|
+
if args.unset and args.priority is not None:
|
|
874
|
+
parser.error("--unset does not take a TIER argument")
|
|
875
|
+
if args.unset and args.account is None:
|
|
876
|
+
parser.error("NUM|EMAIL|ALIAS is required with --unset")
|
|
877
|
+
if args.account is not None and args.priority is None and not args.unset:
|
|
878
|
+
parser.error("TIER is required (or pass --unset)")
|
|
879
|
+
try:
|
|
880
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
881
|
+
_guard_root(switcher)
|
|
882
|
+
if args.account is None:
|
|
883
|
+
print(bolded("Account priorities (higher first; default 0):"))
|
|
884
|
+
for num, policy in switcher.account_policies().items():
|
|
885
|
+
print(f" Account-{num} {switcher.account_email(num)} {policy.priority}")
|
|
886
|
+
print(dimmed("Used only by: cswap auto --strategy priority-consume-first"))
|
|
887
|
+
return
|
|
888
|
+
switcher.set_account_priority(args.account, None if args.unset else args.priority)
|
|
889
|
+
except (ValueError, ClaudeSwitchError) as e:
|
|
890
|
+
error(f"Error: {e}")
|
|
891
|
+
sys.exit(1)
|
|
892
|
+
except KeyboardInterrupt:
|
|
893
|
+
sys.exit(130)
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def _auto_command(argv: list[str]) -> None:
|
|
897
|
+
"""Handle `cswap auto [--once] [--json] [...]`.
|
|
898
|
+
|
|
899
|
+
Pre-dispatched before the main parser is built, like `run` (and with the
|
|
900
|
+
same limitation: `auto` must be the first argument). Runs the auto-switch
|
|
901
|
+
engine — a foreground loop by default, or a single evaluate-and-maybe-
|
|
902
|
+
switch tick with --once whose exit code reports the outcome (for cron/
|
|
903
|
+
systemd timers): 0 switched, 1 error, 2 no action needed, 3 blocked
|
|
904
|
+
(no viable target / all accounts exhausted).
|
|
905
|
+
"""
|
|
906
|
+
import signal
|
|
907
|
+
import time as _time
|
|
908
|
+
|
|
909
|
+
parser = argparse.ArgumentParser(
|
|
910
|
+
prog="cswap auto",
|
|
911
|
+
description=(
|
|
912
|
+
"Automatically switch accounts when the active one nears its "
|
|
913
|
+
"5h/7d rate limit. Runs a foreground polling loop; use --once "
|
|
914
|
+
"for a single tick (cron-friendly)."
|
|
915
|
+
),
|
|
916
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
917
|
+
epilog="""
|
|
918
|
+
Exit codes with --once:
|
|
919
|
+
0 switched to another account
|
|
920
|
+
1 error (network trouble, lock contention, ...)
|
|
921
|
+
2 no action needed
|
|
922
|
+
3 blocked: wanted to switch but no viable target / all exhausted
|
|
923
|
+
|
|
924
|
+
Examples:
|
|
925
|
+
cswap auto # foreground loop, switch at 90% used
|
|
926
|
+
cswap auto --threshold 80 # switch earlier
|
|
927
|
+
cswap auto --weekly-threshold 97 # let the weekly window run higher before switching
|
|
928
|
+
cswap auto --model Fable # also switch when the Fable weekly limit is hit
|
|
929
|
+
cswap auto --json # one JSON event per line (for scripts)
|
|
930
|
+
cswap auto --once; echo $? # single tick, outcome in exit code
|
|
931
|
+
cswap auto --dry-run # log decisions, never actually switch
|
|
932
|
+
|
|
933
|
+
Defaults live in settings.json in the backup root; flags override them.
|
|
934
|
+
""",
|
|
935
|
+
)
|
|
936
|
+
parser.add_argument(
|
|
937
|
+
"--once",
|
|
938
|
+
action="store_true",
|
|
939
|
+
help="Evaluate once, maybe switch, and exit (exit code = outcome)",
|
|
940
|
+
)
|
|
941
|
+
parser.add_argument(
|
|
942
|
+
"--json",
|
|
943
|
+
action="store_true",
|
|
944
|
+
help="Emit one machine-readable JSON event per line on stdout",
|
|
945
|
+
)
|
|
946
|
+
parser.add_argument(
|
|
947
|
+
"--interval",
|
|
948
|
+
type=float,
|
|
949
|
+
metavar="SECONDS",
|
|
950
|
+
help="Poll interval in loop mode (min 15; default 60)",
|
|
951
|
+
)
|
|
952
|
+
parser.add_argument(
|
|
953
|
+
"--threshold",
|
|
954
|
+
type=float,
|
|
955
|
+
metavar="PCT",
|
|
956
|
+
help=(
|
|
957
|
+
"Switch when the active account's 5h window (or any window, "
|
|
958
|
+
"without a weekly line) reaches this utilization (40-99.9; "
|
|
959
|
+
"default 90)"
|
|
960
|
+
),
|
|
961
|
+
)
|
|
962
|
+
parser.add_argument(
|
|
963
|
+
"--weekly-threshold",
|
|
964
|
+
type=float,
|
|
965
|
+
metavar="PCT",
|
|
966
|
+
help=(
|
|
967
|
+
"Separate switch line for the 7-day and per-model weekly windows "
|
|
968
|
+
"(50-99.9; default: the threshold). A flag cannot unset a "
|
|
969
|
+
"configured value; use 'cswap config unset'"
|
|
970
|
+
),
|
|
971
|
+
)
|
|
972
|
+
parser.add_argument(
|
|
973
|
+
"--cooldown",
|
|
974
|
+
type=float,
|
|
975
|
+
metavar="SECONDS",
|
|
976
|
+
help="Minimum time between proactive switches (default 300)",
|
|
977
|
+
)
|
|
978
|
+
parser.add_argument(
|
|
979
|
+
"--model",
|
|
980
|
+
metavar="NAMES",
|
|
981
|
+
help=(
|
|
982
|
+
"Also switch when a per-model weekly limit is hit, not just the "
|
|
983
|
+
"account-wide 5h/7d windows. One name or a comma-separated list "
|
|
984
|
+
"(e.g. Fable, Opus, Sonnet, Haiku, or 'Fable,Opus'), or 'all' "
|
|
985
|
+
"for every per-model window an account reports"
|
|
986
|
+
),
|
|
987
|
+
)
|
|
988
|
+
parser.add_argument(
|
|
989
|
+
"--include-api-key-accounts",
|
|
990
|
+
action=argparse.BooleanOptionalAction,
|
|
991
|
+
default=None,
|
|
992
|
+
help=(
|
|
993
|
+
"Allow switching onto managed API-key accounts as a last resort "
|
|
994
|
+
"(they bill per token; default: excluded)"
|
|
995
|
+
),
|
|
996
|
+
)
|
|
997
|
+
parser.add_argument(
|
|
998
|
+
"--strategy",
|
|
999
|
+
choices=AUTOSWITCH_STRATEGIES,
|
|
1000
|
+
default=None,
|
|
1001
|
+
help=(
|
|
1002
|
+
"Target selection: 'best' (most quota left; default), "
|
|
1003
|
+
"'weekly-first' (switch at the threshold like best, onto the "
|
|
1004
|
+
"account whose weekly window resets soonest), "
|
|
1005
|
+
"'consume-first' (proactively use the account whose weekly window "
|
|
1006
|
+
"resets soonest), or 'priority-consume-first' (highest account "
|
|
1007
|
+
"priority, then soonest weekly reset; only targets below all switch lines)"
|
|
1008
|
+
),
|
|
1009
|
+
)
|
|
1010
|
+
parser.add_argument(
|
|
1011
|
+
"--dry-run",
|
|
1012
|
+
action="store_true",
|
|
1013
|
+
help="Evaluate and report, but never switch or write state",
|
|
1014
|
+
)
|
|
1015
|
+
parser.add_argument(
|
|
1016
|
+
"--debug",
|
|
1017
|
+
action="store_true",
|
|
1018
|
+
help="Enable debug logging",
|
|
1019
|
+
)
|
|
1020
|
+
args = parser.parse_args(argv)
|
|
1021
|
+
|
|
1022
|
+
from claude_swap.autoswitch import AutoSwitchEngine, AutoSwitchEvent, pct_label
|
|
1023
|
+
from claude_swap.printer import accent, yellowed
|
|
1024
|
+
from claude_swap.settings import load_settings, merged_with_cli
|
|
1025
|
+
|
|
1026
|
+
def jsonl_emit(event: AutoSwitchEvent) -> None:
|
|
1027
|
+
print(json.dumps(event.to_json()), flush=True)
|
|
1028
|
+
|
|
1029
|
+
def human_emit(event: AutoSwitchEvent) -> None:
|
|
1030
|
+
stamp = _time.strftime("%H:%M:%S")
|
|
1031
|
+
line = event.human()
|
|
1032
|
+
if event.kind == "switch":
|
|
1033
|
+
line = accent(line)
|
|
1034
|
+
elif event.kind in ("error", "account-quarantined"):
|
|
1035
|
+
line = yellowed(line)
|
|
1036
|
+
elif event.kind in ("poll", "no-switch", "sleep"):
|
|
1037
|
+
line = dimmed(line)
|
|
1038
|
+
print(f"{stamp} {line}", flush=True)
|
|
1039
|
+
|
|
1040
|
+
try:
|
|
1041
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
1042
|
+
if sys.platform != "win32":
|
|
1043
|
+
if os.geteuid() == 0 and not switcher._is_running_in_container():
|
|
1044
|
+
error("Error: Do not run this script as root (unless running in a container)")
|
|
1045
|
+
sys.exit(1)
|
|
1046
|
+
|
|
1047
|
+
settings = merged_with_cli(load_settings(switcher.backup_dir), args)
|
|
1048
|
+
engine = AutoSwitchEngine(
|
|
1049
|
+
switcher,
|
|
1050
|
+
settings,
|
|
1051
|
+
jsonl_emit if args.json else human_emit,
|
|
1052
|
+
dry_run=args.dry_run,
|
|
1053
|
+
)
|
|
1054
|
+
|
|
1055
|
+
if args.once:
|
|
1056
|
+
sys.exit(engine.tick().value)
|
|
1057
|
+
|
|
1058
|
+
# Loop mode: SIGTERM (systemd stop) exits the loop cleanly.
|
|
1059
|
+
signal.signal(signal.SIGTERM, lambda *_: engine.stop())
|
|
1060
|
+
if not args.json:
|
|
1061
|
+
weekly = (
|
|
1062
|
+
f", weekly {pct_label(settings.weekly_threshold)}%"
|
|
1063
|
+
if settings.weekly_threshold is not None
|
|
1064
|
+
else ""
|
|
1065
|
+
)
|
|
1066
|
+
print(
|
|
1067
|
+
dimmed(
|
|
1068
|
+
f"Auto-switch running: threshold {pct_label(settings.threshold)}%"
|
|
1069
|
+
f"{weekly}, every {settings.interval_seconds:.0f}s"
|
|
1070
|
+
f"{' (dry-run)' if args.dry_run else ''} — Ctrl-C to stop"
|
|
1071
|
+
)
|
|
1072
|
+
)
|
|
1073
|
+
sys.exit(engine.run_loop())
|
|
1074
|
+
except ClaudeSwitchError as e:
|
|
1075
|
+
if args.json:
|
|
1076
|
+
print(json.dumps(error_envelope(e)))
|
|
1077
|
+
else:
|
|
1078
|
+
error(f"Error: {e}")
|
|
1079
|
+
sys.exit(1)
|
|
1080
|
+
except KeyboardInterrupt:
|
|
1081
|
+
print(
|
|
1082
|
+
f"\n{dimmed('Auto-switch stopped')}",
|
|
1083
|
+
file=sys.stderr if args.json else sys.stdout,
|
|
1084
|
+
)
|
|
1085
|
+
sys.exit(130)
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def _config_command(argv: list[str]) -> None:
|
|
1089
|
+
"""Handle `cswap config [list|get KEY|set KEY VALUE|unset KEY|path]`.
|
|
1090
|
+
|
|
1091
|
+
Pre-dispatched before the main parser is built, like `run` and `auto`
|
|
1092
|
+
(same limitation: `config` must be the first argument). Edits
|
|
1093
|
+
settings.json in the backup root (or settings.local.json once someone has
|
|
1094
|
+
created it) with strict validation — unlike loading,
|
|
1095
|
+
which forgivingly clamps — so a typo'd key or out-of-range value errors
|
|
1096
|
+
loudly here instead of silently degrading at `cswap auto` time. `list`
|
|
1097
|
+
also names the keys a hand edit left in the file that nothing reads.
|
|
1098
|
+
"""
|
|
1099
|
+
from claude_swap.settings import (
|
|
1100
|
+
SETTING_SPECS,
|
|
1101
|
+
effective_settings,
|
|
1102
|
+
format_setting_value,
|
|
1103
|
+
load_usage_settings,
|
|
1104
|
+
set_setting,
|
|
1105
|
+
setting_spec,
|
|
1106
|
+
settings_write_path,
|
|
1107
|
+
unrecognized_keys,
|
|
1108
|
+
unset_setting,
|
|
1109
|
+
)
|
|
1110
|
+
|
|
1111
|
+
key_lines = "\n".join(
|
|
1112
|
+
f" {spec.dotted:<34}{spec.help} (default {format_setting_value(spec.default)})"
|
|
1113
|
+
for spec in SETTING_SPECS.values()
|
|
1114
|
+
)
|
|
1115
|
+
parser = argparse.ArgumentParser(
|
|
1116
|
+
prog="cswap config",
|
|
1117
|
+
description=(
|
|
1118
|
+
"Read and edit claude-swap settings (settings.json in the "
|
|
1119
|
+
"backup root)."
|
|
1120
|
+
),
|
|
1121
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
1122
|
+
epilog=f"""
|
|
1123
|
+
Keys:
|
|
1124
|
+
{key_lines}
|
|
1125
|
+
|
|
1126
|
+
Examples:
|
|
1127
|
+
cswap config # list effective settings
|
|
1128
|
+
cswap config get autoswitch.threshold
|
|
1129
|
+
cswap config set autoswitch.threshold 80
|
|
1130
|
+
cswap config set autoswitch.weeklyThreshold 97 # own line for the 7d/per-model windows
|
|
1131
|
+
cswap config unset autoswitch.threshold # back to the default
|
|
1132
|
+
cswap config path # the file `set` writes
|
|
1133
|
+
""",
|
|
1134
|
+
)
|
|
1135
|
+
parser.add_argument(
|
|
1136
|
+
"--json",
|
|
1137
|
+
action="store_true",
|
|
1138
|
+
help="Emit machine-readable JSON to stdout (with list or get)",
|
|
1139
|
+
)
|
|
1140
|
+
parser.add_argument(
|
|
1141
|
+
"--debug",
|
|
1142
|
+
action="store_true",
|
|
1143
|
+
help="Enable debug logging",
|
|
1144
|
+
)
|
|
1145
|
+
sub = parser.add_subparsers(dest="action", metavar="{list,get,set,unset,path}")
|
|
1146
|
+
|
|
1147
|
+
p_list = sub.add_parser("list", help="Show all effective settings (the default)")
|
|
1148
|
+
p_get = sub.add_parser("get", help="Print one setting's effective value")
|
|
1149
|
+
p_get.add_argument("key", metavar="KEY", help="Dotted key, e.g. autoswitch.threshold")
|
|
1150
|
+
for p in (p_list, p_get):
|
|
1151
|
+
# SUPPRESS: without it the subparser's False default would clobber a
|
|
1152
|
+
# pre-verb `cswap config --json` in the shared namespace.
|
|
1153
|
+
p.add_argument(
|
|
1154
|
+
"--json",
|
|
1155
|
+
action="store_true",
|
|
1156
|
+
default=argparse.SUPPRESS,
|
|
1157
|
+
help="Emit machine-readable JSON to stdout",
|
|
1158
|
+
)
|
|
1159
|
+
p_set = sub.add_parser("set", help="Validate and persist one setting")
|
|
1160
|
+
p_set.add_argument("key", metavar="KEY")
|
|
1161
|
+
p_set.add_argument("value", metavar="VALUE")
|
|
1162
|
+
p_unset = sub.add_parser("unset", help="Remove one setting (revert to the default)")
|
|
1163
|
+
p_unset.add_argument("key", metavar="KEY")
|
|
1164
|
+
sub.add_parser(
|
|
1165
|
+
"path",
|
|
1166
|
+
help="Print the file `set` writes (settings.json, or "
|
|
1167
|
+
"settings.local.json once it exists)",
|
|
1168
|
+
)
|
|
1169
|
+
|
|
1170
|
+
args = parser.parse_args(argv)
|
|
1171
|
+
json_mode = bool(getattr(args, "json", False))
|
|
1172
|
+
action = args.action or "list"
|
|
1173
|
+
if json_mode and action not in ("list", "get"):
|
|
1174
|
+
parser.error("--json can only be used with list or get")
|
|
1175
|
+
|
|
1176
|
+
try:
|
|
1177
|
+
switcher = ClaudeAccountSwitcher(debug=args.debug)
|
|
1178
|
+
if sys.platform != "win32":
|
|
1179
|
+
if os.geteuid() == 0 and not switcher._is_running_in_container():
|
|
1180
|
+
error("Error: Do not run this script as root (unless running in a container)")
|
|
1181
|
+
sys.exit(1)
|
|
1182
|
+
root = switcher.backup_dir
|
|
1183
|
+
|
|
1184
|
+
if action == "path":
|
|
1185
|
+
print(settings_write_path(root))
|
|
1186
|
+
elif action == "list":
|
|
1187
|
+
rows = effective_settings(root)
|
|
1188
|
+
ignored = unrecognized_keys(root)
|
|
1189
|
+
if json_mode:
|
|
1190
|
+
payload = {
|
|
1191
|
+
"schemaVersion": 1,
|
|
1192
|
+
"path": str(settings_write_path(root)),
|
|
1193
|
+
"settings": [
|
|
1194
|
+
{"key": spec.dotted, "value": value, "isSet": is_set}
|
|
1195
|
+
for spec, value, is_set in rows
|
|
1196
|
+
],
|
|
1197
|
+
"unrecognized": [
|
|
1198
|
+
{"key": item.dotted, "suggestion": item.suggestion}
|
|
1199
|
+
for item in ignored
|
|
1200
|
+
],
|
|
1201
|
+
}
|
|
1202
|
+
print(json.dumps(payload, indent=2))
|
|
1203
|
+
else:
|
|
1204
|
+
key_w = max(len(spec.dotted) for spec, _, _ in rows)
|
|
1205
|
+
val_w = max(len(format_setting_value(v)) for _, v, _ in rows)
|
|
1206
|
+
for spec, value, is_set in rows:
|
|
1207
|
+
line = f"{spec.dotted:<{key_w}} {format_setting_value(value):<{val_w}}"
|
|
1208
|
+
print(line if is_set else f"{line} {dimmed('(default)')}")
|
|
1209
|
+
for item in ignored:
|
|
1210
|
+
warning(
|
|
1211
|
+
f"Warning: settings.json: {item.describe()}",
|
|
1212
|
+
file=sys.stderr,
|
|
1213
|
+
)
|
|
1214
|
+
elif action == "get":
|
|
1215
|
+
spec = setting_spec(args.key)
|
|
1216
|
+
value, is_set = next(
|
|
1217
|
+
(v, s) for sp, v, s in effective_settings(root) if sp is spec
|
|
1218
|
+
)
|
|
1219
|
+
if json_mode:
|
|
1220
|
+
payload = {
|
|
1221
|
+
"schemaVersion": 1,
|
|
1222
|
+
"key": spec.dotted,
|
|
1223
|
+
"value": value,
|
|
1224
|
+
"isSet": is_set,
|
|
1225
|
+
}
|
|
1226
|
+
print(json.dumps(payload, indent=2))
|
|
1227
|
+
else:
|
|
1228
|
+
print(format_setting_value(value))
|
|
1229
|
+
elif action == "set":
|
|
1230
|
+
value = set_setting(root, args.key, args.value)
|
|
1231
|
+
print(f"{args.key} = {format_setting_value(value)}")
|
|
1232
|
+
usage = load_usage_settings(root)
|
|
1233
|
+
if (
|
|
1234
|
+
args.key.startswith("usage.")
|
|
1235
|
+
and usage.fable_probe
|
|
1236
|
+
and not usage.header_probe
|
|
1237
|
+
):
|
|
1238
|
+
# The Fable probe rides on the header probe's request cycle.
|
|
1239
|
+
print(
|
|
1240
|
+
muted(
|
|
1241
|
+
"usage.fableProbe does nothing until "
|
|
1242
|
+
"usage.headerProbe is true"
|
|
1243
|
+
),
|
|
1244
|
+
file=sys.stderr,
|
|
1245
|
+
)
|
|
1246
|
+
elif action == "unset":
|
|
1247
|
+
if unset_setting(root, args.key):
|
|
1248
|
+
spec = setting_spec(args.key)
|
|
1249
|
+
value, is_set = next(
|
|
1250
|
+
(v, s) for sp, v, s in effective_settings(root) if sp is spec
|
|
1251
|
+
)
|
|
1252
|
+
# With settings.local.json in play, settings.json may still set it.
|
|
1253
|
+
now = (
|
|
1254
|
+
f"now {format_setting_value(value)}, from settings.json"
|
|
1255
|
+
if is_set
|
|
1256
|
+
else f"default: {format_setting_value(spec.default)}"
|
|
1257
|
+
)
|
|
1258
|
+
print(f"{args.key} unset ({now})")
|
|
1259
|
+
else:
|
|
1260
|
+
spec = setting_spec(args.key)
|
|
1261
|
+
from_base = any(s for sp, _, s in effective_settings(root) if sp is spec)
|
|
1262
|
+
why = (
|
|
1263
|
+
"is set in settings.json, which this command does not write"
|
|
1264
|
+
if from_base
|
|
1265
|
+
else "is not set"
|
|
1266
|
+
)
|
|
1267
|
+
print(muted(f"{args.key} {why}; nothing to do"), file=sys.stderr)
|
|
1268
|
+
except ClaudeSwitchError as e:
|
|
1269
|
+
if json_mode:
|
|
1270
|
+
print(json.dumps(error_envelope(e), indent=2))
|
|
1271
|
+
else:
|
|
1272
|
+
error(f"Error: {e}")
|
|
1273
|
+
sys.exit(1)
|
|
1274
|
+
except KeyboardInterrupt:
|
|
1275
|
+
print(
|
|
1276
|
+
f"\n{dimmed('Operation cancelled')}",
|
|
1277
|
+
file=sys.stderr if json_mode else sys.stdout,
|
|
1278
|
+
)
|
|
1279
|
+
sys.exit(130)
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def _use_native_tls() -> None:
|
|
1283
|
+
"""Route TLS trust decisions through the OS-native verifier.
|
|
1284
|
+
|
|
1285
|
+
Claude's token endpoint (``platform.claude.com``) serves a Let's Encrypt
|
|
1286
|
+
chain. Python's stdlib ``ssl`` uses OpenSSL, which on Windows loads the
|
|
1287
|
+
system cert store as a flat set and matches CA certs by *subject name*, so a
|
|
1288
|
+
stale, expired duplicate of an intermediate (e.g. an old ``ISRG Root X2``
|
|
1289
|
+
left in the user's store) can shadow the valid path and fail verification
|
|
1290
|
+
with "certificate has expired" even though the served chain is valid — which
|
|
1291
|
+
silently breaks inactive-account token refresh. The OS-native verifiers
|
|
1292
|
+
(SChannel on Windows, SecureTransport on macOS) build the chain correctly
|
|
1293
|
+
and don't trip on the expired duplicate — the same reason Claude Code (Node,
|
|
1294
|
+
with its own bundled roots) is unaffected. ``truststore`` delegates to them.
|
|
1295
|
+
|
|
1296
|
+
Best-effort: on any failure fall back to stdlib ``ssl`` rather than block
|
|
1297
|
+
the CLI over a TLS-trust nicety.
|
|
1298
|
+
"""
|
|
1299
|
+
try:
|
|
1300
|
+
import truststore
|
|
1301
|
+
|
|
1302
|
+
truststore.inject_into_ssl()
|
|
1303
|
+
except Exception:
|
|
1304
|
+
pass
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def _menubar_settings_path():
|
|
1308
|
+
from claude_swap.paths import get_backup_root
|
|
1309
|
+
|
|
1310
|
+
return get_backup_root() / "menubar_settings.json"
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def _set_menubar_auto_switch(enabled: bool) -> bool:
|
|
1314
|
+
"""Set the menu bar's auto-switch toggle and return its previous value."""
|
|
1315
|
+
from claude_swap.menubar import MenuBarSettings
|
|
1316
|
+
|
|
1317
|
+
path = _menubar_settings_path()
|
|
1318
|
+
settings = MenuBarSettings.load(path)
|
|
1319
|
+
previous = settings.auto_switch_enabled
|
|
1320
|
+
settings.auto_switch_enabled = enabled
|
|
1321
|
+
settings.save(path)
|
|
1322
|
+
return previous
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
def _print_menubar_auto_switch(*, suggest_flag: bool) -> None:
|
|
1326
|
+
"""Say whether the menu bar will switch accounts or only show usage.
|
|
1327
|
+
|
|
1328
|
+
The toggle defaults to off and lives only in the menu, so a service
|
|
1329
|
+
installed from a terminal can run for weeks as a display while its owner
|
|
1330
|
+
believes it is switching (it only shows when an account hits its limit).
|
|
1331
|
+
"""
|
|
1332
|
+
from claude_swap.menubar import MenuBarSettings
|
|
1333
|
+
|
|
1334
|
+
if MenuBarSettings.load(_menubar_settings_path()).auto_switch_enabled:
|
|
1335
|
+
print(" auto-switch: on")
|
|
1336
|
+
return
|
|
1337
|
+
hint = (
|
|
1338
|
+
"turn it on from the menu, or re-run with --auto-switch"
|
|
1339
|
+
if suggest_flag
|
|
1340
|
+
else "turn it on from the menu, or run `cswap menubar --auto-switch`"
|
|
1341
|
+
)
|
|
1342
|
+
warning(
|
|
1343
|
+
f" auto-switch: off -- the menu bar shows usage but will not switch "
|
|
1344
|
+
f"accounts; {hint}",
|
|
1345
|
+
file=sys.stderr,
|
|
1346
|
+
)
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
def _menubar_extra_missing() -> str | None:
|
|
1350
|
+
"""Why the menu bar cannot run here: the optional extra is not installed.
|
|
1351
|
+
|
|
1352
|
+
Checked before anything touches launchd. A worker that exits on ``import
|
|
1353
|
+
rumps`` would give launchd a service that crash-loops at every login, which
|
|
1354
|
+
is strictly worse than the import error a foreground run shows.
|
|
1355
|
+
"""
|
|
1356
|
+
import importlib.util
|
|
1357
|
+
|
|
1358
|
+
if importlib.util.find_spec("rumps") is not None:
|
|
1359
|
+
return None
|
|
1360
|
+
from claude_swap.update_check import _detect_install_method
|
|
1361
|
+
|
|
1362
|
+
method = _detect_install_method()
|
|
1363
|
+
if method == "uv":
|
|
1364
|
+
remedy = "uv tool install --force 'llmswap-cli[menubar]'"
|
|
1365
|
+
elif method == "pipx":
|
|
1366
|
+
remedy = "pipx install --force 'llmswap-cli[menubar]'"
|
|
1367
|
+
else:
|
|
1368
|
+
remedy = "pip install 'llmswap-cli[menubar]'"
|
|
1369
|
+
return f"The menu bar needs the 'menubar' extra. Install it with: {remedy}"
|
|
1370
|
+
|
|
1371
|
+
|
|
1372
|
+
def _menubar_foreground(switcher, service_pid: int | None, *, worker: bool) -> int:
|
|
1373
|
+
"""Run the menu bar in this process: launchd's job, or ``--foreground`` from a shell.
|
|
1374
|
+
|
|
1375
|
+
A second instance beside the service would draw a second icon over the same
|
|
1376
|
+
accounts, so a shell run refuses while the service has a pid. launchd's own
|
|
1377
|
+
job is that pid, which is what ``worker`` says.
|
|
1378
|
+
"""
|
|
1379
|
+
if not worker and service_pid is not None:
|
|
1380
|
+
error(
|
|
1381
|
+
f"The menu bar is already running as a service (pid {service_pid}). "
|
|
1382
|
+
"Quit it from the menu, or run 'cswap menubar --uninstall-service', "
|
|
1383
|
+
"before running it in the foreground."
|
|
1384
|
+
)
|
|
1385
|
+
return 1
|
|
1386
|
+
# menubar is import-safe without the extra; a missing rumps surfaces from
|
|
1387
|
+
# run() as a ClaudeSwitchError with the install hint.
|
|
1388
|
+
from claude_swap.menubar import run as menubar_run
|
|
1389
|
+
|
|
1390
|
+
return menubar_run(switcher)
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
def _menubar_start(args) -> int:
|
|
1394
|
+
"""Handle plain ``cswap menubar``: make the service run, say what happened, return.
|
|
1395
|
+
|
|
1396
|
+
First setup registers the menu bar at login and says so, since a command
|
|
1397
|
+
that quietly arranged to run at every login would be a surprise. Later runs
|
|
1398
|
+
only make sure the service is up: a quit job is kickstarted, a plist pinning
|
|
1399
|
+
an old program is repaired, a running one is left alone and reported.
|
|
1400
|
+
"""
|
|
1401
|
+
from claude_swap import launch_agent
|
|
1402
|
+
from claude_swap.menubar import framework_build_warning
|
|
1403
|
+
|
|
1404
|
+
missing = _menubar_extra_missing()
|
|
1405
|
+
if missing:
|
|
1406
|
+
error(missing)
|
|
1407
|
+
return 1
|
|
1408
|
+
unsupported = framework_build_warning()
|
|
1409
|
+
# Before ensure(): the menu bar reads its toggle once at launch, so a
|
|
1410
|
+
# changed value needs the write first and a running service restarted.
|
|
1411
|
+
previous = None
|
|
1412
|
+
if args.auto_switch is not None:
|
|
1413
|
+
previous = _set_menubar_auto_switch(args.auto_switch)
|
|
1414
|
+
toggled = previous is not None and previous != args.auto_switch
|
|
1415
|
+
try:
|
|
1416
|
+
result = launch_agent.ensure(restart=toggled)
|
|
1417
|
+
except BaseException:
|
|
1418
|
+
# Don't leave the toggle changed with no service behind it.
|
|
1419
|
+
if toggled:
|
|
1420
|
+
_set_menubar_auto_switch(previous)
|
|
1421
|
+
raise
|
|
1422
|
+
|
|
1423
|
+
pid = f" (pid {result['pid']})" if result["pid"] else ""
|
|
1424
|
+
action = result["action"]
|
|
1425
|
+
if action == "already-running":
|
|
1426
|
+
print(f"Menu bar is already running{pid}.")
|
|
1427
|
+
elif action == "first-setup":
|
|
1428
|
+
print(f"Menu bar started{pid}.")
|
|
1429
|
+
print(
|
|
1430
|
+
dimmed(
|
|
1431
|
+
" It keeps running after you close this terminal and starts at "
|
|
1432
|
+
"login. Settings → Start at login in the menu turns that off; "
|
|
1433
|
+
"cswap menubar --uninstall-service removes it."
|
|
1434
|
+
)
|
|
1435
|
+
)
|
|
1436
|
+
print(f" plist: {result['plist']}")
|
|
1437
|
+
print(f" logs: {result['stderr_log']}")
|
|
1438
|
+
elif action == "restarted":
|
|
1439
|
+
why = (
|
|
1440
|
+
"to apply the auto-switch setting"
|
|
1441
|
+
if toggled
|
|
1442
|
+
else "so the service runs the current build"
|
|
1443
|
+
)
|
|
1444
|
+
print(f"Menu bar restarted{pid} {why}.")
|
|
1445
|
+
else:
|
|
1446
|
+
print(f"Menu bar started{pid}.")
|
|
1447
|
+
if not result["start_at_login"]:
|
|
1448
|
+
print(dimmed(" Start at login is off, so this lasts until you log out."))
|
|
1449
|
+
if result["switched_off"]:
|
|
1450
|
+
# macOS allowed this start; the switch only governs the start at login.
|
|
1451
|
+
warning(
|
|
1452
|
+
f" Switched off under {launch_agent.SYSTEM_SETTINGS_HINT}: it runs "
|
|
1453
|
+
"now because you asked, but macOS will not start it at login until "
|
|
1454
|
+
"you turn that back on.",
|
|
1455
|
+
file=sys.stderr,
|
|
1456
|
+
)
|
|
1457
|
+
_print_menubar_auto_switch(suggest_flag=True)
|
|
1458
|
+
if unsupported:
|
|
1459
|
+
# Said here too, not only at launch: the service survives reboots and
|
|
1460
|
+
# shows nothing, which is the worst version of the bug.
|
|
1461
|
+
warning(unsupported, file=sys.stderr)
|
|
1462
|
+
return 0
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
def _menubar_service(args) -> int:
|
|
1466
|
+
"""Handle ``menubar --install-service|--uninstall-service|--service-status``.
|
|
1467
|
+
|
|
1468
|
+
Split out of the dispatch chain because these three share one import and
|
|
1469
|
+
one output shape, and because the menu bar branch below them is a
|
|
1470
|
+
non-returning call — folding the service paths inline would leave the
|
|
1471
|
+
reader tracing which branches fall through to launching the app.
|
|
1472
|
+
"""
|
|
1473
|
+
from claude_swap import launch_agent
|
|
1474
|
+
|
|
1475
|
+
if args.install_service:
|
|
1476
|
+
# Installing a service for a menu bar that this interpreter cannot draw
|
|
1477
|
+
# is the worst version of the bug: it survives reboots and shows
|
|
1478
|
+
# nothing. Say so here too, not only when the menu bar is launched.
|
|
1479
|
+
from claude_swap.menubar import framework_build_warning
|
|
1480
|
+
|
|
1481
|
+
missing = _menubar_extra_missing()
|
|
1482
|
+
if missing:
|
|
1483
|
+
error(missing)
|
|
1484
|
+
return 1
|
|
1485
|
+
unsupported = framework_build_warning()
|
|
1486
|
+
# Before install(): it restarts a running service, and the menu bar
|
|
1487
|
+
# reads its toggle once at launch.
|
|
1488
|
+
previous = None
|
|
1489
|
+
if args.auto_switch is not None:
|
|
1490
|
+
previous = _set_menubar_auto_switch(args.auto_switch)
|
|
1491
|
+
try:
|
|
1492
|
+
result = launch_agent.install()
|
|
1493
|
+
except BaseException:
|
|
1494
|
+
# Don't leave the toggle changed with no service behind it.
|
|
1495
|
+
if previous is not None and previous != args.auto_switch:
|
|
1496
|
+
_set_menubar_auto_switch(previous)
|
|
1497
|
+
raise
|
|
1498
|
+
print(f"Menu bar service installed ({result['label']}).")
|
|
1499
|
+
print(f" plist: {result['plist']}")
|
|
1500
|
+
print(f" logs: {result['stderr_log']}")
|
|
1501
|
+
_print_menubar_auto_switch(suggest_flag=True)
|
|
1502
|
+
for key, old, new in result["profile_changes"]:
|
|
1503
|
+
warning(
|
|
1504
|
+
f" now follows {key}={new or '(unset)'} (was {old or '(unset)'}); "
|
|
1505
|
+
"the service manages that profile from now on",
|
|
1506
|
+
file=sys.stderr,
|
|
1507
|
+
)
|
|
1508
|
+
print(
|
|
1509
|
+
dimmed(
|
|
1510
|
+
"It starts at login from now on; plain `cswap menubar` is enough "
|
|
1511
|
+
"to start it again. Re-run this after a cswap upgrade to point "
|
|
1512
|
+
"launchd at the new build."
|
|
1513
|
+
)
|
|
1514
|
+
)
|
|
1515
|
+
if unsupported:
|
|
1516
|
+
# The hint printed above is about upgrades. A reinstall does not
|
|
1517
|
+
# restart the service that is already running, so say that here.
|
|
1518
|
+
warning(
|
|
1519
|
+
unsupported + "\n Then run: cswap menubar --install-service",
|
|
1520
|
+
file=sys.stderr,
|
|
1521
|
+
)
|
|
1522
|
+
return 0
|
|
1523
|
+
|
|
1524
|
+
if args.uninstall_service:
|
|
1525
|
+
result = launch_agent.uninstall()
|
|
1526
|
+
if result["was_loaded"] or result["removed"]:
|
|
1527
|
+
print("Menu bar service removed.")
|
|
1528
|
+
for path in result["removed"]:
|
|
1529
|
+
print(dimmed(f" removed {path}"))
|
|
1530
|
+
if result["cleared_override"]:
|
|
1531
|
+
print(dimmed(" cleared its switch under Login Items & Extensions"))
|
|
1532
|
+
else:
|
|
1533
|
+
print("Menu bar service was not installed.")
|
|
1534
|
+
if result["bundle_error"]:
|
|
1535
|
+
warning(
|
|
1536
|
+
f" the wrapper app could not be removed: {result['bundle_error']}",
|
|
1537
|
+
file=sys.stderr,
|
|
1538
|
+
)
|
|
1539
|
+
return 0
|
|
1540
|
+
|
|
1541
|
+
result = launch_agent.status()
|
|
1542
|
+
if not result["configured"] and not result["loaded"]:
|
|
1543
|
+
print("Menu bar service is not installed.")
|
|
1544
|
+
print(dimmed("Start it with: cswap menubar"))
|
|
1545
|
+
return 0
|
|
1546
|
+
state = result["state"] or ("loaded" if result["loaded"] else "stopped")
|
|
1547
|
+
pid = f" (pid {result['pid']})" if result["pid"] else ""
|
|
1548
|
+
print(f"Menu bar service: {state}{pid}")
|
|
1549
|
+
print(f" starts at login: {'yes' if result['start_at_login'] else 'no'}")
|
|
1550
|
+
plist = result["plist"] if result["start_at_login"] else result["session_plist"]
|
|
1551
|
+
print(f" plist: {plist or result['plist']}")
|
|
1552
|
+
if result["running_build"]:
|
|
1553
|
+
print(f" build: {result['running_build']}")
|
|
1554
|
+
if result["stale_build"]:
|
|
1555
|
+
warning(
|
|
1556
|
+
f" installed build is {result['installed_build']}; plain "
|
|
1557
|
+
"`cswap menubar` restarts it onto that",
|
|
1558
|
+
file=sys.stderr,
|
|
1559
|
+
)
|
|
1560
|
+
_print_menubar_auto_switch(suggest_flag=False)
|
|
1561
|
+
if result["switched_off"]:
|
|
1562
|
+
warning(
|
|
1563
|
+
f" switched off under {launch_agent.SYSTEM_SETTINGS_HINT}; "
|
|
1564
|
+
"macOS will not start it at login until you turn that back on",
|
|
1565
|
+
file=sys.stderr,
|
|
1566
|
+
)
|
|
1567
|
+
if not result["configured"]:
|
|
1568
|
+
print(dimmed("launchd still has it loaded, but the plist is gone."))
|
|
1569
|
+
return 0
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def main() -> None:
|
|
1573
|
+
"""Main entry point for the CLI."""
|
|
1574
|
+
force_utf8_output()
|
|
1575
|
+
_use_native_tls()
|
|
1576
|
+
argv = sys.argv[1:]
|
|
1577
|
+
try:
|
|
1578
|
+
from claude_swap.appearance import cli_should_probe, cli_theme
|
|
1579
|
+
# `run` execs a child that takes over the terminal, and `--json`
|
|
1580
|
+
# must stay machine-readable — never probe (and emit the OSC query)
|
|
1581
|
+
# in either case.
|
|
1582
|
+
probe = cli_should_probe(argv, colors_enabled=printer.colors_enabled())
|
|
1583
|
+
name = cli_theme(load_ui_settings(paths.get_backup_root()).theme, colors=probe)
|
|
1584
|
+
printer.set_theme(name)
|
|
1585
|
+
except Exception:
|
|
1586
|
+
pass # theme is cosmetic; never block the CLI on it
|
|
1587
|
+
|
|
1588
|
+
# `run`, `rc` and `auto` keep their dedicated pre-dispatch parsers.
|
|
1589
|
+
if argv and argv[0] == "run":
|
|
1590
|
+
_run_command(argv[1:])
|
|
1591
|
+
return # only reachable in tests where exec/exit is mocked
|
|
1592
|
+
if argv and argv[0] in ("rc", "remote-control"):
|
|
1593
|
+
_rc_command(argv[0], argv[1:])
|
|
1594
|
+
return # only reachable in tests where exec/exit is mocked
|
|
1595
|
+
if argv and argv[0] == "auto":
|
|
1596
|
+
_auto_command(argv[1:])
|
|
1597
|
+
return # only reachable in tests where sys.exit is mocked
|
|
1598
|
+
if len(sys.argv) > 1 and sys.argv[1] == "config":
|
|
1599
|
+
_config_command(sys.argv[2:])
|
|
1600
|
+
return
|
|
1601
|
+
if argv and argv[0] == "map":
|
|
1602
|
+
_map_command(argv[1:])
|
|
1603
|
+
return
|
|
1604
|
+
if argv and argv[0] == "unmap":
|
|
1605
|
+
_unmap_command(argv[1:])
|
|
1606
|
+
return
|
|
1607
|
+
if argv and argv[0] == "unclaimed":
|
|
1608
|
+
_unclaimed_command(argv[1:])
|
|
1609
|
+
return
|
|
1610
|
+
if argv and argv[0] == "alias":
|
|
1611
|
+
_alias_command(argv[1:])
|
|
1612
|
+
return
|
|
1613
|
+
if argv and argv[0] == "threshold":
|
|
1614
|
+
_threshold_command(argv[1:])
|
|
1615
|
+
return
|
|
1616
|
+
if argv and argv[0] == "priority":
|
|
1617
|
+
_priority_command(argv[1:])
|
|
1618
|
+
return
|
|
1619
|
+
if argv and argv[0] == "swap":
|
|
1620
|
+
_swap_command(argv[1:])
|
|
1621
|
+
return
|
|
1622
|
+
if argv and argv[0] == "move":
|
|
1623
|
+
_move_command(argv[1:])
|
|
1624
|
+
return
|
|
1625
|
+
|
|
1626
|
+
# Bare `cswap` in an interactive terminal opens the TUI dashboard (like
|
|
1627
|
+
# lazygit/k9s). TTY-gated on both ends so scripts and pipes keep getting
|
|
1628
|
+
# the usage error, and `cswap tui` stays the explicit spelling.
|
|
1629
|
+
if not argv and sys.stdout.isatty() and sys.stdin.isatty():
|
|
1630
|
+
argv = ["--tui"]
|
|
1631
|
+
|
|
1632
|
+
# Memorable subcommands (`cswap switch <email>`, `cswap list`, `cswap help`, ...)
|
|
1633
|
+
# are rewritten to the equivalent flags so the original `--flag` interface
|
|
1634
|
+
# keeps working unchanged.
|
|
1635
|
+
argv = _translate_subcommand(argv)
|
|
1636
|
+
|
|
1637
|
+
parser = argparse.ArgumentParser(
|
|
1638
|
+
prog=_prog_name(),
|
|
1639
|
+
usage="%(prog)s <command> [args] [options]",
|
|
1640
|
+
description="""Multi-Account Switcher for Claude Code
|
|
1641
|
+
|
|
1642
|
+
Commands:
|
|
1643
|
+
%(prog)s help show this help
|
|
1644
|
+
%(prog)s list list managed accounts
|
|
1645
|
+
%(prog)s status show current account
|
|
1646
|
+
%(prog)s switch rotate to the next account
|
|
1647
|
+
%(prog)s switch <num|email> switch to a specific account
|
|
1648
|
+
%(prog)s add add the account Claude Code is signed in as
|
|
1649
|
+
%(prog)s login sign in to another account and add it; the active one stays
|
|
1650
|
+
%(prog)s login <num|email> sign in again as a stored account
|
|
1651
|
+
%(prog)s add-token [TOKEN|-] register a setup-token or API key
|
|
1652
|
+
%(prog)s remove <num|email> remove an account
|
|
1653
|
+
%(prog)s disable <num|email> hold an account out of auto-rotation
|
|
1654
|
+
%(prog)s enable <num|email> return a disabled account to rotation
|
|
1655
|
+
%(prog)s threshold <num|email> <pct> set one account's switch-away point
|
|
1656
|
+
%(prog)s threshold <num|email> --unset clear it (use the global default)
|
|
1657
|
+
%(prog)s threshold list the global default and overrides
|
|
1658
|
+
%(prog)s priority <num|email> <tier> set priority (higher first; default 0)
|
|
1659
|
+
%(prog)s priority list account priorities
|
|
1660
|
+
%(prog)s run <num|email> [-- ...] run as an account, this terminal only
|
|
1661
|
+
%(prog)s run run the current dir's mapped account
|
|
1662
|
+
%(prog)s rc <num|email> [name] Remote Control as an account
|
|
1663
|
+
%(prog)s map <num|email> [path] map a directory to an account
|
|
1664
|
+
%(prog)s map list directory mappings
|
|
1665
|
+
%(prog)s unmap [path] remove a directory mapping
|
|
1666
|
+
%(prog)s alias <num|email> <name> set a short alias for an account
|
|
1667
|
+
%(prog)s alias <num|email> --unset remove an account's alias
|
|
1668
|
+
%(prog)s alias list all aliases
|
|
1669
|
+
%(prog)s swap <a> <b> exchange two accounts' slot numbers
|
|
1670
|
+
%(prog)s move <a> <slot> assign an account to a slot (swaps if taken)
|
|
1671
|
+
%(prog)s auto auto-switch when nearing rate limits
|
|
1672
|
+
%(prog)s config [set KEY VALUE] show or change settings (settings.json)
|
|
1673
|
+
%(prog)s unclaimed [--purge ID] list or drop stashed credential entries
|
|
1674
|
+
%(prog)s export <path> export accounts
|
|
1675
|
+
%(prog)s import <path> import accounts
|
|
1676
|
+
%(prog)s import-usage <path> adopt usage another machine read (list --json)
|
|
1677
|
+
%(prog)s tui interactive dashboard (also: bare %(prog)s)
|
|
1678
|
+
%(prog)s watch dashboard, opened on the live watch page
|
|
1679
|
+
%(prog)s menubar macOS menu bar app, kept running by launchd
|
|
1680
|
+
%(prog)s menubar --service-status is it running? does it start at login?
|
|
1681
|
+
%(prog)s upgrade self-upgrade to latest
|
|
1682
|
+
%(prog)s purge remove all claude-swap data
|
|
1683
|
+
|
|
1684
|
+
Aliases: ls=list rm=remove update=upgrade""",
|
|
1685
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
1686
|
+
epilog="""Flags combine with subcommands:
|
|
1687
|
+
%(prog)s switch --strategy best # pick the account with most quota left
|
|
1688
|
+
%(prog)s switch --strategy next-available # rotate, skipping rate-limited accounts
|
|
1689
|
+
%(prog)s switch user@example.com
|
|
1690
|
+
%(prog)s list --token-status
|
|
1691
|
+
%(prog)s list --json
|
|
1692
|
+
%(prog)s import-usage usage.json --hold 600 # adopt another machine's list --json
|
|
1693
|
+
%(prog)s add --slot 3 # add to a specific slot
|
|
1694
|
+
%(prog)s login --email me@example.com # pre-fill the address on the sign-in page
|
|
1695
|
+
%(prog)s login 2 --browser # the default browser already holds account 2
|
|
1696
|
+
%(prog)s add-token sk-ant-oat01-... --email me@example.com
|
|
1697
|
+
%(prog)s run 2 -- --resume # forward args after '--' to claude
|
|
1698
|
+
%(prog)s auto --once # single auto-switch tick (cron-friendly)
|
|
1699
|
+
%(prog)s config set autoswitch.threshold 80
|
|
1700
|
+
|
|
1701
|
+
The original flag spellings (%(prog)s --switch, %(prog)s --list, ...) keep working.
|
|
1702
|
+
""",
|
|
1703
|
+
)
|
|
1704
|
+
|
|
1705
|
+
# Version and debug flags (outside mutually exclusive group)
|
|
1706
|
+
parser.add_argument(
|
|
1707
|
+
"--version",
|
|
1708
|
+
action="version",
|
|
1709
|
+
version=f"%(prog)s {__version__}",
|
|
1710
|
+
)
|
|
1711
|
+
parser.add_argument(
|
|
1712
|
+
"--debug",
|
|
1713
|
+
action="store_true",
|
|
1714
|
+
help="Enable debug logging",
|
|
1715
|
+
)
|
|
1716
|
+
parser.add_argument(
|
|
1717
|
+
"--token-status",
|
|
1718
|
+
action="store_true",
|
|
1719
|
+
help="Show source-labelled OAuth token diagnostics (use with 'list')",
|
|
1720
|
+
)
|
|
1721
|
+
parser.add_argument(
|
|
1722
|
+
"--json",
|
|
1723
|
+
action="store_true",
|
|
1724
|
+
help=(
|
|
1725
|
+
"Emit machine-readable JSON to stdout (use with 'list', 'status', "
|
|
1726
|
+
"or 'switch'). See README 'JSON output for scripting'."
|
|
1727
|
+
),
|
|
1728
|
+
)
|
|
1729
|
+
parser.add_argument(
|
|
1730
|
+
"--strategy",
|
|
1731
|
+
choices=["best", "next-available"],
|
|
1732
|
+
metavar="{best,next-available}",
|
|
1733
|
+
help=(
|
|
1734
|
+
"With bare 'switch': pick the target by remaining 5h/7d quota. "
|
|
1735
|
+
"'best' jumps to the account with the most headroom; "
|
|
1736
|
+
"'next-available' rotates to the next account, skipping any at their limit"
|
|
1737
|
+
),
|
|
1738
|
+
)
|
|
1739
|
+
parser.add_argument(
|
|
1740
|
+
"--model",
|
|
1741
|
+
metavar="NAMES",
|
|
1742
|
+
help=(
|
|
1743
|
+
"With 'switch --strategy': also count these models' per-model "
|
|
1744
|
+
"weekly limits when comparing accounts (comma-separated display "
|
|
1745
|
+
"names, or 'all'). Defaults to the autoswitch.model setting"
|
|
1746
|
+
),
|
|
1747
|
+
)
|
|
1748
|
+
parser.add_argument(
|
|
1749
|
+
"--slot",
|
|
1750
|
+
type=int,
|
|
1751
|
+
metavar="NUM",
|
|
1752
|
+
help="Specify slot number when adding account (use with 'add' or 'add-token')",
|
|
1753
|
+
)
|
|
1754
|
+
parser.add_argument(
|
|
1755
|
+
"--email",
|
|
1756
|
+
metavar="EMAIL",
|
|
1757
|
+
help=(
|
|
1758
|
+
"Email address for the account. Optional with 'add-token'; "
|
|
1759
|
+
"defaults to setup-token-{slot}@token.local (or "
|
|
1760
|
+
"api-key-{slot}@token.local for API keys) since these tokens "
|
|
1761
|
+
"carry no real email metadata. With 'login', the address to "
|
|
1762
|
+
"pre-fill on the sign-in page."
|
|
1763
|
+
),
|
|
1764
|
+
)
|
|
1765
|
+
parser.add_argument(
|
|
1766
|
+
"--sso",
|
|
1767
|
+
action="store_true",
|
|
1768
|
+
help="Ask Claude Code for an SSO sign-in (use with 'login')",
|
|
1769
|
+
)
|
|
1770
|
+
parser.add_argument(
|
|
1771
|
+
"--browser",
|
|
1772
|
+
action="store_true",
|
|
1773
|
+
help=(
|
|
1774
|
+
"Let Claude Code open the sign-in in your default browser, which "
|
|
1775
|
+
"signs in the account that browser already holds, instead of "
|
|
1776
|
+
"printing a link to open yourself (use with 'login')"
|
|
1777
|
+
),
|
|
1778
|
+
)
|
|
1779
|
+
parser.add_argument(
|
|
1780
|
+
"--account",
|
|
1781
|
+
metavar="NUM|EMAIL",
|
|
1782
|
+
help="Limit export to one account (use with 'export')",
|
|
1783
|
+
)
|
|
1784
|
+
parser.add_argument(
|
|
1785
|
+
"--alias",
|
|
1786
|
+
metavar="NAME",
|
|
1787
|
+
help="Set a short display alias for the account (use with 'add' or 'login')",
|
|
1788
|
+
)
|
|
1789
|
+
parser.add_argument(
|
|
1790
|
+
"--force",
|
|
1791
|
+
action="store_true",
|
|
1792
|
+
help=(
|
|
1793
|
+
"Overwrite existing accounts during import; with 'switch <num|email>', "
|
|
1794
|
+
"activate the stored credentials without backing up the current "
|
|
1795
|
+
"login first"
|
|
1796
|
+
),
|
|
1797
|
+
)
|
|
1798
|
+
parser.add_argument(
|
|
1799
|
+
"--full",
|
|
1800
|
+
action="store_true",
|
|
1801
|
+
help="Include full ~/.claude.json in export (default: oauthAccount only)",
|
|
1802
|
+
)
|
|
1803
|
+
parser.add_argument(
|
|
1804
|
+
"--hold",
|
|
1805
|
+
type=float,
|
|
1806
|
+
metavar="SECONDS",
|
|
1807
|
+
help=(
|
|
1808
|
+
"With 'import-usage': keep this machine from fetching the "
|
|
1809
|
+
"imported accounts for this many seconds (0 lifts an earlier hold)"
|
|
1810
|
+
),
|
|
1811
|
+
)
|
|
1812
|
+
# `cswap menubar` runs the menu bar as a launchd service (launch_agent.py);
|
|
1813
|
+
# these pick another operation on that service, so at most one applies.
|
|
1814
|
+
service = parser.add_mutually_exclusive_group()
|
|
1815
|
+
service.add_argument(
|
|
1816
|
+
"--install-service",
|
|
1817
|
+
action="store_true",
|
|
1818
|
+
help=(
|
|
1819
|
+
"With 'menubar': register the menu bar to start at login and "
|
|
1820
|
+
"(re)start it now; plain 'cswap menubar' does this on first use (macOS)"
|
|
1821
|
+
),
|
|
1822
|
+
)
|
|
1823
|
+
service.add_argument(
|
|
1824
|
+
"--uninstall-service",
|
|
1825
|
+
action="store_true",
|
|
1826
|
+
help="With 'menubar': stop the menu bar and remove its LaunchAgent (macOS)",
|
|
1827
|
+
)
|
|
1828
|
+
service.add_argument(
|
|
1829
|
+
"--service-status",
|
|
1830
|
+
action="store_true",
|
|
1831
|
+
help=(
|
|
1832
|
+
"With 'menubar': report whether the menu bar service is installed, "
|
|
1833
|
+
"running and set to start at login"
|
|
1834
|
+
),
|
|
1835
|
+
)
|
|
1836
|
+
service.add_argument(
|
|
1837
|
+
"--foreground",
|
|
1838
|
+
action="store_true",
|
|
1839
|
+
help=(
|
|
1840
|
+
"With 'menubar': run the menu bar attached to this terminal instead "
|
|
1841
|
+
"of as the background service"
|
|
1842
|
+
),
|
|
1843
|
+
)
|
|
1844
|
+
parser.add_argument(
|
|
1845
|
+
"--auto-switch",
|
|
1846
|
+
dest="auto_switch",
|
|
1847
|
+
action="store_const",
|
|
1848
|
+
const=True,
|
|
1849
|
+
default=None,
|
|
1850
|
+
help=(
|
|
1851
|
+
"With 'menubar' or 'menubar --install-service': turn the menu bar's "
|
|
1852
|
+
"auto-switch on (it defaults to off)"
|
|
1853
|
+
),
|
|
1854
|
+
)
|
|
1855
|
+
parser.add_argument(
|
|
1856
|
+
"--no-auto-switch",
|
|
1857
|
+
dest="auto_switch",
|
|
1858
|
+
action="store_const",
|
|
1859
|
+
const=False,
|
|
1860
|
+
help=(
|
|
1861
|
+
"With 'menubar' or 'menubar --install-service': turn the menu bar's "
|
|
1862
|
+
"auto-switch off"
|
|
1863
|
+
),
|
|
1864
|
+
)
|
|
1865
|
+
|
|
1866
|
+
# Legacy `--flag` interface. Still fully supported (bare subcommands rewrite
|
|
1867
|
+
# into these, see _translate_subcommand), but hidden from --help so the
|
|
1868
|
+
# subcommands shown in the description are the one documented interface.
|
|
1869
|
+
# The group is not `required` because the "no command" case is handled
|
|
1870
|
+
# explicitly below (a required group with every member suppressed prints a
|
|
1871
|
+
# broken empty-list error).
|
|
1872
|
+
group = parser.add_mutually_exclusive_group(required=False)
|
|
1873
|
+
group.add_argument(
|
|
1874
|
+
"--add-account",
|
|
1875
|
+
action="store_true",
|
|
1876
|
+
help=argparse.SUPPRESS,
|
|
1877
|
+
)
|
|
1878
|
+
group.add_argument(
|
|
1879
|
+
"--remove-account",
|
|
1880
|
+
metavar="NUM|EMAIL",
|
|
1881
|
+
help=argparse.SUPPRESS,
|
|
1882
|
+
)
|
|
1883
|
+
group.add_argument(
|
|
1884
|
+
"--disable-account",
|
|
1885
|
+
metavar="NUM|EMAIL",
|
|
1886
|
+
help=argparse.SUPPRESS,
|
|
1887
|
+
)
|
|
1888
|
+
group.add_argument(
|
|
1889
|
+
"--enable-account",
|
|
1890
|
+
metavar="NUM|EMAIL",
|
|
1891
|
+
help=argparse.SUPPRESS,
|
|
1892
|
+
)
|
|
1893
|
+
group.add_argument(
|
|
1894
|
+
"--list",
|
|
1895
|
+
action="store_true",
|
|
1896
|
+
help=argparse.SUPPRESS,
|
|
1897
|
+
)
|
|
1898
|
+
group.add_argument(
|
|
1899
|
+
"--switch",
|
|
1900
|
+
action="store_true",
|
|
1901
|
+
help=argparse.SUPPRESS,
|
|
1902
|
+
)
|
|
1903
|
+
group.add_argument(
|
|
1904
|
+
"--switch-to",
|
|
1905
|
+
metavar="NUM|EMAIL",
|
|
1906
|
+
help=argparse.SUPPRESS,
|
|
1907
|
+
)
|
|
1908
|
+
group.add_argument(
|
|
1909
|
+
"--status",
|
|
1910
|
+
action="store_true",
|
|
1911
|
+
help=argparse.SUPPRESS,
|
|
1912
|
+
)
|
|
1913
|
+
group.add_argument(
|
|
1914
|
+
"--purge",
|
|
1915
|
+
action="store_true",
|
|
1916
|
+
help=argparse.SUPPRESS,
|
|
1917
|
+
)
|
|
1918
|
+
group.add_argument(
|
|
1919
|
+
"--export",
|
|
1920
|
+
metavar="PATH",
|
|
1921
|
+
help=argparse.SUPPRESS,
|
|
1922
|
+
)
|
|
1923
|
+
group.add_argument(
|
|
1924
|
+
"--import",
|
|
1925
|
+
dest="import_",
|
|
1926
|
+
metavar="PATH",
|
|
1927
|
+
help=argparse.SUPPRESS,
|
|
1928
|
+
)
|
|
1929
|
+
group.add_argument(
|
|
1930
|
+
"--import-usage",
|
|
1931
|
+
metavar="PATH",
|
|
1932
|
+
help=argparse.SUPPRESS,
|
|
1933
|
+
)
|
|
1934
|
+
group.add_argument(
|
|
1935
|
+
"--tui",
|
|
1936
|
+
action="store_true",
|
|
1937
|
+
help=argparse.SUPPRESS,
|
|
1938
|
+
)
|
|
1939
|
+
group.add_argument(
|
|
1940
|
+
"--watch",
|
|
1941
|
+
action="store_true",
|
|
1942
|
+
help=argparse.SUPPRESS,
|
|
1943
|
+
)
|
|
1944
|
+
group.add_argument(
|
|
1945
|
+
"--menubar",
|
|
1946
|
+
action="store_true",
|
|
1947
|
+
help=argparse.SUPPRESS,
|
|
1948
|
+
)
|
|
1949
|
+
group.add_argument(
|
|
1950
|
+
"--upgrade",
|
|
1951
|
+
action="store_true",
|
|
1952
|
+
help=argparse.SUPPRESS,
|
|
1953
|
+
)
|
|
1954
|
+
group.add_argument(
|
|
1955
|
+
"--add-token",
|
|
1956
|
+
metavar="TOKEN|-",
|
|
1957
|
+
nargs="?",
|
|
1958
|
+
const="",
|
|
1959
|
+
help=argparse.SUPPRESS,
|
|
1960
|
+
)
|
|
1961
|
+
group.add_argument(
|
|
1962
|
+
"--login",
|
|
1963
|
+
metavar="NUM|EMAIL",
|
|
1964
|
+
nargs="?",
|
|
1965
|
+
const="",
|
|
1966
|
+
help=argparse.SUPPRESS,
|
|
1967
|
+
)
|
|
1968
|
+
|
|
1969
|
+
args = parser.parse_args(argv)
|
|
1970
|
+
|
|
1971
|
+
# No action selected: emit a clean, subcommand-oriented message rather than
|
|
1972
|
+
# the raw argparse "one of the arguments ... is required" (which would list
|
|
1973
|
+
# the now-hidden legacy flags). Value actions can be falsy-but-set
|
|
1974
|
+
# (--add-token and --login use const=""), so test those with `is not None`.
|
|
1975
|
+
if not (
|
|
1976
|
+
args.add_account
|
|
1977
|
+
or args.list
|
|
1978
|
+
or args.switch
|
|
1979
|
+
or args.status
|
|
1980
|
+
or args.purge
|
|
1981
|
+
or args.tui
|
|
1982
|
+
or args.watch
|
|
1983
|
+
or args.menubar
|
|
1984
|
+
or args.upgrade
|
|
1985
|
+
or args.remove_account is not None
|
|
1986
|
+
or args.disable_account is not None
|
|
1987
|
+
or args.enable_account is not None
|
|
1988
|
+
or args.switch_to is not None
|
|
1989
|
+
or args.export is not None
|
|
1990
|
+
or args.import_ is not None
|
|
1991
|
+
or args.import_usage is not None
|
|
1992
|
+
or args.add_token is not None
|
|
1993
|
+
or args.login is not None
|
|
1994
|
+
):
|
|
1995
|
+
parser.error("no command given — try '%(prog)s help'" % {"prog": _prog_name()})
|
|
1996
|
+
|
|
1997
|
+
# An empty value satisfies the guard above (the option *is* set) but matches
|
|
1998
|
+
# no truthiness-tested branch of the dispatch chain below, so cswap would
|
|
1999
|
+
# fall out of it and exit 0 having done nothing: `cswap export "$DEST"` with
|
|
2000
|
+
# an unset DEST must not look like a completed backup. Rejected here, ahead
|
|
2001
|
+
# of the modifier guards, so the error names the empty value instead of
|
|
2002
|
+
# blaming an --account/--force/--full that was used correctly. --add-token is
|
|
2003
|
+
# exempt: its const="" means "prompt me for the token".
|
|
2004
|
+
for subcommand, metavar, value in (
|
|
2005
|
+
("remove", "NUM|EMAIL", args.remove_account),
|
|
2006
|
+
("disable", "NUM|EMAIL", args.disable_account),
|
|
2007
|
+
("enable", "NUM|EMAIL", args.enable_account),
|
|
2008
|
+
("switch", "NUM|EMAIL", args.switch_to),
|
|
2009
|
+
("export", "PATH", args.export),
|
|
2010
|
+
("import", "PATH", args.import_),
|
|
2011
|
+
("import-usage", "PATH", args.import_usage),
|
|
2012
|
+
):
|
|
2013
|
+
if value is not None and not value:
|
|
2014
|
+
parser.error(f"'{subcommand}' requires a non-empty {metavar}")
|
|
2015
|
+
|
|
2016
|
+
if args.token_status and not args.list:
|
|
2017
|
+
parser.error("--token-status can only be used with 'list'")
|
|
2018
|
+
|
|
2019
|
+
if args.json and not (args.list or args.status or args.switch or args.switch_to):
|
|
2020
|
+
parser.error("--json can only be used with 'list', 'status', or 'switch'")
|
|
2021
|
+
|
|
2022
|
+
if args.json and args.token_status:
|
|
2023
|
+
# Token status is not part of the JSON v1 schema; reject rather than
|
|
2024
|
+
# silently ignore it (a future additive field can add it).
|
|
2025
|
+
parser.error("--token-status cannot be combined with --json")
|
|
2026
|
+
|
|
2027
|
+
if args.strategy is not None and not args.switch:
|
|
2028
|
+
parser.error("--strategy can only be used with bare 'switch'")
|
|
2029
|
+
|
|
2030
|
+
if args.model is not None and args.strategy is None:
|
|
2031
|
+
# Meaningless on a direct-target switch or plain rotation — nothing
|
|
2032
|
+
# usage-aware reads it there, so reject loudly rather than ignore.
|
|
2033
|
+
parser.error(
|
|
2034
|
+
"--model can only be used with 'switch --strategy best' or "
|
|
2035
|
+
"'switch --strategy next-available'"
|
|
2036
|
+
)
|
|
2037
|
+
|
|
2038
|
+
if args.slot is not None and not (args.add_account or args.add_token is not None):
|
|
2039
|
+
parser.error("--slot can only be used with 'add' or 'add-token'")
|
|
2040
|
+
|
|
2041
|
+
if args.email is not None and args.add_token is None and args.login is None:
|
|
2042
|
+
parser.error("--email can only be used with 'add-token' or 'login'")
|
|
2043
|
+
|
|
2044
|
+
if args.sso and args.login is None:
|
|
2045
|
+
parser.error("--sso can only be used with 'login'")
|
|
2046
|
+
|
|
2047
|
+
if args.browser and args.login is None:
|
|
2048
|
+
parser.error("--browser can only be used with 'login'")
|
|
2049
|
+
|
|
2050
|
+
if args.account is not None and not args.export:
|
|
2051
|
+
parser.error("--account can only be used with 'export'")
|
|
2052
|
+
|
|
2053
|
+
if args.alias is not None and not (args.add_account or args.login is not None):
|
|
2054
|
+
parser.error("--alias can only be used with 'add' or 'login'")
|
|
2055
|
+
|
|
2056
|
+
if args.force and not (args.import_ or args.switch_to):
|
|
2057
|
+
parser.error("--force can only be used with 'import' or 'switch <num|email>'")
|
|
2058
|
+
|
|
2059
|
+
if args.full and not args.export:
|
|
2060
|
+
parser.error("--full can only be used with 'export'")
|
|
2061
|
+
|
|
2062
|
+
if args.hold is not None and args.import_usage is None:
|
|
2063
|
+
parser.error("--hold can only be used with 'import-usage'")
|
|
2064
|
+
|
|
2065
|
+
if args.hold is not None and not (math.isfinite(args.hold) and args.hold >= 0):
|
|
2066
|
+
parser.error("--hold must be a non-negative number of seconds")
|
|
2067
|
+
|
|
2068
|
+
if (
|
|
2069
|
+
args.install_service
|
|
2070
|
+
or args.uninstall_service
|
|
2071
|
+
or args.service_status
|
|
2072
|
+
or args.foreground
|
|
2073
|
+
) and not args.menubar:
|
|
2074
|
+
parser.error(
|
|
2075
|
+
"--install-service, --uninstall-service, --service-status and "
|
|
2076
|
+
"--foreground can only be used with 'menubar'"
|
|
2077
|
+
)
|
|
2078
|
+
|
|
2079
|
+
if args.auto_switch is not None and (
|
|
2080
|
+
not args.menubar
|
|
2081
|
+
or args.uninstall_service
|
|
2082
|
+
or args.service_status
|
|
2083
|
+
or args.foreground
|
|
2084
|
+
):
|
|
2085
|
+
parser.error(
|
|
2086
|
+
"--auto-switch/--no-auto-switch can only be used with "
|
|
2087
|
+
"'menubar' or 'menubar --install-service'"
|
|
2088
|
+
)
|
|
2089
|
+
|
|
2090
|
+
# Self-upgrade runs before switcher init so we don't touch config/keychain
|
|
2091
|
+
# just to upgrade the tool itself.
|
|
2092
|
+
if args.upgrade:
|
|
2093
|
+
from claude_swap.update_check import run_self_upgrade
|
|
2094
|
+
|
|
2095
|
+
try:
|
|
2096
|
+
sys.exit(run_self_upgrade())
|
|
2097
|
+
except KeyboardInterrupt:
|
|
2098
|
+
print(f"\n{dimmed('Upgrade cancelled')}")
|
|
2099
|
+
sys.exit(130)
|
|
2100
|
+
|
|
2101
|
+
# Initialize switcher and dispatch under a single error handler so
|
|
2102
|
+
# init-time failures (e.g. MigrationError on a backup-dir collision)
|
|
2103
|
+
# are presented like every other ClaudeSwitchError: clean stderr line,
|
|
2104
|
+
# exit 1, no traceback.
|
|
2105
|
+
# JSON-capable commands return a payload; the CLI is the single point that
|
|
2106
|
+
# serializes it (so no command writes JSON to stdout itself).
|
|
2107
|
+
payload: dict | None = None
|
|
2108
|
+
try:
|
|
2109
|
+
switcher = ClaudeAccountSwitcher(
|
|
2110
|
+
debug=args.debug, interactive=_person_at_terminal(args)
|
|
2111
|
+
)
|
|
2112
|
+
|
|
2113
|
+
# Check for root (unless in container) - POSIX only
|
|
2114
|
+
if sys.platform != "win32":
|
|
2115
|
+
if os.geteuid() == 0 and not switcher._is_running_in_container():
|
|
2116
|
+
error("Error: Do not run this script as root (unless running in a container)")
|
|
2117
|
+
sys.exit(1)
|
|
2118
|
+
|
|
2119
|
+
if args.add_account:
|
|
2120
|
+
switcher.add_account(slot=args.slot, alias=args.alias)
|
|
2121
|
+
elif args.add_token is not None:
|
|
2122
|
+
switcher.add_account_from_token(
|
|
2123
|
+
token=args.add_token,
|
|
2124
|
+
email=args.email,
|
|
2125
|
+
slot=args.slot,
|
|
2126
|
+
)
|
|
2127
|
+
elif args.login is not None:
|
|
2128
|
+
# A bare `login` carries const="": sign in to another account.
|
|
2129
|
+
switcher.login_account(
|
|
2130
|
+
args.login or None,
|
|
2131
|
+
email=args.email,
|
|
2132
|
+
sso=args.sso,
|
|
2133
|
+
alias=args.alias,
|
|
2134
|
+
open_browser=args.browser,
|
|
2135
|
+
)
|
|
2136
|
+
elif args.remove_account:
|
|
2137
|
+
switcher.remove_account(args.remove_account)
|
|
2138
|
+
elif args.disable_account is not None:
|
|
2139
|
+
switcher.set_account_disabled(args.disable_account, True)
|
|
2140
|
+
elif args.enable_account is not None:
|
|
2141
|
+
switcher.set_account_disabled(args.enable_account, False)
|
|
2142
|
+
elif args.list:
|
|
2143
|
+
payload = switcher.list_accounts(
|
|
2144
|
+
show_token_status=args.token_status,
|
|
2145
|
+
json_output=args.json,
|
|
2146
|
+
)
|
|
2147
|
+
elif args.switch:
|
|
2148
|
+
from claude_swap.settings import load_settings, parse_model_names
|
|
2149
|
+
|
|
2150
|
+
# Only the usage-aware strategies read model limits: --model wins;
|
|
2151
|
+
# otherwise the persistent autoswitch.model setting applies
|
|
2152
|
+
# (announced by switch(), never silently).
|
|
2153
|
+
if args.strategy is None:
|
|
2154
|
+
models, model_source = (), None
|
|
2155
|
+
elif args.model is not None:
|
|
2156
|
+
models, model_source = parse_model_names(args.model), "cli"
|
|
2157
|
+
else:
|
|
2158
|
+
models = parse_model_names(load_settings(switcher.backup_dir).model)
|
|
2159
|
+
model_source = "autoswitch.model" if models else None
|
|
2160
|
+
payload = switcher.switch(
|
|
2161
|
+
strategy=args.strategy,
|
|
2162
|
+
json_output=args.json,
|
|
2163
|
+
models=models,
|
|
2164
|
+
model_source=model_source,
|
|
2165
|
+
)
|
|
2166
|
+
if payload is not None and models:
|
|
2167
|
+
payload["models"] = list(models)
|
|
2168
|
+
payload["modelSource"] = model_source
|
|
2169
|
+
elif args.switch_to:
|
|
2170
|
+
payload = switcher.switch_to(
|
|
2171
|
+
args.switch_to, json_output=args.json, force=args.force
|
|
2172
|
+
)
|
|
2173
|
+
elif args.status:
|
|
2174
|
+
payload = switcher.status(json_output=args.json)
|
|
2175
|
+
elif args.purge:
|
|
2176
|
+
switcher.purge()
|
|
2177
|
+
if sys.platform == "darwin":
|
|
2178
|
+
# The menu bar's LaunchAgent, wrapper app and logs live outside
|
|
2179
|
+
# the directory purge just removed; "all traces" means them too.
|
|
2180
|
+
# After purge() so a refused purge leaves the menu bar alone.
|
|
2181
|
+
from claude_swap import launch_agent
|
|
2182
|
+
|
|
2183
|
+
try:
|
|
2184
|
+
gone = launch_agent.uninstall(backup_dir=switcher.backup_dir)
|
|
2185
|
+
except ClaudeSwitchError as e:
|
|
2186
|
+
warning(f"Menu bar service not removed: {e}", file=sys.stderr)
|
|
2187
|
+
else:
|
|
2188
|
+
if gone["was_loaded"] or gone["removed"]:
|
|
2189
|
+
print("Removed the menu bar service, its app bundle and logs.")
|
|
2190
|
+
elif args.export:
|
|
2191
|
+
from claude_swap.transfer import export_accounts
|
|
2192
|
+
|
|
2193
|
+
export_accounts(switcher, args.export, account=args.account, full=args.full)
|
|
2194
|
+
elif args.import_:
|
|
2195
|
+
from claude_swap.transfer import import_accounts
|
|
2196
|
+
|
|
2197
|
+
import_accounts(switcher, args.import_, force=args.force)
|
|
2198
|
+
elif args.import_usage:
|
|
2199
|
+
from claude_swap.transfer import import_usage
|
|
2200
|
+
|
|
2201
|
+
import_usage(switcher, args.import_usage, hold_s=args.hold)
|
|
2202
|
+
elif args.tui:
|
|
2203
|
+
from claude_swap.tui import run as tui_run
|
|
2204
|
+
|
|
2205
|
+
sys.exit(tui_run(switcher))
|
|
2206
|
+
elif args.watch:
|
|
2207
|
+
from claude_swap.tui import run as tui_run
|
|
2208
|
+
|
|
2209
|
+
sys.exit(tui_run(switcher, start="watch"))
|
|
2210
|
+
elif args.menubar:
|
|
2211
|
+
if sys.platform != "darwin":
|
|
2212
|
+
error("The menu bar is only available on macOS.")
|
|
2213
|
+
sys.exit(1)
|
|
2214
|
+
if args.install_service or args.uninstall_service or args.service_status:
|
|
2215
|
+
sys.exit(_menubar_service(args))
|
|
2216
|
+
from claude_swap import launch_agent
|
|
2217
|
+
|
|
2218
|
+
# launchd's own job runs the menu bar here (recognised by pid, so a
|
|
2219
|
+
# plist from before the --foreground flag still works); everything
|
|
2220
|
+
# else asks launchd to run it and returns.
|
|
2221
|
+
service_pid = launch_agent.service_pid()
|
|
2222
|
+
worker = service_pid is not None and service_pid == os.getpid()
|
|
2223
|
+
if args.foreground or worker:
|
|
2224
|
+
sys.exit(_menubar_foreground(switcher, service_pid, worker=worker))
|
|
2225
|
+
sys.exit(_menubar_start(args))
|
|
2226
|
+
except ClaudeSwitchError as e:
|
|
2227
|
+
# In JSON mode keep stdout pure JSON: emit the structured error envelope
|
|
2228
|
+
# there (exit 1) instead of a red stderr line.
|
|
2229
|
+
if args.json:
|
|
2230
|
+
print(json.dumps(error_envelope(e), indent=2))
|
|
2231
|
+
else:
|
|
2232
|
+
error(f"Error: {e}")
|
|
2233
|
+
sys.exit(1)
|
|
2234
|
+
except KeyboardInterrupt:
|
|
2235
|
+
# Route the cancellation note to stderr in JSON mode so stdout stays
|
|
2236
|
+
# parseable (the guarantee covers completion / handled errors, not Ctrl-C).
|
|
2237
|
+
print(
|
|
2238
|
+
f"\n{dimmed('Operation cancelled')}",
|
|
2239
|
+
file=sys.stderr if args.json else sys.stdout,
|
|
2240
|
+
)
|
|
2241
|
+
sys.exit(130)
|
|
2242
|
+
|
|
2243
|
+
if args.json and payload is not None:
|
|
2244
|
+
print(json.dumps(payload, indent=2))
|
|
2245
|
+
|
|
2246
|
+
# Passive update notification (never fails). Skipped after --purge so we
|
|
2247
|
+
# don't immediately recreate <backup_root>/cache/update_check.json inside
|
|
2248
|
+
# the directory we just deleted. Skipped after --upgrade as a safety guard
|
|
2249
|
+
# in case the dispatch is later refactored to fall through. Skipped when
|
|
2250
|
+
# `updates.check` is false, so no request goes to PyPI at all.
|
|
2251
|
+
if (
|
|
2252
|
+
not args.purge
|
|
2253
|
+
and not args.upgrade
|
|
2254
|
+
and not args.json
|
|
2255
|
+
and load_update_settings(paths.get_backup_root()).check
|
|
2256
|
+
):
|
|
2257
|
+
from claude_swap.update_check import check_for_update
|
|
2258
|
+
|
|
2259
|
+
msg = check_for_update(__version__)
|
|
2260
|
+
if msg:
|
|
2261
|
+
print(f"\n{muted(msg)}", file=sys.stderr)
|
|
2262
|
+
|
|
2263
|
+
|
|
2264
|
+
if __name__ == "__main__":
|
|
2265
|
+
main()
|