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,22 @@
|
|
|
1
|
+
from sub_pool_client.client import PooledClient
|
|
2
|
+
from sub_pool_client.codex import PooledCodexClient
|
|
3
|
+
from sub_pool_client.errors import (
|
|
4
|
+
PoolAcquireTimeoutError,
|
|
5
|
+
PoolAuthError,
|
|
6
|
+
PoolConnectionError,
|
|
7
|
+
PoolError,
|
|
8
|
+
PoolProtocolError,
|
|
9
|
+
PoolUpstreamError,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.0"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"PooledClient",
|
|
15
|
+
"PooledCodexClient",
|
|
16
|
+
"PoolError",
|
|
17
|
+
"PoolConnectionError",
|
|
18
|
+
"PoolAuthError",
|
|
19
|
+
"PoolAcquireTimeoutError",
|
|
20
|
+
"PoolUpstreamError",
|
|
21
|
+
"PoolProtocolError",
|
|
22
|
+
]
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""Provider-agnostic engine behind `sp-claude` / `sp-codex`.
|
|
2
|
+
|
|
3
|
+
What lives here is the lease lifecycle: lease → write per-session
|
|
4
|
+
credentials → spawn the upstream CLI → background refresh + health
|
|
5
|
+
swap → release. The thin click entry-points in `cli_claude.py` and
|
|
6
|
+
`cli_codex.py` instantiate a `CliProvider` and hand it to
|
|
7
|
+
`run_session`; nothing in this module switches on provider name.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import signal
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
from contextlib import suppress
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import click
|
|
24
|
+
import httpx
|
|
25
|
+
|
|
26
|
+
from sub_pool_client._cli_provider import CliProvider
|
|
27
|
+
from sub_pool_client._health_watcher import HealthWatcher
|
|
28
|
+
from sub_pool_client._swap import NoSwapAvailable, swap_credentials
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger("sp")
|
|
32
|
+
|
|
33
|
+
# `sp` config + persistent home dirs, sibling to the user's `~/.claude/`
|
|
34
|
+
# (or `~/.codex/`). One root per host shared across providers; per-provider
|
|
35
|
+
# state lives in subdirs named by `CliProvider.home_subdir`.
|
|
36
|
+
SP_ROOT = Path.home() / ".sub-pool"
|
|
37
|
+
CONFIG_PATH = SP_ROOT / "cli.toml"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ============================================================ config
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Config:
|
|
44
|
+
"""Loaded `~/.sub-pool/cli.toml`.
|
|
45
|
+
|
|
46
|
+
Shape:
|
|
47
|
+
|
|
48
|
+
[pool]
|
|
49
|
+
url = "https://pool.example.com"
|
|
50
|
+
api_key = "cp-..."
|
|
51
|
+
|
|
52
|
+
[claude]
|
|
53
|
+
bin = "claude" # optional, defaults to PATH lookup
|
|
54
|
+
default_account = "" # optional, "" = strategy-picked
|
|
55
|
+
|
|
56
|
+
[codex]
|
|
57
|
+
bin = "codex"
|
|
58
|
+
default_account = ""
|
|
59
|
+
|
|
60
|
+
Per-provider sections are optional; absent values fall back to
|
|
61
|
+
the provider's `default_bin` and an empty default account.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, pool_url: str, api_key: str,
|
|
65
|
+
per_provider: dict[str, dict[str, str]] | None = None):
|
|
66
|
+
self.pool_url = pool_url.rstrip("/")
|
|
67
|
+
self.api_key = api_key
|
|
68
|
+
self._per_provider = per_provider or {}
|
|
69
|
+
|
|
70
|
+
def bin_for(self, provider: CliProvider) -> str:
|
|
71
|
+
return (self._per_provider.get(provider.name, {}).get("bin")
|
|
72
|
+
or provider.default_bin)
|
|
73
|
+
|
|
74
|
+
def default_account_for(self, provider: CliProvider) -> str | None:
|
|
75
|
+
return (self._per_provider.get(provider.name, {}).get("default_account")
|
|
76
|
+
or None)
|
|
77
|
+
|
|
78
|
+
def merged_provider_section(
|
|
79
|
+
self, provider: CliProvider, *, bin_override: str | None = None,
|
|
80
|
+
account_override: str | None = None,
|
|
81
|
+
) -> dict[str, str]:
|
|
82
|
+
"""Return what would be written under `[<provider.name>]`, given
|
|
83
|
+
the existing config and any in-flight overrides from `--setup`."""
|
|
84
|
+
existing = dict(self._per_provider.get(provider.name, {}))
|
|
85
|
+
if bin_override is not None:
|
|
86
|
+
existing["bin"] = bin_override
|
|
87
|
+
if account_override is not None:
|
|
88
|
+
existing["default_account"] = account_override
|
|
89
|
+
return existing
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def load(cls) -> "Config | None":
|
|
93
|
+
if not CONFIG_PATH.exists():
|
|
94
|
+
return None
|
|
95
|
+
import tomllib
|
|
96
|
+
data = tomllib.loads(CONFIG_PATH.read_text())
|
|
97
|
+
pool = data.get("pool") or {}
|
|
98
|
+
if not pool.get("url") or not pool.get("api_key"):
|
|
99
|
+
return None
|
|
100
|
+
per_provider: dict[str, dict[str, str]] = {}
|
|
101
|
+
for name in ("claude", "codex"):
|
|
102
|
+
section = data.get(name)
|
|
103
|
+
if isinstance(section, dict):
|
|
104
|
+
per_provider[name] = {
|
|
105
|
+
k: str(v) for k, v in section.items()
|
|
106
|
+
if isinstance(v, (str, int, float))
|
|
107
|
+
}
|
|
108
|
+
return cls(pool_url=pool["url"], api_key=pool["api_key"],
|
|
109
|
+
per_provider=per_provider)
|
|
110
|
+
|
|
111
|
+
def write(self) -> None:
|
|
112
|
+
SP_ROOT.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
body = (
|
|
114
|
+
"[pool]\n"
|
|
115
|
+
f"url = {_toml_str(self.pool_url)}\n"
|
|
116
|
+
f"api_key = {_toml_str(self.api_key)}\n"
|
|
117
|
+
)
|
|
118
|
+
for name in ("claude", "codex"):
|
|
119
|
+
section = self._per_provider.get(name)
|
|
120
|
+
if not section:
|
|
121
|
+
continue
|
|
122
|
+
body += f"\n[{name}]\n"
|
|
123
|
+
for key in ("bin", "default_account"):
|
|
124
|
+
if section.get(key) is not None:
|
|
125
|
+
body += f"{key} = {_toml_str(str(section[key]))}\n"
|
|
126
|
+
# Create at 0o600 atomically — never a readable window for the
|
|
127
|
+
# api_key — and fchmod after for the existing-file case.
|
|
128
|
+
fd = os.open(str(CONFIG_PATH),
|
|
129
|
+
os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
130
|
+
os.fchmod(fd, 0o600)
|
|
131
|
+
with os.fdopen(fd, "w") as f:
|
|
132
|
+
f.write(body)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _toml_str(s: str) -> str:
|
|
136
|
+
"""Render `s` as a TOML literal string (no escape interpretation).
|
|
137
|
+
Falls back to a basic string when `s` contains a literal `'`."""
|
|
138
|
+
if "'" not in s:
|
|
139
|
+
return f"'{s}'"
|
|
140
|
+
escaped = s.replace("\\", "\\\\").replace('"', '\\"')
|
|
141
|
+
return f'"{escaped}"'
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def run_setup(provider: CliProvider) -> int:
|
|
145
|
+
click.echo(f"sub-pool CLI setup ({provider.name})\n")
|
|
146
|
+
existing = Config.load()
|
|
147
|
+
pool_default = existing.pool_url if existing else ""
|
|
148
|
+
while True:
|
|
149
|
+
pool_url = click.prompt(
|
|
150
|
+
"Pool URL", default=pool_default or "https://",
|
|
151
|
+
show_default=bool(pool_default),
|
|
152
|
+
).strip()
|
|
153
|
+
if pool_url.startswith(("http://", "https://")) and len(pool_url) > 8:
|
|
154
|
+
break
|
|
155
|
+
click.echo(" → must start with http:// or https://", err=True)
|
|
156
|
+
api_key = click.prompt("API key (cp-...)", hide_input=True).strip()
|
|
157
|
+
default_account = click.prompt(
|
|
158
|
+
f"Default {provider.name} account (empty = strategy-based)",
|
|
159
|
+
default=(existing.default_account_for(provider)
|
|
160
|
+
if existing else "") or "",
|
|
161
|
+
show_default=False,
|
|
162
|
+
).strip()
|
|
163
|
+
|
|
164
|
+
# Preserve other providers' sections — setup is per-provider.
|
|
165
|
+
per_provider = (dict(existing._per_provider) if existing else {})
|
|
166
|
+
per_provider[provider.name] = {
|
|
167
|
+
"bin": (existing.bin_for(provider) if existing else provider.default_bin),
|
|
168
|
+
"default_account": default_account,
|
|
169
|
+
}
|
|
170
|
+
cfg = Config(pool_url=pool_url, api_key=api_key, per_provider=per_provider)
|
|
171
|
+
cfg.write()
|
|
172
|
+
click.echo(f"\nWrote {CONFIG_PATH}")
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def run_status(provider: CliProvider) -> int:
|
|
177
|
+
cfg = Config.load()
|
|
178
|
+
if cfg is None:
|
|
179
|
+
click.echo(f"No config — run `sp-{provider.name} --setup`", err=True)
|
|
180
|
+
return 1
|
|
181
|
+
click.echo(f"pool_url {cfg.pool_url}")
|
|
182
|
+
click.echo(f"api_key {cfg.api_key[:12]}…")
|
|
183
|
+
click.echo(f"provider {provider.name}")
|
|
184
|
+
click.echo(f"binary {cfg.bin_for(provider)}")
|
|
185
|
+
click.echo(f"default_acct {cfg.default_account_for(provider) or '(strategy)'}")
|
|
186
|
+
click.echo(f"config_path {CONFIG_PATH}")
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# ============================================================ session dir
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _atomic_write_json(path: Path, payload: Any) -> None:
|
|
194
|
+
"""Mode 0o600 from the start (no readable window) + atomic rename."""
|
|
195
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
196
|
+
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
197
|
+
os.fchmod(fd, 0o600)
|
|
198
|
+
with os.fdopen(fd, "w") as f:
|
|
199
|
+
f.write(json.dumps(payload, indent=2))
|
|
200
|
+
os.replace(tmp, path)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _is_per_session(name: str, prefixes: tuple[str, ...]) -> bool:
|
|
204
|
+
return any(name.startswith(p) for p in prefixes)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _merge_into(src: Path, dst: Path) -> None:
|
|
208
|
+
"""Recursively copy entries from `src` into `dst`. Existing entries
|
|
209
|
+
in `dst` always win — a concurrent session may have already
|
|
210
|
+
committed its own copy.
|
|
211
|
+
"""
|
|
212
|
+
dst.mkdir(parents=True, exist_ok=True)
|
|
213
|
+
for entry in src.iterdir():
|
|
214
|
+
d = dst / entry.name
|
|
215
|
+
if entry.is_dir() and not entry.is_symlink():
|
|
216
|
+
_merge_into(entry, d)
|
|
217
|
+
continue
|
|
218
|
+
if d.exists() or d.is_symlink():
|
|
219
|
+
continue
|
|
220
|
+
try:
|
|
221
|
+
shutil.copy2(entry, d, follow_symlinks=True)
|
|
222
|
+
except Exception: # noqa: BLE001
|
|
223
|
+
pass
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def commit_session_to_home(
|
|
227
|
+
session_dir: Path, home: Path, provider: CliProvider,
|
|
228
|
+
) -> None:
|
|
229
|
+
"""Persist anything the spawned CLI wrote into `session_dir` back
|
|
230
|
+
into the persistent `home`.
|
|
231
|
+
|
|
232
|
+
Entries that are symlinks pointed at `home` already routed writes
|
|
233
|
+
there; nothing to do. Entries matching `cred_skip_prefixes` are
|
|
234
|
+
per-session and must never leak (would persist a stale token).
|
|
235
|
+
|
|
236
|
+
Best-effort — IO failures suppressed; shutdown must remain
|
|
237
|
+
unblockable.
|
|
238
|
+
"""
|
|
239
|
+
if not session_dir.exists():
|
|
240
|
+
return
|
|
241
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
for entry in session_dir.iterdir():
|
|
243
|
+
if _is_per_session(entry.name, provider.cred_skip_prefixes):
|
|
244
|
+
continue
|
|
245
|
+
if entry.is_symlink():
|
|
246
|
+
continue
|
|
247
|
+
dst = home / entry.name
|
|
248
|
+
try:
|
|
249
|
+
if entry.is_dir():
|
|
250
|
+
_merge_into(entry, dst)
|
|
251
|
+
elif not dst.exists():
|
|
252
|
+
shutil.copy2(entry, dst, follow_symlinks=True)
|
|
253
|
+
except Exception: # noqa: BLE001
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def setup_session_dir(
|
|
258
|
+
home: Path, session_dir: Path, provider: CliProvider,
|
|
259
|
+
) -> None:
|
|
260
|
+
"""Wire `session_dir` so the spawned CLI sees it as its config dir.
|
|
261
|
+
|
|
262
|
+
Every top-level entry in `home` (skipping `cred_skip_prefixes`)
|
|
263
|
+
gets symlinked into `session_dir`. The credentials file is NOT
|
|
264
|
+
symlinked — we write a per-session copy so two concurrent sessions
|
|
265
|
+
can bind to different leases without clobbering each other.
|
|
266
|
+
|
|
267
|
+
Re-runnable: rebuilds the symlink layout from `home`'s current
|
|
268
|
+
contents on each call, so files persisted by a previous session
|
|
269
|
+
show up automatically.
|
|
270
|
+
"""
|
|
271
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
272
|
+
os.chmod(home, 0o700)
|
|
273
|
+
for entry in home.iterdir():
|
|
274
|
+
if _is_per_session(entry.name, provider.cred_skip_prefixes):
|
|
275
|
+
continue
|
|
276
|
+
target = session_dir / entry.name
|
|
277
|
+
if target.is_symlink() or target.exists():
|
|
278
|
+
if target.is_dir() and not target.is_symlink():
|
|
279
|
+
shutil.rmtree(target)
|
|
280
|
+
else:
|
|
281
|
+
target.unlink()
|
|
282
|
+
os.symlink(entry.resolve(), target)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# ============================================================ pool I/O
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class PoolHTTP:
|
|
289
|
+
def __init__(self, cfg: Config):
|
|
290
|
+
self._cfg = cfg
|
|
291
|
+
self._client = httpx.AsyncClient(
|
|
292
|
+
base_url=cfg.pool_url,
|
|
293
|
+
headers={"Authorization": f"Bearer {cfg.api_key}"},
|
|
294
|
+
timeout=httpx.Timeout(30.0, connect=10.0),
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
async def aclose(self) -> None:
|
|
298
|
+
await self._client.aclose()
|
|
299
|
+
|
|
300
|
+
async def lease(self, provider: CliProvider, *,
|
|
301
|
+
account: str | None = None,
|
|
302
|
+
user_id: str | None = None) -> dict:
|
|
303
|
+
body: dict[str, Any] = dict(provider.lease_body_extras)
|
|
304
|
+
if account:
|
|
305
|
+
body["account"] = account
|
|
306
|
+
if user_id:
|
|
307
|
+
body["user_id"] = user_id
|
|
308
|
+
r = await self._client.post("/credentials/lease", json=body)
|
|
309
|
+
r.raise_for_status()
|
|
310
|
+
return r.json()
|
|
311
|
+
|
|
312
|
+
async def refresh_token(self, lease_id: str) -> dict:
|
|
313
|
+
r = await self._client.post(f"/credentials/lease/{lease_id}/token")
|
|
314
|
+
r.raise_for_status()
|
|
315
|
+
return r.json()
|
|
316
|
+
|
|
317
|
+
async def release(self, lease_id: str) -> None:
|
|
318
|
+
with suppress(Exception):
|
|
319
|
+
await self._client.request(
|
|
320
|
+
"DELETE", f"/credentials/lease/{lease_id}", json={},
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
async def health(self, lease_id: str) -> dict:
|
|
324
|
+
r = await self._client.get(f"/credentials/lease/{lease_id}/health")
|
|
325
|
+
r.raise_for_status()
|
|
326
|
+
return r.json()
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ============================================================ session main
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
async def run_session(
|
|
333
|
+
provider: CliProvider,
|
|
334
|
+
prompt_args: tuple[str, ...],
|
|
335
|
+
account: str | None,
|
|
336
|
+
bin_override: str | None,
|
|
337
|
+
verbose: bool,
|
|
338
|
+
) -> int:
|
|
339
|
+
cfg = Config.load()
|
|
340
|
+
if cfg is None:
|
|
341
|
+
click.echo(
|
|
342
|
+
f"No pool config — run `sp-{provider.name} --setup` first.",
|
|
343
|
+
err=True,
|
|
344
|
+
)
|
|
345
|
+
return 2
|
|
346
|
+
|
|
347
|
+
if verbose:
|
|
348
|
+
logging.basicConfig(
|
|
349
|
+
level=logging.INFO, format=f"[sp-{provider.name}] %(message)s",
|
|
350
|
+
stream=sys.stderr,
|
|
351
|
+
)
|
|
352
|
+
bin_path = bin_override or cfg.bin_for(provider)
|
|
353
|
+
chosen_account = account or cfg.default_account_for(provider)
|
|
354
|
+
home_dir = SP_ROOT / provider.home_subdir
|
|
355
|
+
user_id = os.environ.get("USER") or os.environ.get("USERNAME")
|
|
356
|
+
|
|
357
|
+
pool = PoolHTTP(cfg)
|
|
358
|
+
try:
|
|
359
|
+
try:
|
|
360
|
+
lease = await pool.lease(
|
|
361
|
+
provider, account=chosen_account, user_id=user_id,
|
|
362
|
+
)
|
|
363
|
+
except httpx.HTTPStatusError as e:
|
|
364
|
+
click.echo(_describe_http_error(e, "lease"), err=True)
|
|
365
|
+
return 3
|
|
366
|
+
except httpx.HTTPError as e:
|
|
367
|
+
click.echo(f"[sp-{provider.name}] pool unreachable: {e}", err=True)
|
|
368
|
+
return 3
|
|
369
|
+
if verbose:
|
|
370
|
+
log.info("leased %s (lease_id=%s)",
|
|
371
|
+
lease.get("account"), lease.get("lease_id"))
|
|
372
|
+
|
|
373
|
+
# Per-session temp config dir. Holds ONLY the per-session
|
|
374
|
+
# credentials; everything else lives in `home_dir` via symlinks
|
|
375
|
+
# set up by `setup_session_dir`. The session_dir is rmtree'd on
|
|
376
|
+
# exit; symlink targets in `home_dir` persist.
|
|
377
|
+
session_dir = Path(tempfile.mkdtemp(prefix=f"sp-{provider.name}-"))
|
|
378
|
+
try:
|
|
379
|
+
setup_session_dir(home_dir, session_dir, provider)
|
|
380
|
+
provider.write_credentials(
|
|
381
|
+
session_dir / provider.cred_filename, lease,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
env = os.environ.copy()
|
|
385
|
+
env[provider.config_dir_env] = str(session_dir)
|
|
386
|
+
for k in provider.bypass_env_vars:
|
|
387
|
+
env.pop(k, None)
|
|
388
|
+
|
|
389
|
+
proc = await asyncio.create_subprocess_exec(
|
|
390
|
+
bin_path, *prompt_args, env=env,
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
# Forward common signals so Ctrl-C reaches the child. Record
|
|
394
|
+
# which handlers we installed so the finally block can
|
|
395
|
+
# uninstall — leaving them set could fire against an
|
|
396
|
+
# already-exited proc, or (in tests that reuse a loop)
|
|
397
|
+
# bleed across sessions.
|
|
398
|
+
loop = asyncio.get_running_loop()
|
|
399
|
+
installed_signals: list[int] = []
|
|
400
|
+
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
|
401
|
+
try:
|
|
402
|
+
loop.add_signal_handler(sig, lambda s=sig: _forward(proc, s))
|
|
403
|
+
except (NotImplementedError, RuntimeError):
|
|
404
|
+
continue
|
|
405
|
+
installed_signals.append(sig)
|
|
406
|
+
|
|
407
|
+
# Background tasks: token refresh + health-driven account swap.
|
|
408
|
+
current = {"lease": lease}
|
|
409
|
+
|
|
410
|
+
async def on_swap_needed(health: dict) -> None:
|
|
411
|
+
# Read the from-account BEFORE swap_credentials runs —
|
|
412
|
+
# the call mutates `current["lease"]` in place (that's
|
|
413
|
+
# what closes the refresh/swap race; see _swap.py).
|
|
414
|
+
old_account = current["lease"].get("account")
|
|
415
|
+
try:
|
|
416
|
+
new = await swap_credentials(
|
|
417
|
+
pool, current, session_dir, provider,
|
|
418
|
+
account=chosen_account,
|
|
419
|
+
)
|
|
420
|
+
if verbose:
|
|
421
|
+
log.info(
|
|
422
|
+
"swapped %s → %s (reason: %s)",
|
|
423
|
+
old_account, new.get("account"),
|
|
424
|
+
(health.get("reason") or "unhealthy")[:80],
|
|
425
|
+
)
|
|
426
|
+
except NoSwapAvailable as e:
|
|
427
|
+
if verbose:
|
|
428
|
+
log.info("swap deferred: %s", e)
|
|
429
|
+
|
|
430
|
+
refresher = asyncio.create_task(
|
|
431
|
+
_token_refresh_loop(pool, current, session_dir, provider, verbose),
|
|
432
|
+
name=f"sp-{provider.name}-refresh",
|
|
433
|
+
)
|
|
434
|
+
watcher = asyncio.create_task(
|
|
435
|
+
HealthWatcher(
|
|
436
|
+
fetch=lambda: pool.health(current["lease"]["lease_id"]),
|
|
437
|
+
on_unhealthy=on_swap_needed,
|
|
438
|
+
).run(),
|
|
439
|
+
name=f"sp-{provider.name}-health",
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
try:
|
|
443
|
+
exit_code = await proc.wait()
|
|
444
|
+
finally:
|
|
445
|
+
for sig in installed_signals:
|
|
446
|
+
with suppress(NotImplementedError, RuntimeError):
|
|
447
|
+
loop.remove_signal_handler(sig)
|
|
448
|
+
refresher.cancel()
|
|
449
|
+
watcher.cancel()
|
|
450
|
+
for t in (refresher, watcher):
|
|
451
|
+
with suppress(asyncio.CancelledError, Exception):
|
|
452
|
+
await t
|
|
453
|
+
await pool.release(current["lease"]["lease_id"])
|
|
454
|
+
finally:
|
|
455
|
+
with suppress(Exception):
|
|
456
|
+
commit_session_to_home(session_dir, home_dir, provider)
|
|
457
|
+
shutil.rmtree(session_dir, ignore_errors=True)
|
|
458
|
+
return exit_code
|
|
459
|
+
finally:
|
|
460
|
+
await pool.aclose()
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _forward(proc: asyncio.subprocess.Process, sig: int) -> None:
|
|
464
|
+
with suppress(ProcessLookupError, OSError):
|
|
465
|
+
proc.send_signal(sig)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
async def _refresh_once(
|
|
469
|
+
pool: PoolHTTP, current: dict, session_dir: Path,
|
|
470
|
+
provider: CliProvider, verbose: bool,
|
|
471
|
+
) -> bool:
|
|
472
|
+
"""Refresh access_token once. Returns True iff the new token was
|
|
473
|
+
persisted; False if the call failed OR a concurrent swap rotated
|
|
474
|
+
`current["lease"]` while our POST /token was in flight — in that
|
|
475
|
+
case our refresh is stale and writing it would clobber the swap's
|
|
476
|
+
credentials file with the (now-cooled) prior account's token.
|
|
477
|
+
"""
|
|
478
|
+
old_lease_id = current["lease"]["lease_id"]
|
|
479
|
+
try:
|
|
480
|
+
new = await pool.refresh_token(old_lease_id)
|
|
481
|
+
except Exception as e: # noqa: BLE001
|
|
482
|
+
if verbose:
|
|
483
|
+
log.info("token refresh failed: %s", e)
|
|
484
|
+
return False
|
|
485
|
+
if current["lease"]["lease_id"] != old_lease_id:
|
|
486
|
+
if verbose:
|
|
487
|
+
log.info("token refresh dropped (lease swapped during refresh)")
|
|
488
|
+
return False
|
|
489
|
+
merged = {**current["lease"], **new}
|
|
490
|
+
current["lease"] = merged
|
|
491
|
+
provider.write_credentials(session_dir / provider.cred_filename, merged)
|
|
492
|
+
if verbose:
|
|
493
|
+
log.info("token refreshed (expires_at=%s)",
|
|
494
|
+
merged.get("token_expires_at"))
|
|
495
|
+
return True
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
async def _token_refresh_loop(
|
|
499
|
+
pool: PoolHTTP, current: dict, session_dir: Path,
|
|
500
|
+
provider: CliProvider, verbose: bool,
|
|
501
|
+
*, interval_s: float = 50 * 60,
|
|
502
|
+
) -> None:
|
|
503
|
+
"""Periodically rotate access_token via the pool. Same cadence as
|
|
504
|
+
PooledClient. See `_refresh_once` for the race-safety guard."""
|
|
505
|
+
while True:
|
|
506
|
+
try:
|
|
507
|
+
await asyncio.sleep(interval_s)
|
|
508
|
+
except asyncio.CancelledError:
|
|
509
|
+
return
|
|
510
|
+
await _refresh_once(pool, current, session_dir, provider, verbose)
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _describe_http_error(e: httpx.HTTPStatusError, action: str) -> str:
|
|
514
|
+
try:
|
|
515
|
+
detail = e.response.json()
|
|
516
|
+
if isinstance(detail, dict):
|
|
517
|
+
inner = detail.get("detail")
|
|
518
|
+
if isinstance(inner, dict):
|
|
519
|
+
return (f"[sp] {action} failed ({e.response.status_code}): "
|
|
520
|
+
f"{inner.get('code')}: {inner.get('message')}")
|
|
521
|
+
if isinstance(inner, str):
|
|
522
|
+
return (f"[sp] {action} failed ({e.response.status_code}): "
|
|
523
|
+
f"{inner}")
|
|
524
|
+
except Exception:
|
|
525
|
+
pass
|
|
526
|
+
return (f"[sp] {action} failed ({e.response.status_code}): "
|
|
527
|
+
f"{e.response.text[:200]}")
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Per-provider knobs for the sp-claude / sp-codex CLIs.
|
|
2
|
+
|
|
3
|
+
The lease loop in `_cli_core` is provider-agnostic — same lease /
|
|
4
|
+
refresh / release flow regardless of which upstream CLI gets spawned.
|
|
5
|
+
Everything that DOES differ between Claude and Codex is collapsed into
|
|
6
|
+
this `CliProvider` value: file names, env var names, default binary,
|
|
7
|
+
credential payload shape.
|
|
8
|
+
|
|
9
|
+
Add a third provider by appending an instance below — no other module
|
|
10
|
+
needs to change.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Callable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _write_claude_credentials(path: Path, lease: dict) -> None:
|
|
22
|
+
"""Write `.credentials.json` in the shape the `claude` CLI reads.
|
|
23
|
+
|
|
24
|
+
`refreshToken` is intentionally blanked — the pool owns the refresh
|
|
25
|
+
chain; consumers poll `/credentials/lease/{id}/token` for rotations
|
|
26
|
+
via `_token_refresh_loop`. `scope` arrives as a space-separated
|
|
27
|
+
string (Anthropic OAuth convention) and gets split into the array
|
|
28
|
+
shape claude expects.
|
|
29
|
+
"""
|
|
30
|
+
scope_raw = (lease.get("scope") or "").strip()
|
|
31
|
+
scopes = scope_raw.split() if scope_raw else []
|
|
32
|
+
payload = {
|
|
33
|
+
"claudeAiOauth": {
|
|
34
|
+
"accessToken": lease["access_token"],
|
|
35
|
+
"refreshToken": "",
|
|
36
|
+
"expiresAt": int(float(lease["token_expires_at"]) * 1000),
|
|
37
|
+
"scopes": scopes,
|
|
38
|
+
"subscriptionType": (lease.get("subscription_type") or "claude_max"),
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
_atomic_write_json(path, payload)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _write_codex_auth(path: Path, lease: dict) -> None:
|
|
45
|
+
"""Write the leased `auth.json` exactly as the pool returned it.
|
|
46
|
+
|
|
47
|
+
The pool already strips `refresh_token` server-side — we just persist
|
|
48
|
+
the sanitized bundle so the local `codex` CLI can read it from
|
|
49
|
+
`$CODEX_HOME/auth.json`.
|
|
50
|
+
"""
|
|
51
|
+
creds = lease.get("credentials") or {}
|
|
52
|
+
auth = creds.get("auth_json")
|
|
53
|
+
if not isinstance(auth, dict):
|
|
54
|
+
raise RuntimeError(
|
|
55
|
+
"lease response did not include a Codex auth_json bundle"
|
|
56
|
+
)
|
|
57
|
+
_atomic_write_json(path, auth)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _atomic_write_json(path: Path, payload: Any) -> None:
|
|
61
|
+
"""Create at 0o600 from the start (no readable window) and atomic-rename."""
|
|
62
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
63
|
+
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
64
|
+
os.fchmod(fd, 0o600)
|
|
65
|
+
try:
|
|
66
|
+
with os.fdopen(fd, "w") as f:
|
|
67
|
+
f.write(json.dumps(payload, indent=2))
|
|
68
|
+
except BaseException:
|
|
69
|
+
try:
|
|
70
|
+
os.unlink(tmp)
|
|
71
|
+
except OSError:
|
|
72
|
+
pass
|
|
73
|
+
raise
|
|
74
|
+
os.replace(tmp, path)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class CliProvider:
|
|
79
|
+
name: str
|
|
80
|
+
# Default binary name resolved from PATH; overridable via CLI flag /
|
|
81
|
+
# cli.toml.
|
|
82
|
+
default_bin: str
|
|
83
|
+
# Environment variable the spawned binary uses to locate its config
|
|
84
|
+
# dir. The CLI sets this to the per-session temp dir.
|
|
85
|
+
config_dir_env: str
|
|
86
|
+
# Name of the credentials file written into the per-session dir.
|
|
87
|
+
cred_filename: str
|
|
88
|
+
# File-name prefixes that are per-session and must NOT be symlinked
|
|
89
|
+
# from the persistent home, nor copied back. Lets a stray
|
|
90
|
+
# `auth.json.tmp` or `.credentials.json.bak` from a crashed run never
|
|
91
|
+
# leak into the persistent home.
|
|
92
|
+
cred_skip_prefixes: tuple[str, ...]
|
|
93
|
+
# Subdir under `~/.sub-pool/` for this provider's persistent
|
|
94
|
+
# CLAUDE_CONFIG_DIR / CODEX_HOME equivalent.
|
|
95
|
+
home_subdir: str
|
|
96
|
+
# Ambient env vars that would let the spawned binary skip the leased
|
|
97
|
+
# credential file. Stripped from the child env before spawn.
|
|
98
|
+
bypass_env_vars: tuple[str, ...]
|
|
99
|
+
# Extra body fields included in POST /credentials/lease so the pool
|
|
100
|
+
# routes us to a matching account. Empty for claude (the default).
|
|
101
|
+
lease_body_extras: dict
|
|
102
|
+
# Pluggable credential writer — kept on the provider so the engine
|
|
103
|
+
# never has to switch on `name`.
|
|
104
|
+
write_credentials: Callable[[Path, dict], None]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
CLAUDE = CliProvider(
|
|
108
|
+
name="claude",
|
|
109
|
+
default_bin="claude",
|
|
110
|
+
config_dir_env="CLAUDE_CONFIG_DIR",
|
|
111
|
+
cred_filename=".credentials.json",
|
|
112
|
+
cred_skip_prefixes=(".credentials",),
|
|
113
|
+
home_subdir="claude-home",
|
|
114
|
+
bypass_env_vars=(
|
|
115
|
+
"ANTHROPIC_API_KEY",
|
|
116
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
117
|
+
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
118
|
+
),
|
|
119
|
+
lease_body_extras={},
|
|
120
|
+
write_credentials=_write_claude_credentials,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
CODEX = CliProvider(
|
|
125
|
+
name="codex",
|
|
126
|
+
default_bin="codex",
|
|
127
|
+
config_dir_env="CODEX_HOME",
|
|
128
|
+
cred_filename="auth.json",
|
|
129
|
+
cred_skip_prefixes=("auth.json",),
|
|
130
|
+
home_subdir="codex-home",
|
|
131
|
+
bypass_env_vars=("OPENAI_API_KEY",),
|
|
132
|
+
lease_body_extras={"provider": "codex"},
|
|
133
|
+
write_credentials=_write_codex_auth,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def get_provider(name: str) -> CliProvider:
|
|
138
|
+
if name == "claude":
|
|
139
|
+
return CLAUDE
|
|
140
|
+
if name == "codex":
|
|
141
|
+
return CODEX
|
|
142
|
+
raise ValueError(f"unknown provider {name!r}")
|