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
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
"""Check PyPI for newer versions of claude-swap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tomllib
|
|
11
|
+
import urllib.request
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, NamedTuple
|
|
14
|
+
|
|
15
|
+
from claude_swap.cache import CACHE_DIR, MISSING, read_cache, write_cache
|
|
16
|
+
|
|
17
|
+
CACHE_PATH = CACHE_DIR / "update_check.json"
|
|
18
|
+
CACHE_TTL = 24 * 3600 # A successful lookup is kept for a day.
|
|
19
|
+
FAILURE_TTL = 3600 # A failed one is retried after an hour.
|
|
20
|
+
from claude_swap import DIST_NAME as PACKAGE
|
|
21
|
+
|
|
22
|
+
PYPI_URL = f"https://pypi.org/pypi/{PACKAGE}/json"
|
|
23
|
+
|
|
24
|
+
_VERSION_RE = re.compile(
|
|
25
|
+
r"(\d+(?:\.\d+)*)(?:[-_.]?(alpha|beta|preview|pre|rc|a|b|c)[-_.]?(\d+)?)?",
|
|
26
|
+
re.IGNORECASE,
|
|
27
|
+
)
|
|
28
|
+
_PRE_RANKS = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "preview": 2, "pre": 2, "rc": 2, "c": 2}
|
|
29
|
+
_FINAL_RANK = 3
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _Version(NamedTuple):
|
|
33
|
+
"""A version as a sort key. NamedTuple so that comparing two of these
|
|
34
|
+
compares the release first and only then the pre-release fields, which is
|
|
35
|
+
what puts 0.27.0b1 below 0.27.0 and both below 0.28.0."""
|
|
36
|
+
|
|
37
|
+
release: tuple[int, ...]
|
|
38
|
+
pre_rank: int # _FINAL_RANK when this is not a pre-release.
|
|
39
|
+
pre_number: int
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _parse_version(v: str) -> _Version:
|
|
43
|
+
"""Parse a release number with an optional PEP 440 pre-release suffix.
|
|
44
|
+
|
|
45
|
+
Every cycle of claude-swap ships as a pre-release first (0.27.0b1,
|
|
46
|
+
0.26.0b1, ...), and a plain int() over the dotted parts raised ValueError
|
|
47
|
+
on those, which check_for_update swallowed as "no update available".
|
|
48
|
+
Development and post releases are not modeled — the project publishes
|
|
49
|
+
none — so they collapse onto the release they belong to.
|
|
50
|
+
"""
|
|
51
|
+
m = _VERSION_RE.match(v)
|
|
52
|
+
if m is None:
|
|
53
|
+
raise ValueError(f"unrecognized version: {v!r}")
|
|
54
|
+
release = tuple(int(x) for x in m.group(1).split("."))
|
|
55
|
+
# PEP 440 makes 0.27 and 0.27.0 the same release, and the pre-release rank
|
|
56
|
+
# only means anything once the release segments line up.
|
|
57
|
+
while len(release) > 1 and release[-1] == 0:
|
|
58
|
+
release = release[:-1]
|
|
59
|
+
if m.group(2) is None:
|
|
60
|
+
return _Version(release, _FINAL_RANK, 0)
|
|
61
|
+
return _Version(release, _PRE_RANKS[m.group(2).lower()], int(m.group(3) or 0))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_newer(latest: str, current: str) -> bool:
|
|
65
|
+
"""Whether the latest release is an upgrade worth telling the user about."""
|
|
66
|
+
latest_version = _parse_version(latest)
|
|
67
|
+
current_version = _parse_version(current)
|
|
68
|
+
# Nobody on a final release asked to be moved onto a pre-release, so we
|
|
69
|
+
# stay quiet for them; people already running one still hear about later
|
|
70
|
+
# pre-releases.
|
|
71
|
+
if latest_version.pre_rank != _FINAL_RANK and current_version.pre_rank == _FINAL_RANK:
|
|
72
|
+
return False
|
|
73
|
+
return latest_version > current_version
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _detect_install_method() -> str | None:
|
|
77
|
+
"""Return 'uv', 'pipx', or None if we can't tell."""
|
|
78
|
+
prefix = Path(sys.prefix)
|
|
79
|
+
parts = tuple(p.lower() for p in prefix.parts)
|
|
80
|
+
pairs = list(zip(parts, parts[1:]))
|
|
81
|
+
|
|
82
|
+
if ("uv", "tools") in pairs:
|
|
83
|
+
return "uv"
|
|
84
|
+
if ("pipx", "venvs") in pairs:
|
|
85
|
+
return "pipx"
|
|
86
|
+
|
|
87
|
+
# Env-var override: only trust if sys.prefix is actually under it.
|
|
88
|
+
for env_var, name in (("UV_TOOL_DIR", "uv"), ("PIPX_HOME", "pipx")):
|
|
89
|
+
root = os.environ.get(env_var)
|
|
90
|
+
if root:
|
|
91
|
+
try:
|
|
92
|
+
if prefix.is_relative_to(Path(root)):
|
|
93
|
+
return name
|
|
94
|
+
except (ValueError, OSError):
|
|
95
|
+
pass
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class _Cooldown(NamedTuple):
|
|
100
|
+
"""An exclude-newer setting as uv spells it, and where the user set it."""
|
|
101
|
+
|
|
102
|
+
value: str # "P14D", "14 days", "2026-10-11T00:36:21Z"
|
|
103
|
+
source: str # 'uv-receipt.toml: exclude-newer-span = "P14D"'
|
|
104
|
+
from_env: bool # Set through UV_EXCLUDE_NEWER rather than the receipt.
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _read_receipt() -> dict[str, Any]:
|
|
108
|
+
"""The ``[tool]`` table of this install's uv tool receipt, or ``{}``."""
|
|
109
|
+
try:
|
|
110
|
+
with (Path(sys.prefix) / "uv-receipt.toml").open("rb") as fh:
|
|
111
|
+
tool = tomllib.load(fh).get("tool", {})
|
|
112
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
113
|
+
return {}
|
|
114
|
+
return tool if isinstance(tool, dict) else {}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _uv_cooldown(receipt: dict[str, Any]) -> _Cooldown | None:
|
|
118
|
+
"""The release cooldown ``uv tool upgrade`` applies to this install.
|
|
119
|
+
|
|
120
|
+
uv records ``--exclude-newer`` in the tool receipt and reapplies it on
|
|
121
|
+
every upgrade. A relative setting ("14 days") is stored as
|
|
122
|
+
``exclude-newer-span`` next to the absolute cutoff of install time, and
|
|
123
|
+
the span is what uv recomputes from. ``UV_EXCLUDE_NEWER`` in the
|
|
124
|
+
environment overrides the receipt, as it does for uv itself.
|
|
125
|
+
"""
|
|
126
|
+
env_value = os.environ.get("UV_EXCLUDE_NEWER", "").strip()
|
|
127
|
+
if env_value:
|
|
128
|
+
return _Cooldown(env_value, f"UV_EXCLUDE_NEWER={env_value}", from_env=True)
|
|
129
|
+
options = receipt.get("options", {})
|
|
130
|
+
if not isinstance(options, dict):
|
|
131
|
+
return None
|
|
132
|
+
for key in ("exclude-newer-span", "exclude-newer"):
|
|
133
|
+
value = options.get(key)
|
|
134
|
+
if isinstance(value, str):
|
|
135
|
+
return _Cooldown(value, f'uv-receipt.toml: {key} = "{value}"', from_env=False)
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# A receipt value is pasted into a shell line unquoted, so only an ISO
|
|
140
|
+
# duration ("P14D") or an RFC 3339 timestamp may pass.
|
|
141
|
+
_CUTOFF_RE = re.compile(r"^[A-Za-z0-9.:+-]+$")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _uv_latest_version(current_version: str, cooldown: _Cooldown | None) -> str | None:
|
|
145
|
+
"""The newest claude-swap release uv would install into this environment.
|
|
146
|
+
|
|
147
|
+
``uv pip list --outdated`` resolves against the index the way ``uv tool
|
|
148
|
+
upgrade`` does once it is handed the same exclude-newer setting, so the
|
|
149
|
+
version it reports is one uv can actually install. Returns the current
|
|
150
|
+
version when nothing newer is visible and None when uv fails. A uv that
|
|
151
|
+
is not on PATH raises FileNotFoundError, since the caller treats that
|
|
152
|
+
differently from a failed resolve. The environment variable is dropped so that the cooldown passed
|
|
153
|
+
here is the only one uv sees, and the command runs from the tool's own
|
|
154
|
+
directory because uv reads the ``uv.toml`` or ``pyproject.toml`` of
|
|
155
|
+
whatever project the shell happens to be in. ``uv tool upgrade`` does
|
|
156
|
+
not, so a project's own cutoff must not hide releases from this check.
|
|
157
|
+
"""
|
|
158
|
+
cmd = ["uv", "pip", "list", "--outdated", "--format", "json", "--python", sys.executable]
|
|
159
|
+
if cooldown is not None:
|
|
160
|
+
cmd += ["--exclude-newer", cooldown.value]
|
|
161
|
+
env = {k: v for k, v in os.environ.items() if k != "UV_EXCLUDE_NEWER"}
|
|
162
|
+
try:
|
|
163
|
+
result = subprocess.run(
|
|
164
|
+
cmd,
|
|
165
|
+
capture_output=True,
|
|
166
|
+
text=True,
|
|
167
|
+
timeout=10,
|
|
168
|
+
env=env,
|
|
169
|
+
check=True,
|
|
170
|
+
cwd=sys.prefix,
|
|
171
|
+
)
|
|
172
|
+
rows = json.loads(result.stdout)
|
|
173
|
+
except FileNotFoundError:
|
|
174
|
+
raise
|
|
175
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
176
|
+
return None
|
|
177
|
+
for row in rows:
|
|
178
|
+
if row.get("name") == PACKAGE:
|
|
179
|
+
latest = row.get("latest_version")
|
|
180
|
+
return latest if isinstance(latest, str) else None
|
|
181
|
+
return current_version
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _pypi_latest_version() -> str | None:
|
|
185
|
+
"""PyPI's latest release, for installs that uv does not manage."""
|
|
186
|
+
try:
|
|
187
|
+
req = urllib.request.Request(PYPI_URL)
|
|
188
|
+
with urllib.request.urlopen(req, timeout=2) as resp:
|
|
189
|
+
data = json.loads(resp.read().decode())
|
|
190
|
+
return data["info"]["version"]
|
|
191
|
+
except Exception:
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class _Lookup(NamedTuple):
|
|
196
|
+
"""A version lookup and whether its answer is worth writing to the cache."""
|
|
197
|
+
|
|
198
|
+
latest: str | None
|
|
199
|
+
cache: bool
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _latest_version(current_version: str, method: str | None) -> _Lookup:
|
|
203
|
+
"""The newest release the user's package manager will actually install.
|
|
204
|
+
|
|
205
|
+
uv is often off PATH when cswap runs under cron or launchd. Without a
|
|
206
|
+
cooldown PyPI answers the same question, so it takes over. With one,
|
|
207
|
+
PyPI would advertise releases the cooldown hides, so the run stays quiet
|
|
208
|
+
and leaves the cache alone: the interactive run that follows has uv and
|
|
209
|
+
retries at once. Any other uv failure (a timeout, a failed resolve) is
|
|
210
|
+
cached like a PyPI failure, so a dead network costs one attempt per
|
|
211
|
+
FAILURE_TTL rather than one per command.
|
|
212
|
+
"""
|
|
213
|
+
if method != "uv":
|
|
214
|
+
return _Lookup(_pypi_latest_version(), cache=True)
|
|
215
|
+
cooldown = _uv_cooldown(_read_receipt())
|
|
216
|
+
uv_missing = False
|
|
217
|
+
try:
|
|
218
|
+
latest = _uv_latest_version(current_version, cooldown)
|
|
219
|
+
except FileNotFoundError:
|
|
220
|
+
latest = None
|
|
221
|
+
uv_missing = True
|
|
222
|
+
if latest is not None:
|
|
223
|
+
return _Lookup(latest, cache=True)
|
|
224
|
+
if cooldown is None:
|
|
225
|
+
return _Lookup(_pypi_latest_version(), cache=True)
|
|
226
|
+
return _Lookup(None, cache=not uv_missing)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def held_back_release_notice(current_version: str) -> str | None:
|
|
230
|
+
"""Explain a release that uv's cooldown keeps ``uv tool upgrade`` from seeing.
|
|
231
|
+
|
|
232
|
+
uv prints "Nothing to upgrade" whether the install is current or the
|
|
233
|
+
newest release is simply younger than the cooldown, and the user cannot
|
|
234
|
+
tell the two apart. When a cooldown is set, this asks uv what it would
|
|
235
|
+
install without one and names the setting that is in the way.
|
|
236
|
+
|
|
237
|
+
The remedy is ``uv tool upgrade`` itself with a zero cooldown, which
|
|
238
|
+
takes the release and leaves the receipt's extras, ``--with`` packages,
|
|
239
|
+
Python version and index options alone. uv stores the zero as
|
|
240
|
+
``exclude-newer-span = "PT0S"``, so a second line restores the receipt's
|
|
241
|
+
own value. The flag also wins over ``UV_EXCLUDE_NEWER`` for that one
|
|
242
|
+
run, and since the variable keeps applying afterwards there is nothing
|
|
243
|
+
to restore in that case.
|
|
244
|
+
"""
|
|
245
|
+
cooldown = _uv_cooldown(_read_receipt())
|
|
246
|
+
if cooldown is None:
|
|
247
|
+
return None
|
|
248
|
+
try:
|
|
249
|
+
latest = _uv_latest_version(current_version, None)
|
|
250
|
+
if latest is None or not _is_newer(latest, current_version):
|
|
251
|
+
return None
|
|
252
|
+
except (FileNotFoundError, ValueError):
|
|
253
|
+
return None
|
|
254
|
+
take_now = f'uv tool upgrade {PACKAGE} --exclude-newer "0 days"'
|
|
255
|
+
lines = [
|
|
256
|
+
f"{PACKAGE} {latest} is on PyPI, but this install has a release cooldown",
|
|
257
|
+
f" ({cooldown.source}) that hides it from uv tool upgrade.",
|
|
258
|
+
]
|
|
259
|
+
if cooldown.from_env:
|
|
260
|
+
lines.append(f" To take it now (the flag overrides UV_EXCLUDE_NEWER): {take_now}")
|
|
261
|
+
else:
|
|
262
|
+
lines.append(f" To take it now: {take_now}")
|
|
263
|
+
if _CUTOFF_RE.match(cooldown.value):
|
|
264
|
+
lines.append(
|
|
265
|
+
" To restore the cooldown: "
|
|
266
|
+
f"uv tool upgrade {PACKAGE} --exclude-newer {cooldown.value}"
|
|
267
|
+
)
|
|
268
|
+
return "\n".join(lines)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def check_for_update(current_version: str) -> str | None:
|
|
272
|
+
"""Return a notification string if a newer version exists, else None."""
|
|
273
|
+
try:
|
|
274
|
+
method = _detect_install_method()
|
|
275
|
+
cached_data = read_cache(CACHE_PATH, CACHE_TTL)
|
|
276
|
+
if cached_data is None:
|
|
277
|
+
# A cached failure. Keep it for an hour, not a day.
|
|
278
|
+
cached_data = read_cache(CACHE_PATH, FAILURE_TTL)
|
|
279
|
+
if cached_data is not MISSING and isinstance(cached_data, str | None):
|
|
280
|
+
latest_version = cached_data
|
|
281
|
+
else:
|
|
282
|
+
lookup = _latest_version(current_version, method)
|
|
283
|
+
latest_version = lookup.latest
|
|
284
|
+
# A failure is cached as None and expires after FAILURE_TTL.
|
|
285
|
+
# The one exception is uv missing under a cooldown, see
|
|
286
|
+
# _latest_version.
|
|
287
|
+
if lookup.cache:
|
|
288
|
+
write_cache(CACHE_PATH, latest_version)
|
|
289
|
+
|
|
290
|
+
if latest_version and _is_newer(latest_version, current_version):
|
|
291
|
+
direct = {
|
|
292
|
+
"uv": f"uv tool upgrade {PACKAGE}",
|
|
293
|
+
"pipx": f"pipx upgrade {PACKAGE}",
|
|
294
|
+
}.get(method or "")
|
|
295
|
+
if direct and sys.platform != "win32":
|
|
296
|
+
# cswap upgrade actually performs the upgrade here.
|
|
297
|
+
hint = "Run `cswap upgrade` to update."
|
|
298
|
+
elif direct:
|
|
299
|
+
# Windows: cswap upgrade only prints, so point at the real command.
|
|
300
|
+
hint = f"Run `{direct}` to update."
|
|
301
|
+
else:
|
|
302
|
+
# Unknown install method: cswap upgrade shows manual instructions.
|
|
303
|
+
hint = "Run `cswap upgrade` for upgrade instructions."
|
|
304
|
+
return (
|
|
305
|
+
f"A newer version of {PACKAGE} is available ({latest_version}). "
|
|
306
|
+
f"You are using {current_version}. {hint}"
|
|
307
|
+
)
|
|
308
|
+
return None
|
|
309
|
+
except Exception:
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _installed_version_on_disk() -> str | None:
|
|
314
|
+
"""The version claude-swap actually has on disk after an upgrade.
|
|
315
|
+
|
|
316
|
+
importlib.metadata resolves the running environment, so it still reports
|
|
317
|
+
the pre-upgrade version from inside this process. A fresh interpreter
|
|
318
|
+
started from sys.executable reads the tool directory uv/pipx rewrote,
|
|
319
|
+
giving an honest after-version for both install methods without parsing
|
|
320
|
+
`uv tool list` / `pipx list` output. Best effort: any failure or timeout
|
|
321
|
+
returns None so a verification hiccup never masks the upgrade's own exit
|
|
322
|
+
status.
|
|
323
|
+
"""
|
|
324
|
+
code = (
|
|
325
|
+
"import importlib.metadata as m\n"
|
|
326
|
+
f"print(m.version('{PACKAGE}'))"
|
|
327
|
+
)
|
|
328
|
+
try:
|
|
329
|
+
result = subprocess.run(
|
|
330
|
+
[sys.executable, "-c", code],
|
|
331
|
+
capture_output=True,
|
|
332
|
+
text=True,
|
|
333
|
+
timeout=10,
|
|
334
|
+
check=True,
|
|
335
|
+
)
|
|
336
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
337
|
+
return None
|
|
338
|
+
version = result.stdout.strip()
|
|
339
|
+
return version or None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def install_identity() -> dict:
|
|
343
|
+
"""``{"version", "source"}`` of the claude-swap this process runs.
|
|
344
|
+
|
|
345
|
+
``source`` is the VCS commit for a git install (importlib.metadata's
|
|
346
|
+
``direct_url.json``), else None. Two builds can share a version string and
|
|
347
|
+
differ only here — anyone installed from a branch, for instance — so a
|
|
348
|
+
"did the build change?" question compares both.
|
|
349
|
+
"""
|
|
350
|
+
from importlib import metadata
|
|
351
|
+
|
|
352
|
+
from claude_swap import __version__
|
|
353
|
+
|
|
354
|
+
source = None
|
|
355
|
+
try:
|
|
356
|
+
raw = metadata.distribution(PACKAGE).read_text("direct_url.json")
|
|
357
|
+
if raw:
|
|
358
|
+
source = (json.loads(raw).get("vcs_info") or {}).get("commit_id") or None
|
|
359
|
+
except (OSError, ImportError, ValueError, AttributeError, TypeError):
|
|
360
|
+
source = None # no metadata, or not the shape pip/uv write: not a git install
|
|
361
|
+
return {"version": __version__, "source": source}
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def describe_identity(identity: dict | None) -> str:
|
|
365
|
+
"""``1.0.0 (3fec656)`` for a git install, ``1.0.0`` otherwise."""
|
|
366
|
+
if not identity:
|
|
367
|
+
return "unknown"
|
|
368
|
+
source = identity.get("source")
|
|
369
|
+
version = str(identity.get("version") or "unknown")
|
|
370
|
+
return f"{version} ({str(source)[:7]})" if source else version
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _installed_identity_on_disk() -> dict | None:
|
|
374
|
+
""":func:`install_identity` as a fresh interpreter sees it after an upgrade.
|
|
375
|
+
|
|
376
|
+
Same reasoning as :func:`_installed_version_on_disk`: this process still
|
|
377
|
+
reports the pre-upgrade build. Best effort, None on any failure.
|
|
378
|
+
"""
|
|
379
|
+
code = (
|
|
380
|
+
"import json\n"
|
|
381
|
+
"from claude_swap.update_check import install_identity\n"
|
|
382
|
+
"print(json.dumps(install_identity()))"
|
|
383
|
+
)
|
|
384
|
+
try:
|
|
385
|
+
result = subprocess.run(
|
|
386
|
+
[sys.executable, "-c", code],
|
|
387
|
+
capture_output=True,
|
|
388
|
+
text=True,
|
|
389
|
+
timeout=10,
|
|
390
|
+
check=True,
|
|
391
|
+
)
|
|
392
|
+
identity = json.loads(result.stdout)
|
|
393
|
+
except (OSError, subprocess.SubprocessError, ValueError, TypeError):
|
|
394
|
+
return None
|
|
395
|
+
return identity if isinstance(identity, dict) else None
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _restart_menubar_if_rebuilt(before: dict) -> None:
|
|
399
|
+
"""Restart a RUNNING menu bar service when the upgrade changed the build.
|
|
400
|
+
|
|
401
|
+
launchd keeps the old process until something restarts it; until now the
|
|
402
|
+
README asked for a manual kickstart. Only a running service is touched — a
|
|
403
|
+
quit one stays quit, which is the user's choice to keep. "Changed" compares
|
|
404
|
+
version and commit, so a git install that keeps its version string counts.
|
|
405
|
+
Other upgrade routes (``uv tool upgrade`` by hand) are covered by the next
|
|
406
|
+
plain ``cswap menubar``, which compares the worker's build stamp.
|
|
407
|
+
"""
|
|
408
|
+
from claude_swap.printer import warning
|
|
409
|
+
|
|
410
|
+
after = _installed_identity_on_disk()
|
|
411
|
+
if after is None or after == before:
|
|
412
|
+
return
|
|
413
|
+
from claude_swap import launch_agent
|
|
414
|
+
from claude_swap.exceptions import ClaudeSwitchError
|
|
415
|
+
|
|
416
|
+
try:
|
|
417
|
+
pid = launch_agent.service_pid()
|
|
418
|
+
if pid is None:
|
|
419
|
+
return
|
|
420
|
+
launch_agent.kickstart(restart=True)
|
|
421
|
+
except (ClaudeSwitchError, OSError) as exc:
|
|
422
|
+
# The upgrade itself succeeded; only the restart did not.
|
|
423
|
+
warning(f"Menu bar not restarted onto the new build: {exc}")
|
|
424
|
+
return
|
|
425
|
+
print(f"Menu bar restarted onto {describe_identity(after)} (was pid {pid}).")
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def run_self_upgrade(current_version: str | None = None) -> int:
|
|
429
|
+
"""Run the appropriate upgrade command for the current install method.
|
|
430
|
+
|
|
431
|
+
Returns the subprocess exit code, or 1 if detection failed or the package
|
|
432
|
+
manager is missing from PATH. After a successful run it verifies what
|
|
433
|
+
actually landed on disk and reports the before -> after, since a package
|
|
434
|
+
manager can exit 0 without changing anything (uv's "Nothing to upgrade",
|
|
435
|
+
#491). A uv install with a release cooldown also gets told about a release
|
|
436
|
+
the cooldown hides, since uv itself only reports "Nothing to upgrade".
|
|
437
|
+
"""
|
|
438
|
+
from claude_swap.printer import accent, error, warning
|
|
439
|
+
|
|
440
|
+
if current_version is None:
|
|
441
|
+
from claude_swap import __version__
|
|
442
|
+
|
|
443
|
+
current_version = __version__
|
|
444
|
+
before = current_version
|
|
445
|
+
before_identity = install_identity()
|
|
446
|
+
|
|
447
|
+
method = _detect_install_method()
|
|
448
|
+
commands = {
|
|
449
|
+
"uv": ["uv", "tool", "upgrade", PACKAGE],
|
|
450
|
+
"pipx": ["pipx", "upgrade", PACKAGE],
|
|
451
|
+
}
|
|
452
|
+
cmd = commands.get(method or "")
|
|
453
|
+
if cmd is None:
|
|
454
|
+
error(
|
|
455
|
+
"Could not detect install method (looked for uv tool / pipx).\n"
|
|
456
|
+
f" sys.prefix: {sys.prefix}\n"
|
|
457
|
+
f" sys.executable: {sys.executable}\n"
|
|
458
|
+
"To upgrade manually, run one of:\n"
|
|
459
|
+
f" uv tool upgrade {PACKAGE}\n"
|
|
460
|
+
f" pipx upgrade {PACKAGE}\n"
|
|
461
|
+
f" {sys.executable} -m pip install --upgrade {PACKAGE}\n"
|
|
462
|
+
"If you installed with `pip install -e .`, use `git pull` instead."
|
|
463
|
+
)
|
|
464
|
+
return 1
|
|
465
|
+
|
|
466
|
+
# Windows: the running cswap.exe launcher is locked, so an in-process
|
|
467
|
+
# uv/pipx upgrade fails when it tries to replace the executable even
|
|
468
|
+
# though the package itself updates. cswap exits right after this, which
|
|
469
|
+
# releases the lock, so the user can just run the command themselves.
|
|
470
|
+
if sys.platform == "win32":
|
|
471
|
+
print(f"To upgrade {PACKAGE} on Windows, run:\n {accent(' '.join(cmd))}")
|
|
472
|
+
if method == "uv":
|
|
473
|
+
notice = held_back_release_notice(current_version)
|
|
474
|
+
if notice:
|
|
475
|
+
warning(notice)
|
|
476
|
+
return 1
|
|
477
|
+
|
|
478
|
+
try:
|
|
479
|
+
result = subprocess.run(cmd, check=False)
|
|
480
|
+
except FileNotFoundError:
|
|
481
|
+
error(
|
|
482
|
+
f"Detected {method} install but `{cmd[0]}` is not on PATH. "
|
|
483
|
+
"Run the upgrade manually from a shell where it is available."
|
|
484
|
+
)
|
|
485
|
+
return 1
|
|
486
|
+
|
|
487
|
+
if result.returncode != 0:
|
|
488
|
+
return result.returncode
|
|
489
|
+
|
|
490
|
+
# The package manager can exit 0 without changing anything, so verify
|
|
491
|
+
# what landed on disk and say so rather than trusting its wording (#491).
|
|
492
|
+
# importlib.metadata in a fresh interpreter reads the directory uv/pipx
|
|
493
|
+
# rewrote, so the report is honest for both install methods. Verification
|
|
494
|
+
# is best effort: a failure or timeout returns None and we stay silent,
|
|
495
|
+
# never masking the upgrade's own exit status.
|
|
496
|
+
after = _installed_version_on_disk()
|
|
497
|
+
if before and after and after != before:
|
|
498
|
+
print(accent(f"{PACKAGE} upgraded: {before} -> {after}"))
|
|
499
|
+
elif before and after:
|
|
500
|
+
print(f"{PACKAGE} is still at {after}.")
|
|
501
|
+
|
|
502
|
+
if sys.platform == "darwin":
|
|
503
|
+
_restart_menubar_if_rebuilt(before_identity)
|
|
504
|
+
|
|
505
|
+
if method == "uv":
|
|
506
|
+
notice = held_back_release_notice(current_version)
|
|
507
|
+
if notice:
|
|
508
|
+
warning(notice)
|
|
509
|
+
return result.returncode
|