sub-pool-client 0.1.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.
Potentially problematic release.
This version of sub-pool-client might be problematic. Click here for more details.
- sub_pool_client/__init__.py +22 -0
- sub_pool_client/_cli_core.py +527 -0
- sub_pool_client/_cli_provider.py +142 -0
- sub_pool_client/_health_watcher.py +73 -0
- sub_pool_client/_shared.py +306 -0
- sub_pool_client/_swap.py +104 -0
- sub_pool_client/_version.py +24 -0
- sub_pool_client/cli_claude.py +56 -0
- sub_pool_client/cli_codex.py +58 -0
- sub_pool_client/client.py +462 -0
- sub_pool_client/codex.py +398 -0
- sub_pool_client/errors.py +47 -0
- sub_pool_client-0.1.0.dist-info/METADATA +207 -0
- sub_pool_client-0.1.0.dist-info/RECORD +16 -0
- sub_pool_client-0.1.0.dist-info/WHEEL +4 -0
- sub_pool_client-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Background health watcher for an active lease.
|
|
2
|
+
|
|
3
|
+
Polls `/credentials/lease/{id}/health` on a slow cadence and invokes
|
|
4
|
+
`on_unhealthy` when the lease's underlying account stops being healthy
|
|
5
|
+
(typically: usage_refresh_loop just marked it COOLING because the plan
|
|
6
|
+
window hit ≥95%). The handler is expected to perform an account swap
|
|
7
|
+
(see `_swap.swap_credentials`).
|
|
8
|
+
|
|
9
|
+
Transient failures (network blips, 5xx) are swallowed and retried on the
|
|
10
|
+
next tick — the watcher's job is to be quietly reliable, not noisy.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import logging
|
|
16
|
+
from typing import Any, Awaitable, Callable
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HealthWatcher:
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
*,
|
|
27
|
+
fetch: Callable[[], Awaitable[dict[str, Any]]],
|
|
28
|
+
on_unhealthy: Callable[[dict[str, Any]], Awaitable[None]],
|
|
29
|
+
interval_s: float = 30.0,
|
|
30
|
+
):
|
|
31
|
+
# `fetch` is a no-argument coroutine that returns the health dict
|
|
32
|
+
# — passed as a closure so it captures the *current* lease id
|
|
33
|
+
# even after a swap rotates it (the CLI updates the captured lease
|
|
34
|
+
# in place via a small mutable container).
|
|
35
|
+
self._fetch = fetch
|
|
36
|
+
self._on_unhealthy = on_unhealthy
|
|
37
|
+
self._interval_s = interval_s
|
|
38
|
+
|
|
39
|
+
async def run(self) -> None:
|
|
40
|
+
while True:
|
|
41
|
+
try:
|
|
42
|
+
await asyncio.sleep(self._interval_s)
|
|
43
|
+
except asyncio.CancelledError:
|
|
44
|
+
return
|
|
45
|
+
try:
|
|
46
|
+
data = await self._fetch()
|
|
47
|
+
except httpx.HTTPStatusError as e:
|
|
48
|
+
if e.response.status_code == 410:
|
|
49
|
+
# Lease ended out from under us (someone called
|
|
50
|
+
# DELETE, or a prior swap obsoleted us). Stop.
|
|
51
|
+
return
|
|
52
|
+
if e.response.status_code == 404:
|
|
53
|
+
# Wrong key / unknown lease — same disposition.
|
|
54
|
+
return
|
|
55
|
+
# Other 4xx/5xx — log and keep going.
|
|
56
|
+
log.debug("health probe http error: %s", e)
|
|
57
|
+
continue
|
|
58
|
+
except (httpx.HTTPError, asyncio.TimeoutError) as e:
|
|
59
|
+
log.debug("health probe network error: %s", e)
|
|
60
|
+
continue
|
|
61
|
+
except Exception as e: # noqa: BLE001
|
|
62
|
+
log.debug("health probe unexpected: %s", e)
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
if data.get("healthy"):
|
|
66
|
+
continue
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
await self._on_unhealthy(data)
|
|
70
|
+
except asyncio.CancelledError:
|
|
71
|
+
return
|
|
72
|
+
except Exception as e: # noqa: BLE001
|
|
73
|
+
log.warning("on_unhealthy handler raised: %s", e)
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Cross-process shared credential directory for PooledClient.
|
|
2
|
+
|
|
3
|
+
A well-known directory per (pool_url, api_key, user_id, required_model)
|
|
4
|
+
combo holds:
|
|
5
|
+
|
|
6
|
+
<dir>/.credentials.json ← CLI reads/writes (matches `claude /login` format)
|
|
7
|
+
<dir>/meta.json ← {"lease_id", "holders": [pid, ...]}
|
|
8
|
+
<dir>/.meta.lock ← flock held only while mutating meta.json
|
|
9
|
+
|
|
10
|
+
Coordination rules:
|
|
11
|
+
|
|
12
|
+
- Credential refreshes are coordinated AT THE OS LEVEL by the CLI itself
|
|
13
|
+
(atomic rename + 401-retry-and-reread — same as native CC multi-process).
|
|
14
|
+
We never hold the flock while the CLI is running.
|
|
15
|
+
|
|
16
|
+
- meta.json has a `holders` list of pids. First arriver leases from the
|
|
17
|
+
pool; later arrivers join (refcount via list length). Dead pids are
|
|
18
|
+
filtered on every meta mutation so a crash doesn't leak a slot forever.
|
|
19
|
+
|
|
20
|
+
- When `holders` goes empty, the last holder reads `.credentials.json`
|
|
21
|
+
(possibly rotated by the CLI mid-run) and posts it back to the pool as
|
|
22
|
+
`updated_credentials` on DELETE, then removes the dir.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import asyncio
|
|
27
|
+
import fcntl
|
|
28
|
+
import hashlib
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import shutil
|
|
32
|
+
from contextlib import asynccontextmanager
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import AsyncIterator
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
DEFAULT_ROOT = Path(
|
|
39
|
+
os.environ.get("SUB_POOL_CLIENT_DIR")
|
|
40
|
+
or Path.home() / ".sub-pool" / "client"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def dir_key(
|
|
45
|
+
*,
|
|
46
|
+
pool_url: str,
|
|
47
|
+
api_key: str,
|
|
48
|
+
provider: str = "claude",
|
|
49
|
+
user_id: str | None = None,
|
|
50
|
+
required_model: str | None = None,
|
|
51
|
+
) -> str:
|
|
52
|
+
"""Deterministic short hash. Same inputs → same shared dir → two
|
|
53
|
+
concurrent PooledClient instances meet."""
|
|
54
|
+
parts = [
|
|
55
|
+
provider or "claude",
|
|
56
|
+
pool_url.rstrip("/"),
|
|
57
|
+
api_key,
|
|
58
|
+
user_id or "",
|
|
59
|
+
required_model or "",
|
|
60
|
+
]
|
|
61
|
+
digest = hashlib.sha256("|".join(parts).encode()).hexdigest()
|
|
62
|
+
return digest[:24]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def shared_dir(key: str, root: Path | None = None) -> Path:
|
|
66
|
+
d = (root or DEFAULT_ROOT) / key
|
|
67
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
return d
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Meta:
|
|
73
|
+
lease_id: str | None = None
|
|
74
|
+
holders: list[int] | None = None
|
|
75
|
+
# Which holder owns the /token poll task. If this pid dies, the next
|
|
76
|
+
# arrival / heartbeat tick hands leadership to any live holder.
|
|
77
|
+
# Stays None when no leader has been elected yet (e.g. during
|
|
78
|
+
# bring-up, or after a graceful leader exit before a takeover).
|
|
79
|
+
poll_leader: int | None = None
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def from_json(cls, d: dict) -> "Meta":
|
|
83
|
+
return cls(
|
|
84
|
+
lease_id=d.get("lease_id"),
|
|
85
|
+
holders=list(d.get("holders") or []),
|
|
86
|
+
poll_leader=d.get("poll_leader"),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def to_json(self) -> dict:
|
|
90
|
+
return {
|
|
91
|
+
"lease_id": self.lease_id,
|
|
92
|
+
"holders": self.holders or [],
|
|
93
|
+
"poll_leader": self.poll_leader,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _pid_alive(pid: int) -> bool:
|
|
98
|
+
"""True if the pid currently names a running process."""
|
|
99
|
+
if pid <= 0:
|
|
100
|
+
return False
|
|
101
|
+
try:
|
|
102
|
+
os.kill(pid, 0)
|
|
103
|
+
except ProcessLookupError:
|
|
104
|
+
return False
|
|
105
|
+
except PermissionError:
|
|
106
|
+
# Process exists but we don't own it — rare on a single-user box,
|
|
107
|
+
# but signal "alive" to avoid clobbering someone else's lease.
|
|
108
|
+
return True
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Per-process serialization on top of fcntl.flock. flock is
|
|
113
|
+
# per-process, so two asyncio tasks in the same process would both
|
|
114
|
+
# acquire LOCK_EX "concurrently" without blocking each other. An
|
|
115
|
+
# asyncio.Lock keyed by the shared-dir path plugs that hole.
|
|
116
|
+
_process_locks: dict[str, asyncio.Lock] = {}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _process_lock(key: str) -> asyncio.Lock:
|
|
120
|
+
lock = _process_locks.get(key)
|
|
121
|
+
if lock is None:
|
|
122
|
+
lock = asyncio.Lock()
|
|
123
|
+
_process_locks[key] = lock
|
|
124
|
+
return lock
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@asynccontextmanager
|
|
128
|
+
async def locked_meta(dir_: Path) -> AsyncIterator[Meta]:
|
|
129
|
+
"""Exclusive access to the shared dir's meta.json, both within this
|
|
130
|
+
process (asyncio.Lock) and across processes (fcntl.flock). Caller
|
|
131
|
+
mutates the yielded Meta in place; we persist on exit.
|
|
132
|
+
"""
|
|
133
|
+
lock_path = dir_ / ".meta.lock"
|
|
134
|
+
meta_path = dir_ / "meta.json"
|
|
135
|
+
|
|
136
|
+
async with _process_lock(str(dir_.resolve())):
|
|
137
|
+
# Use O_CREAT so the first arriver creates the lockfile.
|
|
138
|
+
fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT, 0o600)
|
|
139
|
+
try:
|
|
140
|
+
# flock is sync & blocking; release the loop while waiting so
|
|
141
|
+
# a second consumer in the same process isn't completely
|
|
142
|
+
# stuck if someone's running a long inter-process critical
|
|
143
|
+
# section next door.
|
|
144
|
+
await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX)
|
|
145
|
+
try:
|
|
146
|
+
raw = meta_path.read_text() if meta_path.exists() else "{}"
|
|
147
|
+
data = json.loads(raw or "{}")
|
|
148
|
+
except (OSError, ValueError):
|
|
149
|
+
data = {}
|
|
150
|
+
|
|
151
|
+
meta = Meta.from_json(data)
|
|
152
|
+
# Filter dead pids on every read — orphan cleanup is tied to
|
|
153
|
+
# the critical section so we never race with a rejoin.
|
|
154
|
+
if meta.holders:
|
|
155
|
+
meta.holders = [p for p in meta.holders if _pid_alive(p)]
|
|
156
|
+
# A leader pid that no longer exists = no leader. The next
|
|
157
|
+
# heartbeat / enter will elect a fresh one from live holders.
|
|
158
|
+
if meta.poll_leader is not None and not _pid_alive(meta.poll_leader):
|
|
159
|
+
meta.poll_leader = None
|
|
160
|
+
|
|
161
|
+
yield meta
|
|
162
|
+
|
|
163
|
+
payload = json.dumps(meta.to_json(), indent=2)
|
|
164
|
+
tmp = meta_path.with_suffix(meta_path.suffix + ".tmp")
|
|
165
|
+
tmp.write_text(payload)
|
|
166
|
+
os.replace(tmp, meta_path)
|
|
167
|
+
finally:
|
|
168
|
+
try:
|
|
169
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
170
|
+
finally:
|
|
171
|
+
os.close(fd)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def bundle_to_cli_schema(bundle: dict) -> dict:
|
|
175
|
+
"""Translate our flat snake_case bundle (what pool stores in
|
|
176
|
+
token.json / what oauth_anthropic emits) into the nested camelCase
|
|
177
|
+
shape the `claude` CLI's `.credentials.json` uses.
|
|
178
|
+
|
|
179
|
+
Pool shape (seconds since epoch):
|
|
180
|
+
{"access_token", "refresh_token", "expires_at",
|
|
181
|
+
"scope" (str), "subscription_type", ...}
|
|
182
|
+
|
|
183
|
+
CLI shape (milliseconds since epoch, camelCase, nested):
|
|
184
|
+
{"claudeAiOauth": {
|
|
185
|
+
"accessToken", "refreshToken", "expiresAt",
|
|
186
|
+
"scopes" (list[str]), "subscriptionType"
|
|
187
|
+
}}
|
|
188
|
+
"""
|
|
189
|
+
expires_s = float(bundle.get("expires_at") or 0)
|
|
190
|
+
expires_ms = int(expires_s * 1000) if expires_s else 0
|
|
191
|
+
scope_str = bundle.get("scope") or ""
|
|
192
|
+
scopes = scope_str.split() if isinstance(scope_str, str) else list(scope_str or [])
|
|
193
|
+
return {
|
|
194
|
+
"claudeAiOauth": {
|
|
195
|
+
"accessToken": bundle.get("access_token") or "",
|
|
196
|
+
"refreshToken": bundle.get("refresh_token") or "",
|
|
197
|
+
"expiresAt": expires_ms,
|
|
198
|
+
"scopes": scopes,
|
|
199
|
+
"subscriptionType": bundle.get("subscription_type") or "",
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def bundle_from_cli_schema(cli_file_contents: dict) -> dict:
|
|
205
|
+
"""Inverse of bundle_to_cli_schema. Used when we read the (possibly
|
|
206
|
+
rotated) file back out on release to post `updated_credentials` to
|
|
207
|
+
the pool."""
|
|
208
|
+
nested = cli_file_contents.get("claudeAiOauth") or {}
|
|
209
|
+
expires_ms = int(nested.get("expiresAt") or 0)
|
|
210
|
+
expires_s = expires_ms / 1000.0 if expires_ms else 0.0
|
|
211
|
+
scopes = nested.get("scopes") or []
|
|
212
|
+
scope_str = " ".join(scopes) if isinstance(scopes, list) else str(scopes)
|
|
213
|
+
return {
|
|
214
|
+
"access_token": nested.get("accessToken") or "",
|
|
215
|
+
"refresh_token": nested.get("refreshToken") or "",
|
|
216
|
+
"expires_at": expires_s,
|
|
217
|
+
"scope": scope_str,
|
|
218
|
+
"subscription_type": nested.get("subscriptionType") or "",
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def write_credentials(dir_: Path, bundle: dict) -> None:
|
|
223
|
+
"""Atomic .credentials.json write in the CLI's expected schema,
|
|
224
|
+
0600 perms. `bundle` is our flat snake_case shape."""
|
|
225
|
+
p = dir_ / ".credentials.json"
|
|
226
|
+
tmp = p.with_suffix(p.suffix + ".tmp")
|
|
227
|
+
cli_payload = bundle_to_cli_schema(bundle)
|
|
228
|
+
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
229
|
+
try:
|
|
230
|
+
with os.fdopen(fd, "w") as f:
|
|
231
|
+
json.dump(cli_payload, f, indent=2)
|
|
232
|
+
except BaseException:
|
|
233
|
+
try:
|
|
234
|
+
os.unlink(tmp)
|
|
235
|
+
except OSError:
|
|
236
|
+
pass
|
|
237
|
+
raise
|
|
238
|
+
os.replace(tmp, p)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def read_credentials(dir_: Path) -> dict | None:
|
|
242
|
+
"""Read .credentials.json (CLI schema) and return our flat bundle
|
|
243
|
+
shape. None if the file is missing / malformed."""
|
|
244
|
+
p = dir_ / ".credentials.json"
|
|
245
|
+
if not p.exists():
|
|
246
|
+
return None
|
|
247
|
+
try:
|
|
248
|
+
raw = json.loads(p.read_text())
|
|
249
|
+
except (OSError, ValueError):
|
|
250
|
+
return None
|
|
251
|
+
if not isinstance(raw, dict) or "claudeAiOauth" not in raw:
|
|
252
|
+
return None
|
|
253
|
+
return bundle_from_cli_schema(raw)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def write_codex_auth(dir_: Path, auth_json: dict) -> None:
|
|
257
|
+
"""Atomic Codex auth.json write in $CODEX_HOME."""
|
|
258
|
+
p = dir_ / "auth.json"
|
|
259
|
+
tmp = p.with_suffix(p.suffix + ".tmp")
|
|
260
|
+
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
261
|
+
try:
|
|
262
|
+
with os.fdopen(fd, "w") as f:
|
|
263
|
+
json.dump(auth_json, f, indent=2)
|
|
264
|
+
except BaseException:
|
|
265
|
+
try:
|
|
266
|
+
os.unlink(tmp)
|
|
267
|
+
except OSError:
|
|
268
|
+
pass
|
|
269
|
+
raise
|
|
270
|
+
os.replace(tmp, p)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def read_codex_auth(dir_: Path) -> dict | None:
|
|
274
|
+
p = dir_ / "auth.json"
|
|
275
|
+
if not p.exists():
|
|
276
|
+
return None
|
|
277
|
+
try:
|
|
278
|
+
raw = json.loads(p.read_text())
|
|
279
|
+
except (OSError, ValueError):
|
|
280
|
+
return None
|
|
281
|
+
return raw if isinstance(raw, dict) else None
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def cleanup_dir(dir_: Path) -> None:
|
|
285
|
+
"""Remove the shared dir. Idempotent."""
|
|
286
|
+
try:
|
|
287
|
+
shutil.rmtree(dir_, ignore_errors=True)
|
|
288
|
+
except Exception: # noqa: BLE001
|
|
289
|
+
pass
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# The DEFAULT_ROOT constant pulls from $SUB_POOL_CLIENT_DIR at import
|
|
293
|
+
# time; tests that want isolation should clear the env before import or
|
|
294
|
+
# pass `root=` explicitly.
|
|
295
|
+
__all__ = [
|
|
296
|
+
"DEFAULT_ROOT",
|
|
297
|
+
"Meta",
|
|
298
|
+
"cleanup_dir",
|
|
299
|
+
"dir_key",
|
|
300
|
+
"locked_meta",
|
|
301
|
+
"read_credentials",
|
|
302
|
+
"read_codex_auth",
|
|
303
|
+
"shared_dir",
|
|
304
|
+
"write_codex_auth",
|
|
305
|
+
"write_credentials",
|
|
306
|
+
]
|
sub_pool_client/_swap.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Mid-session account swap.
|
|
2
|
+
|
|
3
|
+
When the health watcher reports the current lease's account has cooled,
|
|
4
|
+
this module rotates the on-disk credential to a different account:
|
|
5
|
+
|
|
6
|
+
1. POST /credentials/lease (pool strategy picks an AVAILABLE account,
|
|
7
|
+
not the one we're trying to swap away from — because the strategy
|
|
8
|
+
already skips COOLING accounts).
|
|
9
|
+
2. Atomically update the caller's `current` container AND
|
|
10
|
+
.credentials.json (sync block, no await between).
|
|
11
|
+
3. Best-effort DELETE the old lease.
|
|
12
|
+
|
|
13
|
+
The order in step 2 is load-bearing — see the race-safety contract in
|
|
14
|
+
`swap_credentials` below.
|
|
15
|
+
|
|
16
|
+
The `claude` CLI re-reads .credentials.json across requests (empirically
|
|
17
|
+
verified: a /login in one window flips the running `claude` in another
|
|
18
|
+
window to the newly-written identity, observable via `/cost`), so the
|
|
19
|
+
swap is transparent to the user — next prompt round-trips on the new
|
|
20
|
+
account.
|
|
21
|
+
|
|
22
|
+
If every account in the pool is currently cooling, the strategy returns
|
|
23
|
+
503. We raise `NoSwapAvailable`; the watcher swallows it and retries on
|
|
24
|
+
the next tick.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import TYPE_CHECKING
|
|
31
|
+
|
|
32
|
+
import httpx
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from sub_pool_client._cli_core import PoolHTTP
|
|
36
|
+
from sub_pool_client._cli_provider import CliProvider
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class NoSwapAvailable(Exception):
|
|
42
|
+
"""Pool has no other healthy account to switch to right now."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def swap_credentials(
|
|
46
|
+
pool: "PoolHTTP", current: dict, session_dir: Path,
|
|
47
|
+
provider: "CliProvider",
|
|
48
|
+
*, account: str | None = None,
|
|
49
|
+
) -> dict:
|
|
50
|
+
"""Replace the lease backing `session_dir` with a fresh one.
|
|
51
|
+
|
|
52
|
+
`current` is the same mutable container the refresh / health tasks
|
|
53
|
+
read out of (`{"lease": <lease dict>}`); we mutate it in place so
|
|
54
|
+
those tasks pick up the new lease_id without any restart plumbing.
|
|
55
|
+
|
|
56
|
+
Race-safety contract — this is why `current` is a parameter rather
|
|
57
|
+
than something the caller assigns after we return:
|
|
58
|
+
|
|
59
|
+
The token-refresh task captures `current["lease"]["lease_id"]`
|
|
60
|
+
pre-call, awaits `pool.refresh_token`, then re-checks the lease_id
|
|
61
|
+
to detect a concurrent swap (`_refresh_once`). For that guard to
|
|
62
|
+
catch us, `current["lease"]` must be advanced to the new lease
|
|
63
|
+
BEFORE any further `await` in this function — otherwise refresh
|
|
64
|
+
can wake up while we're suspended on `pool.release`, still see the
|
|
65
|
+
old lease_id, and clobber `.credentials.json` with a stale token.
|
|
66
|
+
|
|
67
|
+
So: update `current` + disk inside a sync block, THEN await release.
|
|
68
|
+
|
|
69
|
+
Returns the new lease dict (also stored at `current["lease"]`).
|
|
70
|
+
"""
|
|
71
|
+
old_lease_id = current["lease"]["lease_id"]
|
|
72
|
+
try:
|
|
73
|
+
new_lease = await pool.lease(provider, account=account)
|
|
74
|
+
except httpx.HTTPStatusError as e:
|
|
75
|
+
# 503 = strategy says no candidate (all cooling / invalid).
|
|
76
|
+
# Anything else: surface as no-swap-available so the watcher
|
|
77
|
+
# backs off; we don't want to nuke the existing lease over a
|
|
78
|
+
# transient pool blip.
|
|
79
|
+
raise NoSwapAvailable(
|
|
80
|
+
f"pool returned {e.response.status_code}: "
|
|
81
|
+
f"{e.response.text[:120]}"
|
|
82
|
+
) from e
|
|
83
|
+
except httpx.HTTPError as e:
|
|
84
|
+
raise NoSwapAvailable(f"pool unreachable: {e}") from e
|
|
85
|
+
|
|
86
|
+
if new_lease.get("lease_id") == old_lease_id:
|
|
87
|
+
# Strategy handed back the same lease — happens if the CLI passes
|
|
88
|
+
# `account=` and that account is still the only candidate. Not a
|
|
89
|
+
# real swap; treat as nothing-to-do so we don't churn.
|
|
90
|
+
raise NoSwapAvailable("strategy returned the same lease_id")
|
|
91
|
+
|
|
92
|
+
# === Sync block — no await between disk write and current update.
|
|
93
|
+
# Write disk first so a `write_credentials` exception leaves the
|
|
94
|
+
# caller's view (`current`) consistent with what's actually on disk.
|
|
95
|
+
provider.write_credentials(session_dir / provider.cred_filename, new_lease)
|
|
96
|
+
current["lease"] = new_lease
|
|
97
|
+
# === End sync block.
|
|
98
|
+
|
|
99
|
+
# Best-effort cleanup of the now-cooled lease. Even if release fails
|
|
100
|
+
# the swap has already taken effect.
|
|
101
|
+
await pool.release(old_lease_id)
|
|
102
|
+
log.info("swapped lease %s → %s (account %s)",
|
|
103
|
+
old_lease_id, new_lease["lease_id"], new_lease.get("account"))
|
|
104
|
+
return new_lease
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""sp-claude — run the `claude` CLI under a credential leased from sub-pool.
|
|
2
|
+
|
|
3
|
+
sp-claude # interactive REPL, equivalent to bare `claude`
|
|
4
|
+
sp-claude "prompt" # one-shot
|
|
5
|
+
sp-claude -- /resume # arguments after `--` go straight to claude
|
|
6
|
+
|
|
7
|
+
Setup / introspection:
|
|
8
|
+
|
|
9
|
+
sp-claude --setup # one-time wizard, writes ~/.sub-pool/cli.toml
|
|
10
|
+
sp-claude --status # print current pool URL + last-used account
|
|
11
|
+
sp-claude --account NAME # bind to a specific pool account
|
|
12
|
+
sp-claude --claude-bin /path # override `claude` binary location
|
|
13
|
+
sp-claude --verbose # print swap / refresh events to stderr
|
|
14
|
+
|
|
15
|
+
While the session is alive the credentials file in `CLAUDE_CONFIG_DIR`
|
|
16
|
+
is kept current — token rotations and mid-session account swaps
|
|
17
|
+
happen transparently in the background.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import sys
|
|
23
|
+
|
|
24
|
+
import click
|
|
25
|
+
|
|
26
|
+
from sub_pool_client._cli_core import run_session, run_setup, run_status
|
|
27
|
+
from sub_pool_client._cli_provider import CLAUDE
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@click.command(
|
|
31
|
+
context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
|
|
32
|
+
help="Run `claude` CLI with credentials leased from a sub-pool server.",
|
|
33
|
+
)
|
|
34
|
+
@click.argument("claude_args", nargs=-1, type=click.UNPROCESSED)
|
|
35
|
+
@click.option("--setup", is_flag=True, help="One-time pool config wizard.")
|
|
36
|
+
@click.option("--status", is_flag=True, help="Show current config + exit.")
|
|
37
|
+
@click.option("--account", default=None,
|
|
38
|
+
help="Bind to a specific account, skipping round-robin order. "
|
|
39
|
+
"Subject to the api key's strategy eligibility.")
|
|
40
|
+
@click.option("--claude-bin", default=None,
|
|
41
|
+
help="Override path to `claude` binary.")
|
|
42
|
+
@click.option("--verbose", is_flag=True,
|
|
43
|
+
help="Print swap / refresh events to stderr.")
|
|
44
|
+
def main(claude_args, setup, status, account, claude_bin, verbose) -> None:
|
|
45
|
+
if setup:
|
|
46
|
+
sys.exit(run_setup(CLAUDE))
|
|
47
|
+
if status:
|
|
48
|
+
sys.exit(run_status(CLAUDE))
|
|
49
|
+
code = asyncio.run(run_session(
|
|
50
|
+
CLAUDE, claude_args, account, claude_bin, verbose,
|
|
51
|
+
))
|
|
52
|
+
sys.exit(code)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if __name__ == "__main__":
|
|
56
|
+
main()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""sp-codex — run the `codex` CLI under a credential leased from sub-pool.
|
|
2
|
+
|
|
3
|
+
sp-codex # interactive REPL, equivalent to bare `codex`
|
|
4
|
+
sp-codex exec "prompt" # one-shot; args after the binary are
|
|
5
|
+
# passed through unchanged
|
|
6
|
+
sp-codex -- /help # arguments after `--` go straight to codex
|
|
7
|
+
|
|
8
|
+
Setup / introspection:
|
|
9
|
+
|
|
10
|
+
sp-codex --setup # one-time wizard, writes ~/.sub-pool/cli.toml
|
|
11
|
+
sp-codex --status # print current pool URL + last-used account
|
|
12
|
+
sp-codex --account NAME # bind to a specific Codex account
|
|
13
|
+
sp-codex --codex-bin /path # override `codex` binary location
|
|
14
|
+
sp-codex --verbose # print swap / refresh events to stderr
|
|
15
|
+
|
|
16
|
+
While the session is alive `$CODEX_HOME/auth.json` is kept current —
|
|
17
|
+
token rotations and mid-session account swaps happen transparently in
|
|
18
|
+
the background, so the leased account stays in rotation across long
|
|
19
|
+
runs.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import sys
|
|
25
|
+
|
|
26
|
+
import click
|
|
27
|
+
|
|
28
|
+
from sub_pool_client._cli_core import run_session, run_setup, run_status
|
|
29
|
+
from sub_pool_client._cli_provider import CODEX
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@click.command(
|
|
33
|
+
context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
|
|
34
|
+
help="Run `codex` CLI with credentials leased from a sub-pool server.",
|
|
35
|
+
)
|
|
36
|
+
@click.argument("codex_args", nargs=-1, type=click.UNPROCESSED)
|
|
37
|
+
@click.option("--setup", is_flag=True, help="One-time pool config wizard.")
|
|
38
|
+
@click.option("--status", is_flag=True, help="Show current config + exit.")
|
|
39
|
+
@click.option("--account", default=None,
|
|
40
|
+
help="Bind to a specific Codex account, skipping round-robin "
|
|
41
|
+
"order. Subject to the api key's strategy eligibility.")
|
|
42
|
+
@click.option("--codex-bin", default=None,
|
|
43
|
+
help="Override path to `codex` binary.")
|
|
44
|
+
@click.option("--verbose", is_flag=True,
|
|
45
|
+
help="Print swap / refresh events to stderr.")
|
|
46
|
+
def main(codex_args, setup, status, account, codex_bin, verbose) -> None:
|
|
47
|
+
if setup:
|
|
48
|
+
sys.exit(run_setup(CODEX))
|
|
49
|
+
if status:
|
|
50
|
+
sys.exit(run_status(CODEX))
|
|
51
|
+
code = asyncio.run(run_session(
|
|
52
|
+
CODEX, codex_args, account, codex_bin, verbose,
|
|
53
|
+
))
|
|
54
|
+
sys.exit(code)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
main()
|