llmswap-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,862 @@
1
+ """Run ``cswap menubar`` as a launchd LaunchAgent instead of a foreground process.
2
+
3
+ A menu bar item that dies with the terminal that started it, and never comes
4
+ back after a logout or reboot, is the wrong shape for a menu bar app. So
5
+ ``cswap menubar`` does not run the menu bar in the calling process: it makes
6
+ sure launchd runs it (:func:`ensure`) and returns. launchd then starts it at
7
+ login and restarts it after a crash. The process launchd spawns is
8
+ ``cswap menubar --foreground``, the one invocation that draws the status item
9
+ in place. (The wrapper ``.app`` that process hops into is
10
+ ``claude_swap.app_bundle``'s business: launchd only ever needs the console
11
+ script.)
12
+
13
+ *The plist's location is the Start-at-login preference.* A plist in
14
+ ``~/Library/LaunchAgents`` is what launchd scans at login, so that is where
15
+ first setup puts it. When the user turns *Start at login* off in the menu, the
16
+ same plist moves to the data directory: launchd can still be handed it for the
17
+ current session (that is how ``brew services run`` works too), but nothing
18
+ scans that directory at login. The file is deliberately kept there rather than
19
+ deleted, because a missing plist means "never set up" and would turn Start at
20
+ login back on the next time ``cswap menubar`` ran. Both present means the login
21
+ copy wins. Nothing here moves a plist *and* touches launchd in one step: the
22
+ running job keeps its in-memory definition, and the menu toggle must never
23
+ stop the app whose menu was just clicked.
24
+
25
+ *launchd's own worker is recognised by pid, not by flag.* ``launchctl print``
26
+ names the job's pid; when that is this process, launchd started us and
27
+ ``cswap menubar`` has to run the menu bar here instead of trying to start the
28
+ service it already is. That also keeps plists written before the
29
+ ``--foreground`` flag existed working: they still say plain ``cswap menubar``.
30
+
31
+ Two older decisions are worth restating, because both differ from the obvious
32
+ approach:
33
+
34
+ *The plist pins the console script, not ``sys.executable``.* A LaunchAgent
35
+ outlives upgrades, and the two paths age differently: ``uv tool upgrade`` (and
36
+ ``cswap upgrade``) rebuilds the tool's virtualenv — ``sys.executable`` points
37
+ inside that virtualenv and can be replaced — while the console script keeps its
38
+ path across upgrades. Pinning the script means an upgraded cswap needs a
39
+ ``launchctl kickstart``, not a reinstalled service. ``sys.executable -m
40
+ claude_swap`` stays as the fallback for installs that expose no console script.
41
+
42
+ *Logs go to ``~/Library/Logs``, not ``/tmp``.* ``/tmp`` is world-writable and
43
+ periodically purged, so a crash log can vanish before anyone reads it, and a
44
+ predictable world-writable path is a poor place to point a long-lived writer.
45
+
46
+ Everything here is macOS-only; callers guard on ``sys.platform`` and the public
47
+ functions refuse rather than half-work elsewhere.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import json
53
+ import os
54
+ import plistlib
55
+ import shutil
56
+ import subprocess
57
+ import sys
58
+ import time
59
+ from collections.abc import Mapping
60
+ from pathlib import Path
61
+
62
+ from claude_swap.exceptions import ClaudeSwitchError
63
+ from claude_swap.fsutil import atomic_write_bytes
64
+
65
+ LABEL = "com.cswap.menubar"
66
+
67
+ # The one invocation that runs the menu bar in the calling process. launchd's
68
+ # plist uses it; so does a developer who wants the app attached to a terminal.
69
+ WORKER_FLAG = "--foreground"
70
+
71
+ # Where the user switches a LaunchAgent off. The switch governs the start at
72
+ # login only: macOS still lets the user's own `launchctl bootstrap` through, so
73
+ # a start is allowed to proceed, but it has to say that this is where the
74
+ # login start was turned off.
75
+ SYSTEM_SETTINGS_HINT = (
76
+ "System Settings → General → Login Items & Extensions → Allow in the Background"
77
+ )
78
+
79
+ # `sfltool dumpbtm` lists every background item with its disposition; it is
80
+ # the only non-root view of the System Settings switch and takes ~2 s.
81
+ _BTM_DUMP_TIMEOUT_SECONDS = 15.0
82
+
83
+ # launchd's default PATH is /usr/bin:/bin:/usr/sbin:/sbin, which covers
84
+ # `security` (Keychain reads) but not a Homebrew or ~/.local/bin `claude`. The
85
+ # menu bar shells out to detect running sessions, so seed a PATH that finds it.
86
+ _EXTRA_PATH_DIRS = ("~/.local/bin", "/opt/homebrew/bin", "/usr/local/bin")
87
+ _BASE_PATH_DIRS = ("/usr/bin", "/bin", "/usr/sbin", "/sbin")
88
+
89
+ # launchd does not inherit the installing shell's environment, so a user behind
90
+ # a proxy would get an agent that dials direct. Forward only these, never all.
91
+ # A key that is set but empty is forwarded too: urllib reads an empty lowercase
92
+ # name as cancelling its uppercase twin (`https_proxy=` switches off an
93
+ # `HTTPS_PROXY`), so dropping it would hand the agent a proxy the shell had
94
+ # turned off. launchd sets an empty string as an empty variable.
95
+ _PROFILE_ENV_KEYS = ("CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", "XDG_DATA_HOME")
96
+ _FORWARDED_ENV_KEYS = (
97
+ "https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY",
98
+ "no_proxy", "NO_PROXY", "SSL_CERT_FILE", "SSL_CERT_DIR",
99
+ # The profile the installing shell was in. Without these the service
100
+ # would manage the default profile while the shell that set it up manages
101
+ # another. There is one service per user, and it follows the shell that
102
+ # installed it; `--install-service` from a different profile says so.
103
+ *_PROFILE_ENV_KEYS,
104
+ )
105
+
106
+ # Written by the worker at start: its pid and build. Lets a later `cswap
107
+ # menubar` (or `cswap upgrade`) tell a running instance of an old build from
108
+ # the installed one, whichever way the upgrade happened.
109
+ STAMP_NAME = "menubar_worker.json"
110
+
111
+ # A worker younger than this may simply not have written its stamp yet (the
112
+ # bundle hop and the imports come first); a missing stamp says nothing then.
113
+ _STAMP_GRACE_SECONDS = 60.0
114
+
115
+ # `launchctl bootout` can return before launchd has finished tearing the
116
+ # job down, and a `bootstrap` inside that window fails with "Operation
117
+ # already in progress". Poll until the job is really gone instead of
118
+ # assuming bootout was synchronous (Homebrew's services code does the same).
119
+ _UNLOAD_TIMEOUT_SECONDS = 5.0
120
+ _UNLOAD_POLL_SECONDS = 0.1
121
+
122
+ # After a bootstrap or kickstart launchd spawns the job asynchronously; wait
123
+ # briefly for a pid so the caller can print one, but never block on it.
124
+ _SPAWN_TIMEOUT_SECONDS = 2.0
125
+
126
+
127
+ def _require_macos() -> None:
128
+ if sys.platform != "darwin":
129
+ raise ClaudeSwitchError(
130
+ "The menu bar service is only available on macOS."
131
+ )
132
+
133
+
134
+ def plist_path(label: str = LABEL, home: Path | None = None) -> Path:
135
+ """The plist's path while the menu bar starts at login."""
136
+ return (home or Path.home()) / "Library" / "LaunchAgents" / f"{label}.plist"
137
+
138
+
139
+ def session_plist_path(label: str = LABEL, backup_dir: Path | None = None) -> Path:
140
+ """The plist's path while Start at login is off (see the module docstring)."""
141
+ if backup_dir is None:
142
+ from claude_swap.paths import get_backup_root
143
+
144
+ backup_dir = get_backup_root()
145
+ return Path(backup_dir) / f"{label}.plist"
146
+
147
+
148
+ def start_at_login_enabled(label: str = LABEL, home: Path | None = None) -> bool:
149
+ """Whether launchd will start the menu bar at the next login."""
150
+ return plist_path(label, home).exists()
151
+
152
+
153
+ def worker_stamp_path(backup_dir: Path | None = None) -> Path:
154
+ if backup_dir is None:
155
+ from claude_swap.paths import get_backup_root
156
+
157
+ backup_dir = get_backup_root()
158
+ return Path(backup_dir) / STAMP_NAME
159
+
160
+
161
+ def write_worker_stamp(backup_dir: Path | None = None) -> Path:
162
+ """Record this process's pid and build; called by the menu bar at start."""
163
+ from claude_swap.update_check import install_identity
164
+
165
+ path = worker_stamp_path(backup_dir)
166
+ path.parent.mkdir(parents=True, exist_ok=True)
167
+ data = {"pid": os.getpid(), "started_at": time.time(), **install_identity()}
168
+ atomic_write_bytes(path, json.dumps(data, indent=2).encode("utf-8"))
169
+ return path
170
+
171
+
172
+ def read_worker_stamp(backup_dir: Path | None = None) -> dict | None:
173
+ try:
174
+ loaded = json.loads(worker_stamp_path(backup_dir).read_text(encoding="utf-8"))
175
+ except (OSError, ValueError):
176
+ return None
177
+ return loaded if isinstance(loaded, dict) else None
178
+
179
+
180
+ def _parse_etime(text: str) -> float | None:
181
+ """Seconds from ``ps -o etime`` output: ``[[dd-]hh:]mm:ss``."""
182
+ text = text.strip()
183
+ if not text:
184
+ return None
185
+ days = 0
186
+ if "-" in text:
187
+ day_part, text = text.split("-", 1)
188
+ if not day_part.isdigit():
189
+ return None
190
+ days = int(day_part)
191
+ parts = text.split(":")
192
+ if not 2 <= len(parts) <= 3 or not all(part.isdigit() for part in parts):
193
+ return None
194
+ values = [int(part) for part in parts]
195
+ hours, minutes, seconds = (0, *values) if len(values) == 2 else values
196
+ return float(days * 86400 + hours * 3600 + minutes * 60 + seconds)
197
+
198
+
199
+ def _process_age_seconds(pid: int) -> float | None:
200
+ """Seconds since ``pid`` started, or None when ``ps`` cannot say."""
201
+ try:
202
+ proc = subprocess.run(
203
+ ["ps", "-p", str(pid), "-o", "etime="],
204
+ capture_output=True,
205
+ text=True,
206
+ check=False,
207
+ timeout=5,
208
+ )
209
+ except (OSError, subprocess.SubprocessError):
210
+ return None
211
+ if proc.returncode != 0:
212
+ return None
213
+ return _parse_etime(proc.stdout)
214
+
215
+
216
+ def worker_build_is_stale(pid: int, backup_dir: Path | None = None) -> bool:
217
+ """Whether the worker running as ``pid`` should be restarted onto this build.
218
+
219
+ With a stamp of its own (pid match) the answer is exact: version and commit
220
+ are compared, so a git install whose version string never moves still
221
+ counts. Without one — a worker from before stamps existed (the 0.30 and
222
+ 1.0.0b1 builds), or one that could not write the data directory — the
223
+ build is unknown, and the worker is restarted once so that its successor
224
+ can be told apart. Not while it may still be writing its stamp, and not
225
+ when a stamp cannot be written here either: then every call would restart
226
+ it, which is worse than an unknown build.
227
+ """
228
+ stamp = read_worker_stamp(backup_dir)
229
+ if not stamp or stamp.get("pid") != pid:
230
+ age = _process_age_seconds(pid)
231
+ if age is None or age < _STAMP_GRACE_SECONDS:
232
+ return False
233
+ return os.access(worker_stamp_path(backup_dir).parent, os.W_OK)
234
+ from claude_swap.update_check import install_identity
235
+
236
+ current = install_identity()
237
+ return (stamp.get("version"), stamp.get("source")) != (
238
+ current["version"],
239
+ current["source"],
240
+ )
241
+
242
+
243
+ def log_paths(label: str = LABEL, home: Path | None = None) -> tuple[Path, Path]:
244
+ """``(stdout, stderr)`` log destinations for ``label``."""
245
+ logs = (home or Path.home()) / "Library" / "Logs"
246
+ return logs / f"{label}.log", logs / f"{label}.err"
247
+
248
+
249
+ def service_target(label: str = LABEL, uid: int | None = None) -> str:
250
+ """launchd service target, e.g. ``gui/501/com.cswap.menubar``."""
251
+ return f"gui/{os.getuid() if uid is None else uid}/{label}"
252
+
253
+
254
+ def domain_target(uid: int | None = None) -> str:
255
+ """launchd domain target, e.g. ``gui/501``."""
256
+ return f"gui/{os.getuid() if uid is None else uid}"
257
+
258
+
259
+ def resolve_program() -> list[str]:
260
+ """Argv prefix that launchd should run, minus the subcommand.
261
+
262
+ Prefers the installed console script (stable across upgrades, see the
263
+ module docstring) and falls back to running the package through the
264
+ interpreter that is executing right now.
265
+
266
+ The path is made absolute but deliberately NOT resolved: a `uv tool
267
+ install` puts a symlink at ``~/.local/bin/cswap`` pointing into the tool's
268
+ virtualenv, and resolving it would write that virtualenv-internal path
269
+ into the plist — the very path this module avoids pinning, since a
270
+ reinstall recreates the virtualenv while the symlink keeps its name.
271
+ """
272
+ candidate = sys.argv[0] if sys.argv and sys.argv[0] else None
273
+ if candidate is not None:
274
+ absolute = Path(os.path.abspath(candidate))
275
+ if absolute.name == "cswap" and absolute.is_file():
276
+ return [str(absolute)]
277
+
278
+ which = shutil.which("cswap")
279
+ if which:
280
+ return [str(Path(os.path.abspath(which)))]
281
+
282
+ return [sys.executable, "-m", "claude_swap"]
283
+
284
+
285
+ def program_arguments(program: list[str] | None = None) -> list[str]:
286
+ """The argv launchd runs: the program plus the worker invocation."""
287
+ return [*(program or resolve_program()), "menubar", WORKER_FLAG]
288
+
289
+
290
+ def _path_env(program: list[str]) -> str:
291
+ """PATH for the agent, with the program's own directory first."""
292
+ dirs: list[str] = []
293
+ first = Path(program[0]).parent
294
+ if str(first) not in ("", "."):
295
+ dirs.append(str(first))
296
+ for extra in (*_EXTRA_PATH_DIRS, *_BASE_PATH_DIRS):
297
+ expanded = os.path.expanduser(extra)
298
+ if expanded not in dirs:
299
+ dirs.append(expanded)
300
+ return ":".join(dirs)
301
+
302
+
303
+ def _plist_dict(
304
+ program: list[str] | None = None,
305
+ label: str = LABEL,
306
+ home: Path | None = None,
307
+ env: Mapping[str, str] | None = None,
308
+ ) -> dict:
309
+ """The LaunchAgent definition, as the dict :func:`build_plist` serializes."""
310
+ program = program or resolve_program()
311
+ out_log, err_log = log_paths(label, home)
312
+ env = os.environ if env is None else env
313
+ forwarded = {k: env[k] for k in _FORWARDED_ENV_KEYS if k in env}
314
+ return {
315
+ "Label": label,
316
+ "ProgramArguments": program_arguments(program),
317
+ "RunAtLoad": True,
318
+ # Restart a crash, but respect a deliberate Quit. The menu bar's
319
+ # quit handler calls rumps.quit_application(), a clean exit(0);
320
+ # under a bare `KeepAlive: True` launchd would relaunch it at once
321
+ # and the Quit item would do nothing the user can see.
322
+ "KeepAlive": {"SuccessfulExit": False},
323
+ # A menu bar owner is a UI process; Background would have launchd
324
+ # apply throttled I/O and CPU bands to it.
325
+ "ProcessType": "Interactive",
326
+ "EnvironmentVariables": {"PATH": _path_env(program), **forwarded},
327
+ "StandardOutPath": str(out_log),
328
+ "StandardErrorPath": str(err_log),
329
+ }
330
+
331
+
332
+ def build_plist(
333
+ program: list[str] | None = None,
334
+ label: str = LABEL,
335
+ home: Path | None = None,
336
+ env: Mapping[str, str] | None = None,
337
+ ) -> bytes:
338
+ """Serialize the LaunchAgent plist.
339
+
340
+ Built with :mod:`plistlib` rather than a formatted XML string so paths
341
+ containing ``&`` or ``<`` cannot produce a plist launchd refuses to parse.
342
+ """
343
+ return plistlib.dumps(_plist_dict(program, label, home, env))
344
+
345
+
346
+ def _load_plist(path: Path) -> dict | None:
347
+ """The plist at ``path`` as a dict; None when absent or unreadable.
348
+
349
+ An unreadable plist is treated like a missing one so that :func:`ensure`
350
+ rewrites it rather than handing launchd a file it will refuse.
351
+ """
352
+ try:
353
+ loaded = plistlib.loads(path.read_bytes())
354
+ except (OSError, plistlib.InvalidFileException, ValueError):
355
+ return None
356
+ return loaded if isinstance(loaded, dict) else None
357
+
358
+
359
+ def _launchctl(*args: str) -> subprocess.CompletedProcess:
360
+ try:
361
+ return subprocess.run(
362
+ ["launchctl", *args],
363
+ capture_output=True,
364
+ text=True,
365
+ check=False,
366
+ )
367
+ except FileNotFoundError as e: # pragma: no cover - launchctl is in the base OS
368
+ raise ClaudeSwitchError("launchctl not found; is this macOS?") from e
369
+
370
+
371
+ def _wait_until_unloaded(
372
+ label: str = LABEL,
373
+ uid: int | None = None,
374
+ timeout: float = _UNLOAD_TIMEOUT_SECONDS,
375
+ ) -> bool:
376
+ """Block until launchd has dropped the job. True if it went away in time."""
377
+ deadline = time.monotonic() + timeout
378
+ while is_loaded(label, uid):
379
+ if time.monotonic() >= deadline:
380
+ return False
381
+ time.sleep(_UNLOAD_POLL_SECONDS)
382
+ return True
383
+
384
+
385
+ def _wait_for_pid(
386
+ label: str = LABEL,
387
+ uid: int | None = None,
388
+ timeout: float = _SPAWN_TIMEOUT_SECONDS,
389
+ ) -> int | None:
390
+ """The job's pid once launchd has spawned it, or None if it took too long."""
391
+ deadline = time.monotonic() + timeout
392
+ while True:
393
+ pid = service_pid(label, uid)
394
+ if pid is not None or time.monotonic() >= deadline:
395
+ return pid
396
+ time.sleep(_UNLOAD_POLL_SECONDS)
397
+
398
+
399
+ def is_loaded(label: str = LABEL, uid: int | None = None) -> bool:
400
+ """Whether launchd currently knows about the service."""
401
+ return _launchctl("print", service_target(label, uid)).returncode == 0
402
+
403
+
404
+ def _launchd_disabled(label: str = LABEL, uid: int | None = None) -> bool:
405
+ """Whether launchd's own override list disables the service.
406
+
407
+ ``launchctl print-disabled gui/<uid>`` is what ``launchctl disable`` writes.
408
+ Older launchctl spelled the value ``true``; current ones say ``disabled``.
409
+ A list that cannot be read counts as "not disabled".
410
+ """
411
+ printed = _launchctl("print-disabled", domain_target(uid))
412
+ if printed.returncode != 0:
413
+ return False
414
+ key = f'"{label}"'
415
+ for line in printed.stdout.splitlines():
416
+ stripped = line.strip()
417
+ if stripped.startswith(key) and "=>" in stripped:
418
+ value = stripped.split("=>", 1)[1].strip().rstrip(";").lower()
419
+ return value in ("disabled", "true")
420
+ return False
421
+
422
+
423
+ def _btm_record_disallowed(dump: str, label: str) -> bool:
424
+ """Whether ``sfltool dumpbtm`` output lists ``label`` as switched off.
425
+
426
+ Records are blocks headed `` #N:``; each has a ``Disposition: [..]`` line
427
+ before its ``Identifier:`` line, which BTM spells as ``<type>.<label>``
428
+ (``8.com.cswap.menubar`` for a user agent). ``disallowed`` in the
429
+ disposition is the "Allow in the Background" switch in the off position;
430
+ an item the user left alone reads ``allowed``.
431
+ """
432
+ matches = disallowed = False
433
+ for raw in dump.splitlines():
434
+ line = raw.strip()
435
+ if line.startswith("#") and line.endswith(":"):
436
+ if matches and disallowed:
437
+ return True
438
+ matches = disallowed = False
439
+ elif line.startswith("Identifier:"):
440
+ identifier = line.split(":", 1)[1].strip()
441
+ matches = identifier == label or identifier.endswith("." + label)
442
+ elif line.startswith("Disposition:") and "[" in line:
443
+ flags = line.split("[", 1)[1].split("]", 1)[0]
444
+ disallowed = "disallowed" in [flag.strip() for flag in flags.split(",")]
445
+ return matches and disallowed
446
+
447
+
448
+ def _btm_disallowed(label: str = LABEL) -> bool:
449
+ """Whether the user switched the item off under Login Items & Extensions.
450
+
451
+ That switch is recorded by backgroundtaskmanagementd, not in launchd's
452
+ disabled list, and it governs the start at login only: a manual
453
+ ``launchctl bootstrap`` from the user's own session still goes through
454
+ (verified on macOS 27). A dump that cannot be read — older releases want
455
+ root for it — counts as "not switched off".
456
+ """
457
+ try:
458
+ proc = subprocess.run(
459
+ ["sfltool", "dumpbtm"],
460
+ capture_output=True,
461
+ text=True,
462
+ check=False,
463
+ timeout=_BTM_DUMP_TIMEOUT_SECONDS,
464
+ )
465
+ except (OSError, subprocess.SubprocessError):
466
+ return False
467
+ if proc.returncode != 0:
468
+ return False
469
+ return _btm_record_disallowed(proc.stdout, label)
470
+
471
+
472
+ def switched_off_in_system_settings(label: str = LABEL, uid: int | None = None) -> bool:
473
+ """Whether the user turned the service off, in either place macOS offers.
474
+
475
+ Slow (about two seconds, see :func:`_btm_disallowed`), so callers ask only
476
+ when the answer changes what they say: before a start, and for status.
477
+ """
478
+ return _launchd_disabled(label, uid) or _btm_disallowed(label)
479
+
480
+
481
+ def _job_state(
482
+ label: str = LABEL, uid: int | None = None
483
+ ) -> tuple[bool, str | None, int | None]:
484
+ """``(loaded, state, pid)`` from ``launchctl print``."""
485
+ printed = _launchctl("print", service_target(label, uid))
486
+ loaded = printed.returncode == 0
487
+ state: str | None = None
488
+ pid: int | None = None
489
+ if loaded:
490
+ for line in printed.stdout.splitlines():
491
+ # `launchctl print` nests sub-dictionaries — pid-local endpoints,
492
+ # inherited environment — and those repeat keys the job itself
493
+ # uses, `state` among them. The job's own fields are the ones at a
494
+ # single tab, so anything deeper is a different object's field.
495
+ if not line.startswith("\t") or line.startswith("\t\t"):
496
+ continue
497
+ stripped = line.strip()
498
+ if state is None and stripped.startswith("state = "):
499
+ state = stripped.removeprefix("state = ").strip()
500
+ elif pid is None and stripped.startswith("pid = "):
501
+ raw = stripped.removeprefix("pid = ").strip()
502
+ if raw.isdigit():
503
+ pid = int(raw)
504
+ return loaded, state, pid
505
+
506
+
507
+ def service_pid(label: str = LABEL, uid: int | None = None) -> int | None:
508
+ """The pid of the running service, or None when it is not running."""
509
+ return _job_state(label, uid)[2]
510
+
511
+
512
+ def running_as_service(label: str = LABEL, uid: int | None = None) -> bool:
513
+ """Whether THIS process is the launchd job for ``label``.
514
+
515
+ launchd's ``print`` names the job's pid; a match means launchd started us,
516
+ through whichever plist it holds, so ``cswap menubar`` must run the menu bar
517
+ here rather than try to start the service it already is. Off macOS there is
518
+ no launchd to ask.
519
+ """
520
+ if sys.platform != "darwin":
521
+ return False
522
+ pid = service_pid(label, uid)
523
+ return pid is not None and pid == os.getpid()
524
+
525
+
526
+ def status(
527
+ label: str = LABEL,
528
+ uid: int | None = None,
529
+ home: Path | None = None,
530
+ backup_dir: Path | None = None,
531
+ ) -> dict:
532
+ """Installed / loaded / running state, plus the pid when there is one.
533
+
534
+ ``installed`` and ``start_at_login`` both mean "the plist is in
535
+ ``~/Library/LaunchAgents``"; the first name predates the second and is kept
536
+ for callers that read it. ``session_plist`` is set while Start at login is
537
+ off, ``configured`` is true when either plist exists, and ``switched_off``
538
+ reports the System Settings switch (a slow read, see
539
+ :func:`switched_off_in_system_settings`).
540
+ """
541
+ from claude_swap.update_check import describe_identity, install_identity
542
+
543
+ _require_macos()
544
+ loaded, state, pid = _job_state(label, uid)
545
+ login = plist_path(label, home)
546
+ session = session_plist_path(label, backup_dir)
547
+ stamp = read_worker_stamp(backup_dir)
548
+ own_stamp = stamp if (stamp and pid is not None and stamp.get("pid") == pid) else None
549
+ return {
550
+ "label": label,
551
+ "installed": login.exists(),
552
+ "start_at_login": login.exists(),
553
+ "session_plist": str(session) if session.exists() else None,
554
+ "configured": login.exists() or session.exists(),
555
+ "loaded": loaded,
556
+ "state": state,
557
+ "pid": pid,
558
+ "plist": str(login),
559
+ "switched_off": switched_off_in_system_settings(label, uid),
560
+ "running_build": describe_identity(own_stamp) if own_stamp else None,
561
+ "installed_build": describe_identity(install_identity()),
562
+ "stale_build": pid is not None and worker_build_is_stale(pid, backup_dir),
563
+ }
564
+
565
+
566
+ def _bootstrap(target_plist: Path, label: str, uid: int | None, settled: bool) -> None:
567
+ booted = _launchctl("bootstrap", domain_target(uid), str(target_plist))
568
+ if booted.returncode != 0:
569
+ detail = (booted.stderr or booted.stdout or "").strip()
570
+ if not settled:
571
+ detail = f"{detail}; the previous instance was still shutting down".lstrip("; ")
572
+ raise ClaudeSwitchError(
573
+ f"launchctl bootstrap failed (exit {booted.returncode})"
574
+ + (f": {detail}" if detail else "")
575
+ )
576
+
577
+
578
+ def _reload(target_plist: Path, label: str, uid: int | None) -> None:
579
+ """Hand launchd ``target_plist``, replacing a loaded definition if any.
580
+
581
+ launchd keeps a bootstrapped job's definition in memory, so a changed
582
+ plist only takes effect through bootout + bootstrap; ``kickstart`` would
583
+ restart the old definition.
584
+ """
585
+ settled = True
586
+ if is_loaded(label, uid):
587
+ _launchctl("bootout", service_target(label, uid))
588
+ settled = _wait_until_unloaded(label, uid)
589
+ _bootstrap(target_plist, label, uid, settled)
590
+
591
+
592
+ def kickstart(
593
+ label: str = LABEL, uid: int | None = None, *, restart: bool = False
594
+ ) -> None:
595
+ """Start a loaded job now; with ``restart`` also kill a running one first."""
596
+ args = ["kickstart", *(["-k"] if restart else []), service_target(label, uid)]
597
+ kicked = _launchctl(*args)
598
+ if kicked.returncode != 0:
599
+ detail = (kicked.stderr or kicked.stdout or "").strip()
600
+ raise ClaudeSwitchError(
601
+ f"launchctl kickstart failed (exit {kicked.returncode})"
602
+ + (f": {detail}" if detail else "")
603
+ )
604
+
605
+
606
+ def ensure(
607
+ label: str = LABEL,
608
+ home: Path | None = None,
609
+ backup_dir: Path | None = None,
610
+ program: list[str] | None = None,
611
+ uid: int | None = None,
612
+ *,
613
+ restart: bool = False,
614
+ ) -> dict:
615
+ """Make the menu bar service run; first setup registers it at login.
616
+
617
+ What happens depends on what is there (the module docstring has the why):
618
+
619
+ * no plist anywhere — first setup: the plist goes to ``~/Library/LaunchAgents``
620
+ and is bootstrapped, so the menu bar starts now and at every login;
621
+ * a plist in ``~/Library/LaunchAgents`` — Start at login is on: a stopped
622
+ job is kickstarted, an unloaded one bootstrapped, a running one left alone;
623
+ * a plist only in the data directory — the user turned Start at login off:
624
+ the same, but bootstrapped from there, so launchd forgets it at logout;
625
+ * both — the login copy wins and the other is removed.
626
+
627
+ A plist whose ``ProgramArguments`` no longer match this install (a reinstall
628
+ moved the console script, or the file predates the worker flag) is rewritten
629
+ and the job reloaded, keeping the environment the installing shell
630
+ forwarded — this shell may lack the proxy variables that one had. ``restart``
631
+ restarts a running job even when nothing changed, for a setting the menu bar
632
+ only reads at launch.
633
+
634
+ A service the user switched off under Login Items & Extensions is still
635
+ started: macOS itself allows the manual start and reserves that switch for
636
+ the start at login, so refusing would be stricter than the OS. The result's
637
+ ``switched_off`` lets the caller say that it will not come back at login.
638
+ Returns the action taken (``first-setup``, ``started``, ``restarted`` or
639
+ ``already-running``) with the paths and the pid.
640
+ """
641
+ _require_macos()
642
+ program = program or resolve_program()
643
+ login_plist = plist_path(label, home)
644
+ session_plist = session_plist_path(label, backup_dir)
645
+ out_log, err_log = log_paths(label, home)
646
+
647
+ first_setup = not login_plist.exists() and not session_plist.exists()
648
+ if first_setup or login_plist.exists():
649
+ target = login_plist
650
+ if session_plist.exists():
651
+ session_plist.unlink()
652
+ else:
653
+ target = session_plist
654
+ target.parent.mkdir(parents=True, exist_ok=True)
655
+ out_log.parent.mkdir(parents=True, exist_ok=True)
656
+
657
+ wanted = _plist_dict(program, label, home)
658
+ existing = _load_plist(target)
659
+ repaired = False
660
+ if existing is None:
661
+ # Owner-only and atomic, not the umask's 0644 via write_bytes: a
662
+ # forwarded proxy URL can carry credentials, and a write cut short by
663
+ # Ctrl-C must not leave a truncated plist for the next login to choke on.
664
+ atomic_write_bytes(target, plistlib.dumps(wanted))
665
+ repaired = not first_setup
666
+ elif existing.get("ProgramArguments") != wanted["ProgramArguments"]:
667
+ env = dict(existing.get("EnvironmentVariables") or {})
668
+ env["PATH"] = wanted["EnvironmentVariables"]["PATH"]
669
+ wanted["EnvironmentVariables"] = env
670
+ atomic_write_bytes(target, plistlib.dumps(wanted))
671
+ repaired = True
672
+
673
+ loaded, _state, pid = _job_state(label, uid)
674
+ switched_off = False
675
+ # A running worker of an older build is restarted onto this one: that is
676
+ # what makes "ensure" cover an upgrade made by `uv tool upgrade` by hand.
677
+ stale_build = (
678
+ pid is not None and not repaired and not restart
679
+ and worker_build_is_stale(pid, backup_dir)
680
+ )
681
+ if pid is not None and not repaired and not restart and not stale_build:
682
+ action = "already-running"
683
+ else:
684
+ # Asked only when something is about to start: the read takes ~2 s and
685
+ # a running service has nothing new to say about the login start.
686
+ switched_off = switched_off_in_system_settings(label, uid)
687
+ action = "restarted" if pid is not None else ("first-setup" if first_setup else "started")
688
+ if repaired or not loaded:
689
+ _reload(target, label, uid)
690
+ else:
691
+ kickstart(label, uid, restart=pid is not None)
692
+ pid = _wait_for_pid(label, uid)
693
+
694
+ return {
695
+ "label": label,
696
+ "action": action,
697
+ "start_at_login": target == login_plist,
698
+ "plist": str(target),
699
+ "program": wanted["ProgramArguments"],
700
+ "stdout_log": str(out_log),
701
+ "stderr_log": str(err_log),
702
+ "pid": pid,
703
+ "switched_off": switched_off,
704
+ "stale_build": stale_build,
705
+ }
706
+
707
+
708
+ def install(
709
+ label: str = LABEL,
710
+ home: Path | None = None,
711
+ program: list[str] | None = None,
712
+ uid: int | None = None,
713
+ backup_dir: Path | None = None,
714
+ ) -> dict:
715
+ """Write the login plist from this shell's environment and (re)load it.
716
+
717
+ The explicit form of first setup, and the way back to starting at login
718
+ after the menu's toggle moved the plist out: a session-only plist is removed
719
+ and the login one written fresh. Idempotent: an already-loaded service is
720
+ booted out first, so running this after an upgrade re-reads the plist
721
+ instead of failing with launchd's "service already loaded" (EEXIST, code 5).
722
+ """
723
+ _require_macos()
724
+ program = program or resolve_program()
725
+ target_plist = plist_path(label, home)
726
+ out_log, err_log = log_paths(label, home)
727
+
728
+ target_plist.parent.mkdir(parents=True, exist_ok=True)
729
+ out_log.parent.mkdir(parents=True, exist_ok=True)
730
+ # A reinstall from a shell in another profile silently redirects the
731
+ # service; report what moved so the caller can say so. The previous
732
+ # configuration is in whichever home the plist currently has: the data
733
+ # directory while Start at login is off.
734
+ session_plist = session_plist_path(label, backup_dir)
735
+ wanted = _plist_dict(program, label, home)
736
+ previous = _load_plist(target_plist) or _load_plist(session_plist)
737
+ profile_changes: list[tuple[str, str | None, str | None]] = []
738
+ if previous is not None:
739
+ old_env = previous.get("EnvironmentVariables") or {}
740
+ new_env = wanted["EnvironmentVariables"]
741
+ profile_changes = [
742
+ (key, old_env.get(key), new_env.get(key))
743
+ for key in _PROFILE_ENV_KEYS
744
+ if old_env.get(key) != new_env.get(key)
745
+ ]
746
+ # Owner-only and atomic, not the umask's 0644 via write_bytes: a forwarded
747
+ # proxy URL can carry credentials, and a write cut short by Ctrl-C must
748
+ # not leave a truncated plist for the next login to choke on.
749
+ atomic_write_bytes(target_plist, plistlib.dumps(wanted))
750
+ if session_plist.exists():
751
+ session_plist.unlink()
752
+
753
+ _reload(target_plist, label, uid)
754
+
755
+ return {
756
+ "label": label,
757
+ "plist": str(target_plist),
758
+ "program": wanted["ProgramArguments"],
759
+ "start_at_login": True,
760
+ "stdout_log": str(out_log),
761
+ "stderr_log": str(err_log),
762
+ "profile_changes": profile_changes,
763
+ }
764
+
765
+
766
+ def uninstall(
767
+ label: str = LABEL,
768
+ home: Path | None = None,
769
+ uid: int | None = None,
770
+ backup_dir: Path | None = None,
771
+ ) -> dict:
772
+ """Stop the service and remove every trace the menu bar left on the Mac.
773
+
774
+ That is the plist in either home, launchd's own record of the service
775
+ (the "Allow in the Background" switch leaves a disabled override that
776
+ would otherwise outlive the plist), the wrapper ``.app`` the menu bar built
777
+ for itself, and the two log files. Tolerates every partial state — loaded
778
+ without a plist, a plist that was never bootstrapped, neither — because
779
+ the point of an uninstall is to arrive at "gone", not to insist on the
780
+ path taken to get there. A bundle that cannot be deleted is reported, not
781
+ fatal: the service itself is already gone by then.
782
+ """
783
+ _require_macos()
784
+ was_loaded = is_loaded(label, uid)
785
+ if was_loaded:
786
+ booted_out = _launchctl("bootout", service_target(label, uid))
787
+ if booted_out.returncode != 0 and is_loaded(label, uid):
788
+ detail = (booted_out.stderr or booted_out.stdout or "").strip()
789
+ raise ClaudeSwitchError(
790
+ f"launchctl bootout failed (exit {booted_out.returncode})"
791
+ + (f": {detail}" if detail else "")
792
+ )
793
+
794
+ cleared_override = False
795
+ if _launchd_disabled(label, uid):
796
+ cleared_override = _launchctl("enable", service_target(label, uid)).returncode == 0
797
+
798
+ removed_paths: list[Path] = []
799
+ for candidate in (plist_path(label, home), session_plist_path(label, backup_dir)):
800
+ if candidate.exists():
801
+ candidate.unlink()
802
+ removed_paths.append(candidate)
803
+ for log in log_paths(label, home):
804
+ if log.exists():
805
+ log.unlink()
806
+ removed_paths.append(log)
807
+ stamp = worker_stamp_path(backup_dir)
808
+ if stamp.exists():
809
+ stamp.unlink()
810
+ removed_paths.append(stamp)
811
+
812
+ from claude_swap import app_bundle
813
+
814
+ if backup_dir is None:
815
+ from claude_swap.paths import get_backup_root
816
+
817
+ backup_dir = get_backup_root()
818
+ bundle_error: str | None = None
819
+ try:
820
+ removed_paths.extend(app_bundle.remove(backup_dir))
821
+ except OSError as exc:
822
+ bundle_error = str(exc)
823
+
824
+ return {
825
+ "label": label,
826
+ "was_loaded": was_loaded,
827
+ "removed_plist": any(p.suffix == ".plist" for p in removed_paths),
828
+ "removed": [str(p) for p in removed_paths],
829
+ "cleared_override": cleared_override,
830
+ "bundle_error": bundle_error,
831
+ }
832
+
833
+
834
+ def set_start_at_login(
835
+ enabled: bool,
836
+ label: str = LABEL,
837
+ home: Path | None = None,
838
+ backup_dir: Path | None = None,
839
+ program: list[str] | None = None,
840
+ ) -> dict:
841
+ """Record the Start-at-login preference by moving the plist between its homes.
842
+
843
+ Only the file moves; launchd is not touched. The running job keeps its
844
+ in-memory definition either way, the next login scans only
845
+ ``~/Library/LaunchAgents``, and the menu calls this from inside the very
846
+ process a bootout would kill. With no plist anywhere (the menu bar was run
847
+ with ``--foreground`` from a shell) a fresh one is written at the chosen
848
+ location, so the choice is remembered.
849
+ """
850
+ _require_macos()
851
+ login_plist = plist_path(label, home)
852
+ session_plist = session_plist_path(label, backup_dir)
853
+ source, destination = (
854
+ (session_plist, login_plist) if enabled else (login_plist, session_plist)
855
+ )
856
+ destination.parent.mkdir(parents=True, exist_ok=True)
857
+ if source.exists():
858
+ atomic_write_bytes(destination, source.read_bytes())
859
+ source.unlink()
860
+ elif not destination.exists():
861
+ atomic_write_bytes(destination, build_plist(program, label, home))
862
+ return {"label": label, "start_at_login": enabled, "plist": str(destination)}