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,370 @@
1
+ """Detect running Claude Code instances.
2
+
3
+ Reads session PID files (~/.claude/sessions/{pid}.json) and IDE lockfiles
4
+ (~/.claude/ide/{port}.lock) to determine which Claude Code instances are
5
+ currently running. Uses the same mechanism Claude Code itself uses internally.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import calendar
11
+ import json
12
+ import logging
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ from claude_swap import spawn
20
+ from claude_swap.paths import get_claude_config_home
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # A session record names a pid, and the OS recycles pids: once the claude
25
+ # that wrote the record is gone, the number can belong to anything. The
26
+ # record also carries claude's reading of its own start (``procStart``): on
27
+ # Linux the ``/proc/<pid>/stat`` start time in clock ticks since boot, fixed
28
+ # for the process's lifetime, and elsewhere ``ps -o lstart``, a wall-clock
29
+ # time. Only the latter needs slack, for the small clock steps that move a
30
+ # ``ps`` start time on some platforms.
31
+ PID_REUSE_SLACK_S = 120
32
+
33
+ _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
34
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
35
+
36
+
37
+ @dataclass
38
+ class ClaudeSession:
39
+ """A running Claude Code session from ~/.claude/sessions/{pid}.json."""
40
+
41
+ pid: int
42
+ session_id: str
43
+ cwd: str
44
+ started_at: int # epoch milliseconds
45
+ kind: str # "interactive", "bg", "daemon", "daemon-worker"
46
+ entrypoint: str # "cli", "claude-vscode", "claude-desktop", "sdk-cli", "mcp"
47
+ status: str | None = None # "busy", "idle", "waiting"
48
+
49
+
50
+ @dataclass
51
+ class IdeInstance:
52
+ """A running IDE instance from ~/.claude/ide/{port}.lock."""
53
+
54
+ port: int # from filename
55
+ pid: int
56
+ ide_name: str # "Visual Studio Code", "Cursor", "Windsurf"
57
+ workspace_folders: list[str] = field(default_factory=list)
58
+
59
+
60
+ def get_claude_dir() -> Path:
61
+ """Return the Claude config directory, respecting CLAUDE_CONFIG_DIR."""
62
+ return get_claude_config_home()
63
+
64
+
65
+ def is_pid_alive(pid: int) -> bool:
66
+ """Check whether a process with the given PID is running.
67
+
68
+ Cross-platform:
69
+ - macOS/Linux/WSL: os.kill(pid, 0)
70
+ - Windows: ctypes OpenProcess
71
+ """
72
+ if pid <= 1:
73
+ return False
74
+
75
+ if sys.platform == "win32":
76
+ return _is_pid_alive_windows(pid)
77
+
78
+ try:
79
+ os.kill(pid, 0)
80
+ return True
81
+ except PermissionError:
82
+ # EPERM means the process exists but we lack permission
83
+ return True
84
+ except OSError:
85
+ return False
86
+
87
+
88
+ def _is_pid_alive_windows(pid: int) -> bool:
89
+ """Windows-specific PID liveness check using ctypes."""
90
+ try:
91
+ import ctypes
92
+
93
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
94
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
95
+ handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
96
+ if handle:
97
+ kernel32.CloseHandle(handle)
98
+ return True
99
+ return False
100
+ except Exception:
101
+ return False
102
+
103
+
104
+ def _ps(pid: int, *columns: str) -> str | None:
105
+ """``ps -o`` ``columns`` for ``pid``, or None when unknowable.
106
+
107
+ POSIX only, under ``LC_ALL=C TZ=UTC`` like claude's own reading. Windows
108
+ and every failure answer None: not knowing must never be read as "not
109
+ the recorded process".
110
+ """
111
+ if sys.platform == "win32":
112
+ return None
113
+ try:
114
+ proc = spawn.run(
115
+ ["ps", "-o", ",".join(f"{c}=" for c in columns), "-p", str(pid)],
116
+ capture_output=True,
117
+ text=True,
118
+ timeout=5,
119
+ env={**os.environ, "LC_ALL": "C", "TZ": "UTC"},
120
+ )
121
+ except (OSError, subprocess.TimeoutExpired):
122
+ return None
123
+ text = proc.stdout.strip()
124
+ if proc.returncode != 0 or not text:
125
+ return None
126
+ return text
127
+
128
+
129
+ def process_started_at(pid: int) -> int | None:
130
+ """Epoch seconds at which ``pid`` started, or None when unknowable.
131
+
132
+ Read the way claude stamps ``procStart`` into its record, ``ps -o
133
+ lstart=`` under ``LC_ALL=C TZ=UTC``, so the two agree to the second for
134
+ the same process.
135
+ """
136
+ text = _ps(pid, "lstart")
137
+ if text is None:
138
+ return None
139
+ try:
140
+ return _lstart_seconds(text)
141
+ except ValueError:
142
+ return None
143
+
144
+
145
+ def _lstart_seconds(text: str) -> int:
146
+ """``Wed Sep 2 20:35:59 2026``, the ``ps -o lstart`` format under
147
+ ``LC_ALL=C TZ=UTC``, as epoch seconds. Parsed by hand because ``strptime``
148
+ reads month names in the process locale."""
149
+ parts = text.split()
150
+ if len(parts) != 5 or parts[1] not in _MONTHS:
151
+ raise ValueError(text)
152
+ _, month, day, clock, year = parts
153
+ hours, minutes, seconds = (int(p) for p in clock.split(":"))
154
+ return calendar.timegm(
155
+ (int(year), _MONTHS.index(month) + 1, int(day), hours, minutes, seconds, 0, 0, 0)
156
+ )
157
+
158
+
159
+ def process_start_ticks(pid: int) -> str | None:
160
+ """``/proc/<pid>/stat``'s start time, in clock ticks since boot, or None
161
+ when unreadable. Linux by construction: the file exists nowhere else."""
162
+ try:
163
+ text = Path(f"/proc/{pid}/stat").read_text(encoding="ascii", errors="replace")
164
+ except OSError:
165
+ return None
166
+ return _stat_start_ticks(text)
167
+
168
+
169
+ def _stat_start_ticks(text: str) -> str | None:
170
+ """Field 22 of a ``/proc/<pid>/stat`` line, as the string claude stamps
171
+ into ``procStart``. The command name sits in parentheses before the
172
+ numeric fields and may itself contain spaces or parentheses, so the
173
+ fields are counted from the last closing one."""
174
+ _, _, rest = text.rpartition(")")
175
+ fields = rest.split()
176
+ if len(fields) <= 19 or not fields[19].isdigit():
177
+ return None
178
+ return fields[19]
179
+
180
+
181
+ def process_is_claude(pid: int) -> bool | None:
182
+ """Does the process at ``pid`` look like a claude, or None when unknowable.
183
+
184
+ Judged from ``ps -o comm=,args=``: the native binary and the symlink to
185
+ it are named ``claude``, and an npm install runs ``cli.js`` out of a
186
+ ``claude-code`` package directory.
187
+ """
188
+ text = _ps(pid, "comm", "args")
189
+ if text is None:
190
+ return None
191
+ return "claude" in text.lower()
192
+
193
+
194
+ def pid_matches_record(pid: int, proc_start: str | None) -> bool:
195
+ """Is the live process at ``pid`` the one that wrote a record stamped
196
+ ``proc_start``, claude's reading of its own start?
197
+
198
+ On Linux the stamp is the ``/proc/<pid>/stat`` start time in clock ticks
199
+ since boot, which a process keeps for life and no two processes at one
200
+ pid share, so equality is the whole test and no clock domain is
201
+ involved. Elsewhere it is ``ps -o lstart``, a wall-clock time: a
202
+ recycled pid belongs to a process that started after the recorded claude
203
+ did, and only that direction disqualifies, and only a stranger. Some
204
+ ``ps`` builds derive every start time from a boot time that moves with
205
+ each wall-clock step (a WSL2 resume re-syncing the clock steps it by the
206
+ whole sleep), so a live session can read as younger than its own record;
207
+ a claude at the pid is kept either way, and a pid genuinely recycled by
208
+ another claude lingers only for that process's lifetime, which is what
209
+ happened before this check. Everything unknowable (Windows, whose stamp
210
+ is a FILETIME with no ``/proc`` to check it against, ``ps`` unavailable,
211
+ an unstamped or unparseable record) passes, because "cannot tell" must
212
+ never turn a live session into "nobody there".
213
+ """
214
+ if not proc_start:
215
+ return True
216
+ if proc_start.isdigit():
217
+ ticks = process_start_ticks(pid)
218
+ return ticks is None or ticks == proc_start
219
+ try:
220
+ recorded = _lstart_seconds(proc_start)
221
+ except ValueError:
222
+ return True
223
+ started = process_started_at(pid)
224
+ if started is None or started <= recorded + PID_REUSE_SLACK_S:
225
+ return True
226
+ return process_is_claude(pid) is not False
227
+
228
+
229
+ def scan_sessions(claude_dir: Path | None = None) -> tuple[list[ClaudeSession], int]:
230
+ """Live sessions, and how many records could NOT be read.
231
+
232
+ A record counts as live only when its pid is alive AND still belongs to
233
+ the claude that wrote it (see ``pid_matches_record``): a crashed claude
234
+ leaves its record behind, and the OS can hand the number to something
235
+ else.
236
+
237
+ Two kinds of caller read this directory and they need opposite things from
238
+ an unparseable record:
239
+
240
+ - A SCAN (a listing, a status display) wants it skipped. One bad file must
241
+ not take out the whole listing.
242
+ - A GUARD wants to know. ``0 live`` and ``0 readable`` are the same list,
243
+ and only the first is safe to act on -- the callers gate ``_bootstrap``
244
+ (which deletes a profile's Keychain entry and overwrites
245
+ ``.credentials.json``) and account removal, so reading "could not tell"
246
+ as "nobody there" runs them underneath a live instance.
247
+
248
+ So the count is returned rather than swallowed, and ``list_sessions``
249
+ below is the scan-shaped view that drops it.
250
+
251
+ ``iterdir``, NOT ``glob`` behind an ``is_dir`` check: both of those
252
+ suppress the ``OSError`` they hit, so a sessions directory that cannot be
253
+ listed -- or one whose stat fails because the profile root cannot be
254
+ traversed -- arrived at the GUARD as an empty directory rather than an
255
+ unknown one. Such a directory contributes exactly 1, which makes the count
256
+ a lower bound on the records at stake rather than a tally of them; every
257
+ caller only asks whether it is zero.
258
+
259
+ A MISSING directory is the one scan failure that still counts 0: a profile
260
+ that has never been run holds no records, and refusing on it would block
261
+ every guarded step against it permanently.
262
+ """
263
+ sessions_dir = (claude_dir or get_claude_dir()) / "sessions"
264
+ try:
265
+ # ``match`` keeps the platform casing the old ``glob`` had (a
266
+ # ``.JSON`` record still counts on Windows); ``endswith`` would not.
267
+ paths = [p for p in sessions_dir.iterdir() if p.match("*.json")]
268
+ except FileNotFoundError:
269
+ return [], 0
270
+ except OSError as exc:
271
+ logger.debug("Cannot list session directory %s: %s", sessions_dir, exc)
272
+ return [], 1
273
+
274
+ sessions = []
275
+ unreadable = 0
276
+ for path in paths:
277
+ try:
278
+ data = json.loads(path.read_text(encoding="utf-8"))
279
+ pid = data["pid"]
280
+ if not is_pid_alive(pid):
281
+ continue
282
+ if not pid_matches_record(pid, data.get("procStart")):
283
+ logger.debug(
284
+ "Skipping session file %s: pid %s was recycled", path, pid
285
+ )
286
+ continue
287
+ sessions.append(ClaudeSession(
288
+ pid=pid,
289
+ session_id=data.get("sessionId", ""),
290
+ cwd=data.get("cwd", ""),
291
+ started_at=data.get("startedAt", 0),
292
+ kind=data.get("kind", ""),
293
+ entrypoint=data.get("entrypoint", ""),
294
+ status=data.get("status"),
295
+ ))
296
+ except (
297
+ json.JSONDecodeError, # malformed JSON
298
+ KeyError, # required field missing
299
+ TypeError, # field has the wrong type (e.g. pid not an int)
300
+ AttributeError, # valid JSON that is not an object: a
301
+ # top-level array reaches `.get` as a list.
302
+ # Also how a too-deep nesting lands where
303
+ # the parser's recursion limit is high
304
+ # enough not to raise -- it differs per
305
+ # machine, so BOTH outcomes must be inert.
306
+ ValueError, # includes UnicodeDecodeError from read_text
307
+ OverflowError, # pid too large for os.kill's C long (is_pid_alive)
308
+ RecursionError, # pathologically nested JSON in json.loads
309
+ OSError,
310
+ ) as exc:
311
+ unreadable += 1
312
+ logger.debug("Skipping session file %s: %s", path, exc)
313
+ return sessions, unreadable
314
+
315
+
316
+ def list_sessions(claude_dir: Path | None = None) -> list[ClaudeSession]:
317
+ """Live sessions. A record that cannot be read is SKIPPED.
318
+
319
+ SCAN USE ONLY. The returned list cannot distinguish "no live sessions"
320
+ from "no readable records", so anything gating a destructive step must
321
+ call :func:`scan_sessions` and treat a non-zero count as live.
322
+ """
323
+ return scan_sessions(claude_dir)[0]
324
+
325
+
326
+ def list_ide_instances(claude_dir: Path | None = None) -> list[IdeInstance]:
327
+ """Read IDE lockfiles and return only those with alive processes."""
328
+ ide_dir = (claude_dir or get_claude_dir()) / "ide"
329
+ if not ide_dir.is_dir():
330
+ return []
331
+
332
+ instances = []
333
+ for path in ide_dir.glob("*.lock"):
334
+ try:
335
+ data = json.loads(path.read_text(encoding="utf-8"))
336
+ pid = data.get("pid")
337
+ if pid is None or not is_pid_alive(pid):
338
+ continue
339
+ port = int(path.stem)
340
+ instances.append(IdeInstance(
341
+ port=port,
342
+ pid=pid,
343
+ ide_name=data.get("ideName", "Unknown IDE"),
344
+ workspace_folders=data.get("workspaceFolders", []),
345
+ ))
346
+ except (
347
+ json.JSONDecodeError, # malformed JSON
348
+ KeyError, # required field missing
349
+ TypeError, # field has the wrong type (e.g. pid not an int)
350
+ AttributeError, # valid JSON that is not an object: a
351
+ # top-level array reaches `.get` as a list.
352
+ # Also how a too-deep nesting lands where
353
+ # the parser's recursion limit is high
354
+ # enough not to raise -- it differs per
355
+ # machine, so BOTH outcomes must be inert.
356
+ ValueError, # includes UnicodeDecodeError from read_text
357
+ OverflowError, # pid too large for os.kill's C long (is_pid_alive)
358
+ RecursionError, # pathologically nested JSON in json.loads
359
+ OSError,
360
+ ) as exc:
361
+ logger.debug("Skipping IDE lockfile %s: %s", path, exc)
362
+ return instances
363
+
364
+
365
+ def get_running_instances(
366
+ claude_dir: Path | None = None,
367
+ ) -> tuple[list[ClaudeSession], list[IdeInstance]]:
368
+ """Return all running Claude Code sessions and IDE instances."""
369
+ resolved = claude_dir or get_claude_dir()
370
+ return list_sessions(resolved), list_ide_instances(resolved)