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/cache.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Simple file-based cache utilities for claude-swap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from claude_swap.paths import get_backup_root
|
|
10
|
+
|
|
11
|
+
CACHE_DIR = get_backup_root() / "cache"
|
|
12
|
+
|
|
13
|
+
MISSING = object()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_cache(path: Path, ttl: float, default=MISSING):
|
|
17
|
+
"""Read cached JSON data if the file exists and is within TTL.
|
|
18
|
+
|
|
19
|
+
Returns the stored 'data' value, or *default* if missing/expired/invalid.
|
|
20
|
+
When *default* is not provided, returns the ``MISSING`` sentinel so
|
|
21
|
+
callers can distinguish "no cache" from a cached ``None`` value.
|
|
22
|
+
"""
|
|
23
|
+
try:
|
|
24
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
25
|
+
if time.time() - raw["timestamp"] < ttl:
|
|
26
|
+
return raw["data"]
|
|
27
|
+
except (
|
|
28
|
+
OSError,
|
|
29
|
+
json.JSONDecodeError,
|
|
30
|
+
UnicodeDecodeError,
|
|
31
|
+
KeyError,
|
|
32
|
+
TypeError,
|
|
33
|
+
):
|
|
34
|
+
pass
|
|
35
|
+
return default
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def write_cache(path: Path, data) -> None:
|
|
39
|
+
"""Write data to a cache file with a timestamp."""
|
|
40
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
path.write_text(
|
|
42
|
+
json.dumps({"timestamp": time.time(), "data": data}),
|
|
43
|
+
encoding="utf-8",
|
|
44
|
+
)
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Cooperate with Claude Code's own advisory locks while mutating its files.
|
|
2
|
+
|
|
3
|
+
Claude Code guards its OAuth token refresh with the npm ``proper-lockfile``
|
|
4
|
+
package, and its ``~/.claude.json`` writes with the same mechanism on the
|
|
5
|
+
config file. The protocol (verified against the 2.1.218 bundle):
|
|
6
|
+
|
|
7
|
+
- The lock artifact is a **directory**; ``mkdir`` atomicity is the mutex.
|
|
8
|
+
- The refresh path takes **two** locks, in order: the primary
|
|
9
|
+
``<config-home>/.oauth_refresh.lock``, then the legacy
|
|
10
|
+
``<config-home>.lock`` (``~/.claude.lock``) kept for compatibility with
|
|
11
|
+
external tools. Both run ``stale: 60000, update: 5000`` — a credential
|
|
12
|
+
lock is stale only past **60s**, and live holders touch every 5s. On a
|
|
13
|
+
contended legacy lock Claude Code releases the primary and retries.
|
|
14
|
+
- The config lock (``~/.claude.json.lock``) keeps the older defaults:
|
|
15
|
+
stale after 10s, touched every 5s.
|
|
16
|
+
- Claude Code retries a held credentials lock 5 times with 1-2s jittered
|
|
17
|
+
sleeps before giving up, so briefly holding it is fully cooperative.
|
|
18
|
+
|
|
19
|
+
Holding these locks while swapping credentials closes the one real race with a
|
|
20
|
+
running Claude Code: its refresh reads credentials, refreshes over the network,
|
|
21
|
+
and saves — all under both credential locks — so a swap landing inside that
|
|
22
|
+
window would be overwritten by the refreshed old-account token (and the
|
|
23
|
+
just-taken backup would keep a pre-rotation refresh token). Under the lock,
|
|
24
|
+
Claude Code's own double-checked re-read sees the swapped (non-expired)
|
|
25
|
+
credential and aborts the refresh instead.
|
|
26
|
+
|
|
27
|
+
References (claude-code 2.1.218 bundle): the ``uKi`` lock-options helper
|
|
28
|
+
(``lockfilePath: join(dir, ".oauth_refresh.lock"), stale: 60000, update:
|
|
29
|
+
5000``) and ``CKi`` (dual acquisition, legacy released-on-contention with
|
|
30
|
+
``tengu_oauth_refresh_legacy_lock_contended`` telemetry).
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import logging
|
|
36
|
+
import os
|
|
37
|
+
import random
|
|
38
|
+
import threading
|
|
39
|
+
import time
|
|
40
|
+
from contextlib import contextmanager
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
from claude_swap.exceptions import ClaudeCodeLockTimeout
|
|
44
|
+
from claude_swap.paths import get_claude_config_home, get_global_config_path
|
|
45
|
+
|
|
46
|
+
# Claude Code's credential-refresh locks run ``stale: 60000, update: 5000``
|
|
47
|
+
# (2.1.218 ``uKi``): a lock younger than 60s belongs to a live holder and
|
|
48
|
+
# must never be stolen — the holder's toucher may stall well past 10s
|
|
49
|
+
# (suspend, blocked event loop) while it still legitimately owns the lock.
|
|
50
|
+
CREDENTIALS_STALENESS_S = 60.0
|
|
51
|
+
# The config lock (~/.claude.json.lock) keeps the older proper-lockfile
|
|
52
|
+
# defaults: stale after 10s, touched every 5s.
|
|
53
|
+
CONFIG_STALENESS_S = 10.0
|
|
54
|
+
# We touch a little faster than CC's 5s for margin.
|
|
55
|
+
TOUCH_INTERVAL_S = 3.0
|
|
56
|
+
# Claude Code holds the credentials lock for one token-endpoint round trip
|
|
57
|
+
# (sub-second to a few seconds); its config lock for a local RMW. 9s of
|
|
58
|
+
# bounded waiting comfortably outlasts both without stalling the CLI forever.
|
|
59
|
+
# Note this is a PER-LOCK budget: claude_credentials_lock acquires two locks
|
|
60
|
+
# sequentially, so its worst case is ~2x this value.
|
|
61
|
+
DEFAULT_TIMEOUT_S = 9.0
|
|
62
|
+
# A short back-off after an arm declines, so the retry loop cannot spin hot.
|
|
63
|
+
_DECLINE_BACKOFF_S = 0.05
|
|
64
|
+
# A stale-lock takeover is a stat followed by an rmdir, and two waiters that
|
|
65
|
+
# both saw the same dead holder could each run it: the second rmdir then hit
|
|
66
|
+
# the first waiter's fresh lock (#420). Takeovers are serialized through this
|
|
67
|
+
# sibling directory and re-check staleness inside it. Claude Code never looks
|
|
68
|
+
# at it, so the lock protocol itself is unchanged.
|
|
69
|
+
TAKEOVER_SUFFIX = ".takeover"
|
|
70
|
+
# The takeover directory is held for one stat + rmdir; older than this, its
|
|
71
|
+
# holder died mid-takeover.
|
|
72
|
+
TAKEOVER_STALENESS_S = 5.0
|
|
73
|
+
|
|
74
|
+
_logger = logging.getLogger("claude-swap")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def credentials_lock_dir() -> Path:
|
|
78
|
+
"""Legacy credential lock (``~/.claude.lock``) — CC still takes it for
|
|
79
|
+
compatibility; external exclusion today rests on this one."""
|
|
80
|
+
home = get_claude_config_home()
|
|
81
|
+
return home.parent / (home.name + ".lock")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def oauth_refresh_lock_dir() -> Path:
|
|
85
|
+
"""Claude Code's primary OAuth refresh lock
|
|
86
|
+
(``<config-home>/.oauth_refresh.lock``, 2.1.218+)."""
|
|
87
|
+
return get_claude_config_home() / ".oauth_refresh.lock"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def config_lock_dir() -> Path:
|
|
91
|
+
"""Lock directory guarding the global config file (``~/.claude.json.lock``)."""
|
|
92
|
+
path = get_global_config_path()
|
|
93
|
+
return path.parent / (path.name + ".lock")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _nap(want: float, start: float, timeout: float) -> None:
|
|
97
|
+
"""Sleep at most what is LEFT of the budget, never a full jitter draw.
|
|
98
|
+
|
|
99
|
+
The deadline is checked at the top of the loop, so a sleep longer than the
|
|
100
|
+
remainder would run to completion first and the raise would land late.
|
|
101
|
+
Clamping to the remainder rather than to `timeout` keeps that true on the
|
|
102
|
+
SECOND retry too -- `min(want, timeout)` is a no-op once most of the
|
|
103
|
+
budget is already spent.
|
|
104
|
+
|
|
105
|
+
Never negative: an expired budget sleeps zero and the caller's next
|
|
106
|
+
deadline check raises, which is the same instant either way.
|
|
107
|
+
"""
|
|
108
|
+
left = timeout - (time.monotonic() - start)
|
|
109
|
+
if left > 0:
|
|
110
|
+
time.sleep(min(want, left))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _remove_if_still_stale(lock_dir: Path, staleness: float) -> bool:
|
|
114
|
+
"""Remove ``lock_dir`` if it is still stale, under the takeover directory.
|
|
115
|
+
|
|
116
|
+
Returns True if this call removed it. False means another waiter is mid-
|
|
117
|
+
takeover, the lock was already gone or retaken, or it can't be removed.
|
|
118
|
+
"""
|
|
119
|
+
takeover = lock_dir.with_name(lock_dir.name + TAKEOVER_SUFFIX)
|
|
120
|
+
try:
|
|
121
|
+
os.mkdir(takeover)
|
|
122
|
+
except FileExistsError:
|
|
123
|
+
try:
|
|
124
|
+
if time.time() - os.lstat(takeover).st_mtime > TAKEOVER_STALENESS_S:
|
|
125
|
+
try:
|
|
126
|
+
os.rmdir(takeover) # its holder died mid-takeover
|
|
127
|
+
except NotADirectoryError:
|
|
128
|
+
os.unlink(takeover) # a file or symlink; not ours to keep
|
|
129
|
+
except OSError:
|
|
130
|
+
pass
|
|
131
|
+
return False
|
|
132
|
+
except OSError:
|
|
133
|
+
return False
|
|
134
|
+
try:
|
|
135
|
+
# Re-check inside: the waiter before us may already have removed the
|
|
136
|
+
# dead lock and taken a fresh one at the same path.
|
|
137
|
+
if time.time() - os.stat(lock_dir).st_mtime <= staleness:
|
|
138
|
+
return False
|
|
139
|
+
os.rmdir(lock_dir)
|
|
140
|
+
return True
|
|
141
|
+
except OSError:
|
|
142
|
+
return False
|
|
143
|
+
finally:
|
|
144
|
+
try:
|
|
145
|
+
os.rmdir(takeover)
|
|
146
|
+
except OSError:
|
|
147
|
+
pass
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@contextmanager
|
|
151
|
+
def proper_lockfile(
|
|
152
|
+
lock_dir: Path,
|
|
153
|
+
*,
|
|
154
|
+
timeout: float | None = None,
|
|
155
|
+
staleness: float = CONFIG_STALENESS_S,
|
|
156
|
+
):
|
|
157
|
+
"""Acquire a proper-lockfile-compatible directory lock.
|
|
158
|
+
|
|
159
|
+
Blocks up to ``timeout`` seconds (default ``DEFAULT_TIMEOUT_S``, resolved
|
|
160
|
+
at call time so tests can shorten it), taking over locks whose mtime is
|
|
161
|
+
older than ``staleness``, touches the directory mtime while held so other
|
|
162
|
+
holders don't deem us stale, and removes it on exit.
|
|
163
|
+
|
|
164
|
+
Raises:
|
|
165
|
+
ClaudeCodeLockTimeout: The lock stayed held past ``timeout``.
|
|
166
|
+
"""
|
|
167
|
+
if timeout is None:
|
|
168
|
+
timeout = DEFAULT_TIMEOUT_S
|
|
169
|
+
lock_dir.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
start = time.monotonic()
|
|
171
|
+
while True:
|
|
172
|
+
try:
|
|
173
|
+
os.mkdir(lock_dir)
|
|
174
|
+
break
|
|
175
|
+
except FileExistsError:
|
|
176
|
+
pass
|
|
177
|
+
if time.monotonic() - start > timeout:
|
|
178
|
+
raise ClaudeCodeLockTimeout(
|
|
179
|
+
f"Could not acquire {lock_dir.name} — Claude Code appears "
|
|
180
|
+
"to be refreshing credentials. Retry in a few seconds."
|
|
181
|
+
)
|
|
182
|
+
try:
|
|
183
|
+
held_mtime = os.stat(lock_dir).st_mtime
|
|
184
|
+
except FileNotFoundError:
|
|
185
|
+
# BACK OFF HERE TOO. A dangling symlink at the lock path answers
|
|
186
|
+
# FileExistsError to mkdir and FileNotFoundError to stat, so this
|
|
187
|
+
# arm can repeat for the whole budget.
|
|
188
|
+
_nap(_DECLINE_BACKOFF_S, start, timeout)
|
|
189
|
+
continue
|
|
190
|
+
if time.time() - held_mtime > staleness:
|
|
191
|
+
# Dead holder per the protocol: remove and retake. Declining --
|
|
192
|
+
# a peer retook it, or the corpse could not be removed -- must
|
|
193
|
+
# not spin hot, and must not sleep past the deadline.
|
|
194
|
+
if not _remove_if_still_stale(lock_dir, staleness):
|
|
195
|
+
_nap(_DECLINE_BACKOFF_S, start, timeout)
|
|
196
|
+
continue
|
|
197
|
+
_nap(0.25 + random.random() * 0.25, start, timeout)
|
|
198
|
+
|
|
199
|
+
stop_touching = threading.Event()
|
|
200
|
+
warned = False
|
|
201
|
+
last_ok = time.time()
|
|
202
|
+
|
|
203
|
+
def _touch() -> None:
|
|
204
|
+
nonlocal warned, last_ok
|
|
205
|
+
while not stop_touching.wait(TOUCH_INTERVAL_S):
|
|
206
|
+
try:
|
|
207
|
+
os.utime(lock_dir)
|
|
208
|
+
# THE LATCH IS PER FREEZE, NOT PER HOLD: a refresh that lands
|
|
209
|
+
# ends the episode the warning describes, so the next freeze
|
|
210
|
+
# is a new fact and the takeover it precedes needs saying.
|
|
211
|
+
last_ok, warned = time.time(), False
|
|
212
|
+
except FileNotFoundError:
|
|
213
|
+
return # gone; nothing left to keep alive
|
|
214
|
+
except OSError as e:
|
|
215
|
+
# Transient, so stay armed: absence is terminal and every
|
|
216
|
+
# other errno is not. Re-checking the path to tell them apart
|
|
217
|
+
# is a second syscall that can fail the same way, and from
|
|
218
|
+
# 3.14 one that reads absence out of a permission error.
|
|
219
|
+
#
|
|
220
|
+
# WARN ONLY ONCE THE SENTENCE IS TRUE. It describes a freeze
|
|
221
|
+
# that outlives `staleness`; firing on the first failure
|
|
222
|
+
# announced imminent theft over a lock that stayed fresh.
|
|
223
|
+
if not warned and time.time() - last_ok > staleness:
|
|
224
|
+
warned = True
|
|
225
|
+
_logger.warning(
|
|
226
|
+
"Could not refresh %s (%s); its mtime stops advancing, "
|
|
227
|
+
"so a waiter may take it over as stale",
|
|
228
|
+
lock_dir,
|
|
229
|
+
e,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
toucher = threading.Thread(target=_touch, daemon=True)
|
|
233
|
+
toucher.start()
|
|
234
|
+
try:
|
|
235
|
+
yield
|
|
236
|
+
finally:
|
|
237
|
+
stop_touching.set()
|
|
238
|
+
toucher.join(timeout=1.0)
|
|
239
|
+
try:
|
|
240
|
+
os.rmdir(lock_dir)
|
|
241
|
+
except FileNotFoundError:
|
|
242
|
+
_logger.warning(
|
|
243
|
+
"Lock %s vanished while held (taken over as stale?)", lock_dir
|
|
244
|
+
)
|
|
245
|
+
except OSError as e:
|
|
246
|
+
_logger.warning("Failed to release lock %s: %s", lock_dir, e)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@contextmanager
|
|
250
|
+
def claude_credentials_lock(*, timeout: float | None = None):
|
|
251
|
+
"""Hold Claude Code's credential-refresh locks, in CC's own order.
|
|
252
|
+
|
|
253
|
+
2.1.218 takes ``<config-home>/.oauth_refresh.lock`` first, then the
|
|
254
|
+
legacy ``~/.claude.lock``; on legacy contention it releases the primary
|
|
255
|
+
before retrying. Mirroring both the pair and the order means a waiting
|
|
256
|
+
cswap and a waiting Claude Code can never deadlock against each other,
|
|
257
|
+
and exclusion holds even after CC drops the legacy lock. Both use CC's
|
|
258
|
+
60s staleness — never steal a lock a live CC may still hold.
|
|
259
|
+
"""
|
|
260
|
+
with (
|
|
261
|
+
proper_lockfile(
|
|
262
|
+
oauth_refresh_lock_dir(),
|
|
263
|
+
timeout=timeout,
|
|
264
|
+
staleness=CREDENTIALS_STALENESS_S,
|
|
265
|
+
),
|
|
266
|
+
proper_lockfile(
|
|
267
|
+
credentials_lock_dir(),
|
|
268
|
+
timeout=timeout,
|
|
269
|
+
staleness=CREDENTIALS_STALENESS_S,
|
|
270
|
+
),
|
|
271
|
+
):
|
|
272
|
+
yield
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@contextmanager
|
|
276
|
+
def claude_config_lock(*, timeout: float | None = None):
|
|
277
|
+
"""Hold Claude Code's global-config write lock (``~/.claude.json.lock``)."""
|
|
278
|
+
with proper_lockfile(config_lock_dir(), timeout=timeout):
|
|
279
|
+
yield
|