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
sub_pool_client/codex.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""PooledCodexClient — lease a Codex account from the pool and run
|
|
2
|
+
Codex CLI locally with a pool-managed auth.json.
|
|
3
|
+
|
|
4
|
+
Symmetric to `PooledClient` for claude:
|
|
5
|
+
- The pool owns the OAuth refresh_token chain. The leased auth.json
|
|
6
|
+
contains a fresh access_token but its refresh_token field is
|
|
7
|
+
blanked out, so the local Codex CLI cannot independently rotate
|
|
8
|
+
the chain (and racing rotations across concurrent leases can't
|
|
9
|
+
happen).
|
|
10
|
+
- A background poll task asks the pool for a refreshed access_token
|
|
11
|
+
before the current one expires, then atomically rewrites the
|
|
12
|
+
shared $CODEX_HOME/auth.json so the CLI picks up the new token on
|
|
13
|
+
its next read.
|
|
14
|
+
- On a backend error (consumer-detected 429 / auth_expired from
|
|
15
|
+
upstream OpenAI), the caller can call `report_error(code, msg)`
|
|
16
|
+
so the pool cools the account and routes other leases elsewhere.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import time
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
import httpx
|
|
28
|
+
|
|
29
|
+
from sub_pool_client._shared import (
|
|
30
|
+
cleanup_dir,
|
|
31
|
+
dir_key,
|
|
32
|
+
locked_meta,
|
|
33
|
+
shared_dir,
|
|
34
|
+
write_codex_auth,
|
|
35
|
+
)
|
|
36
|
+
from sub_pool_client.errors import (
|
|
37
|
+
PoolAuthError,
|
|
38
|
+
PoolConnectionError,
|
|
39
|
+
PoolUpstreamError,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
log = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PooledCodexClient:
|
|
46
|
+
"""Context manager that exposes a leased Codex account through CODEX_HOME.
|
|
47
|
+
|
|
48
|
+
The pool leases a sanitized Codex CLI auth.json (no refresh_token).
|
|
49
|
+
Codex itself runs on the caller's machine; this client prepares an
|
|
50
|
+
isolated CODEX_HOME, reference-counts shared local use, polls the
|
|
51
|
+
pool for refreshed access_tokens, and releases the lease on exit.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
*,
|
|
57
|
+
pool_url: str | None = None,
|
|
58
|
+
api_key: str | None = None,
|
|
59
|
+
user_id: str | None = None,
|
|
60
|
+
request_id: str | None = None,
|
|
61
|
+
required_model: str | None = None,
|
|
62
|
+
required_features: list[str] | None = None,
|
|
63
|
+
codex_bin: str = "codex",
|
|
64
|
+
http_client: httpx.AsyncClient | None = None,
|
|
65
|
+
):
|
|
66
|
+
self._pool_url = (pool_url or os.environ.get("SUB_POOL_URL", "")).rstrip("/")
|
|
67
|
+
self._api_key = api_key or os.environ.get("SUB_POOL_KEY", "")
|
|
68
|
+
if not self._pool_url:
|
|
69
|
+
raise ValueError("pool_url required (set SUB_POOL_URL)")
|
|
70
|
+
if not self._api_key:
|
|
71
|
+
raise ValueError("api_key required (set SUB_POOL_KEY)")
|
|
72
|
+
|
|
73
|
+
self._user_id = user_id
|
|
74
|
+
self._request_id_req = request_id
|
|
75
|
+
self._required_model = required_model
|
|
76
|
+
self._required_features = list(required_features or [])
|
|
77
|
+
self._codex_bin = codex_bin
|
|
78
|
+
self._owned_http = http_client is None
|
|
79
|
+
self._http = http_client or httpx.AsyncClient(timeout=10.0)
|
|
80
|
+
|
|
81
|
+
self._dir: Path | None = None
|
|
82
|
+
self._lease_id: str | None = None
|
|
83
|
+
self._lease_account: str | None = None
|
|
84
|
+
self._lease_request_id: str | None = None
|
|
85
|
+
self._token_expires_at: float = 0.0
|
|
86
|
+
|
|
87
|
+
self._poll_task: asyncio.Task | None = None
|
|
88
|
+
self._heartbeat_task: asyncio.Task | None = None
|
|
89
|
+
self._is_poll_leader: bool = False
|
|
90
|
+
|
|
91
|
+
async def __aenter__(self) -> "PooledCodexClient":
|
|
92
|
+
key = dir_key(
|
|
93
|
+
pool_url=self._pool_url,
|
|
94
|
+
api_key=self._api_key,
|
|
95
|
+
provider="codex",
|
|
96
|
+
user_id=self._user_id,
|
|
97
|
+
required_model=self._required_model,
|
|
98
|
+
)
|
|
99
|
+
self._dir = shared_dir(key)
|
|
100
|
+
await self._join_or_acquire_lease()
|
|
101
|
+
if self._is_poll_leader:
|
|
102
|
+
self._poll_task = asyncio.create_task(self._poll_loop())
|
|
103
|
+
# Every holder runs the heartbeat — cheap, and takes over
|
|
104
|
+
# leadership if the current leader exits.
|
|
105
|
+
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
|
|
106
|
+
return self
|
|
107
|
+
|
|
108
|
+
async def __aexit__(self, exc_type, exc, tb) -> None:
|
|
109
|
+
for attr in ("_poll_task", "_heartbeat_task"):
|
|
110
|
+
t = getattr(self, attr, None)
|
|
111
|
+
if t is not None:
|
|
112
|
+
t.cancel()
|
|
113
|
+
try:
|
|
114
|
+
await t
|
|
115
|
+
except (asyncio.CancelledError, Exception):
|
|
116
|
+
pass
|
|
117
|
+
setattr(self, attr, None)
|
|
118
|
+
await self._leave_lease(exc)
|
|
119
|
+
if self._owned_http:
|
|
120
|
+
await self._http.aclose()
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def codex_home(self) -> Path:
|
|
124
|
+
if self._dir is None:
|
|
125
|
+
raise RuntimeError("PooledCodexClient is not entered")
|
|
126
|
+
return self._dir
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def env(self) -> dict[str, str]:
|
|
130
|
+
env = os.environ.copy()
|
|
131
|
+
env["CODEX_HOME"] = str(self.codex_home)
|
|
132
|
+
# Avoid an ambient API key taking precedence over the leased auth.json.
|
|
133
|
+
env.pop("OPENAI_API_KEY", None)
|
|
134
|
+
return env
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def account(self) -> str | None:
|
|
138
|
+
return self._lease_account
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def lease_id(self) -> str | None:
|
|
142
|
+
return self._lease_id
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def request_id(self) -> str | None:
|
|
146
|
+
return self._lease_request_id
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
async def report_error(self, code: str, message: str) -> dict:
|
|
150
|
+
"""Mid-lease: tell the pool about a backend error (429, quota,
|
|
151
|
+
auth rejection) so it cools the account and routes parallel
|
|
152
|
+
leases elsewhere. The lease itself stays alive — caller decides
|
|
153
|
+
whether to keep using it or tear down and re-lease.
|
|
154
|
+
"""
|
|
155
|
+
if self._lease_id is None:
|
|
156
|
+
return {}
|
|
157
|
+
try:
|
|
158
|
+
r = await self._http.post(
|
|
159
|
+
f"{self._pool_url}/credentials/lease/{self._lease_id}/report-error",
|
|
160
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
161
|
+
json={"code": code, "message": message},
|
|
162
|
+
)
|
|
163
|
+
except Exception as e: # noqa: BLE001
|
|
164
|
+
log.warning("codex report_error HTTP failed: %s", e)
|
|
165
|
+
return {}
|
|
166
|
+
if r.status_code >= 400:
|
|
167
|
+
log.warning("codex report_error %s: %s", r.status_code, r.text[:200])
|
|
168
|
+
return {}
|
|
169
|
+
return r.json()
|
|
170
|
+
|
|
171
|
+
async def exec(
|
|
172
|
+
self,
|
|
173
|
+
prompt: str,
|
|
174
|
+
*extra_args: str,
|
|
175
|
+
cwd: str | Path | None = None,
|
|
176
|
+
model: str | None = None,
|
|
177
|
+
json_output: bool = False,
|
|
178
|
+
) -> asyncio.subprocess.Process:
|
|
179
|
+
"""Spawn `codex exec` with this lease's CODEX_HOME.
|
|
180
|
+
|
|
181
|
+
The returned process is already started; callers decide how to read
|
|
182
|
+
stdout/stderr and wait.
|
|
183
|
+
"""
|
|
184
|
+
cmd = [self._codex_bin, "exec"]
|
|
185
|
+
if model:
|
|
186
|
+
cmd += ["--model", model]
|
|
187
|
+
if cwd is not None:
|
|
188
|
+
cmd += ["--cd", str(cwd)]
|
|
189
|
+
if json_output:
|
|
190
|
+
cmd.append("--json")
|
|
191
|
+
cmd.extend(extra_args)
|
|
192
|
+
cmd.append(prompt)
|
|
193
|
+
return await asyncio.create_subprocess_exec(
|
|
194
|
+
*cmd,
|
|
195
|
+
env=self.env,
|
|
196
|
+
stdout=asyncio.subprocess.PIPE,
|
|
197
|
+
stderr=asyncio.subprocess.PIPE,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
async def _join_or_acquire_lease(self) -> None:
|
|
201
|
+
assert self._dir is not None
|
|
202
|
+
my_pid = os.getpid()
|
|
203
|
+
async with locked_meta(self._dir) as meta:
|
|
204
|
+
if meta.lease_id and meta.holders:
|
|
205
|
+
# Active lease already present — reuse it.
|
|
206
|
+
self._lease_id = meta.lease_id
|
|
207
|
+
meta.holders.append(my_pid)
|
|
208
|
+
# locked_meta cleared dead-pid leaders, so poll_leader is
|
|
209
|
+
# either a live pid or None. Claim leadership right away
|
|
210
|
+
# if vacant; otherwise the heartbeat task will promote
|
|
211
|
+
# us if the current leader exits.
|
|
212
|
+
if meta.poll_leader is None:
|
|
213
|
+
meta.poll_leader = my_pid
|
|
214
|
+
self._is_poll_leader = True
|
|
215
|
+
return
|
|
216
|
+
|
|
217
|
+
lease = await self._post_lease()
|
|
218
|
+
creds = lease.get("credentials") or {}
|
|
219
|
+
auth_json = creds.get("auth_json")
|
|
220
|
+
if not isinstance(auth_json, dict):
|
|
221
|
+
raise PoolUpstreamError(
|
|
222
|
+
"MissingBundle",
|
|
223
|
+
"lease response did not include a Codex auth_json bundle",
|
|
224
|
+
)
|
|
225
|
+
write_codex_auth(self._dir, auth_json)
|
|
226
|
+
self._lease_id = lease["lease_id"]
|
|
227
|
+
self._lease_account = lease.get("account")
|
|
228
|
+
self._lease_request_id = lease.get("request_id")
|
|
229
|
+
self._token_expires_at = float(lease.get("token_expires_at") or 0.0)
|
|
230
|
+
meta.lease_id = self._lease_id
|
|
231
|
+
meta.holders = [my_pid]
|
|
232
|
+
meta.poll_leader = my_pid
|
|
233
|
+
self._is_poll_leader = True
|
|
234
|
+
|
|
235
|
+
async def _leave_lease(self, exc: BaseException | None) -> None:
|
|
236
|
+
if self._dir is None or self._lease_id is None:
|
|
237
|
+
return
|
|
238
|
+
my_pid = os.getpid()
|
|
239
|
+
last_out = False
|
|
240
|
+
lease_id_to_release: str | None = None
|
|
241
|
+
async with locked_meta(self._dir) as meta:
|
|
242
|
+
if meta.holders:
|
|
243
|
+
try:
|
|
244
|
+
meta.holders.remove(my_pid)
|
|
245
|
+
except ValueError:
|
|
246
|
+
pass
|
|
247
|
+
if meta.poll_leader == my_pid:
|
|
248
|
+
meta.poll_leader = None
|
|
249
|
+
if not meta.holders:
|
|
250
|
+
lease_id_to_release = meta.lease_id
|
|
251
|
+
last_out = True
|
|
252
|
+
|
|
253
|
+
if last_out and lease_id_to_release is not None:
|
|
254
|
+
try:
|
|
255
|
+
await self._delete_lease(lease_id_to_release, exc)
|
|
256
|
+
except Exception:
|
|
257
|
+
log.exception("lease release failed (best-effort)")
|
|
258
|
+
cleanup_dir(self._dir)
|
|
259
|
+
|
|
260
|
+
async def _heartbeat_loop(self, interval_s: float = 30.0) -> None:
|
|
261
|
+
"""If the original poll leader exits, the next-in-line holder
|
|
262
|
+
promotes itself and takes over the rotation."""
|
|
263
|
+
try:
|
|
264
|
+
while True:
|
|
265
|
+
await asyncio.sleep(interval_s)
|
|
266
|
+
if self._is_poll_leader or self._dir is None:
|
|
267
|
+
continue
|
|
268
|
+
my_pid = os.getpid()
|
|
269
|
+
promoted = False
|
|
270
|
+
async with locked_meta(self._dir) as meta:
|
|
271
|
+
if meta.poll_leader is None and my_pid in (meta.holders or []):
|
|
272
|
+
meta.poll_leader = my_pid
|
|
273
|
+
promoted = True
|
|
274
|
+
if promoted:
|
|
275
|
+
self._is_poll_leader = True
|
|
276
|
+
self._poll_task = asyncio.create_task(self._poll_loop())
|
|
277
|
+
log.info("codex heartbeat: promoted self to poll leader")
|
|
278
|
+
return
|
|
279
|
+
except asyncio.CancelledError:
|
|
280
|
+
return
|
|
281
|
+
|
|
282
|
+
async def _poll_loop(self) -> None:
|
|
283
|
+
"""Periodically ask the pool for a refreshed sanitized auth.json
|
|
284
|
+
and rewrite the shared one. Codex CLI re-reads auth.json on its
|
|
285
|
+
next call, so the rotation is transparent.
|
|
286
|
+
"""
|
|
287
|
+
try:
|
|
288
|
+
while True:
|
|
289
|
+
remaining = self._token_expires_at - time.time()
|
|
290
|
+
# Wake up 10 min before expiry, minimum 60s sleep.
|
|
291
|
+
sleep_s = max(60.0, remaining - 600.0)
|
|
292
|
+
await asyncio.sleep(sleep_s)
|
|
293
|
+
|
|
294
|
+
if self._dir is None or self._lease_id is None:
|
|
295
|
+
return
|
|
296
|
+
|
|
297
|
+
try:
|
|
298
|
+
new = await self._post_poll_token()
|
|
299
|
+
except Exception as e: # noqa: BLE001
|
|
300
|
+
log.warning("codex lease token poll failed: %s", e)
|
|
301
|
+
self._token_expires_at = time.time() + 60.0
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
creds = new.get("credentials") or {}
|
|
305
|
+
new_auth = creds.get("auth_json")
|
|
306
|
+
new_exp = float(new.get("token_expires_at") or 0.0)
|
|
307
|
+
if not isinstance(new_auth, dict) or not new_exp:
|
|
308
|
+
log.warning(
|
|
309
|
+
"codex poll returned empty bundle: %s", new,
|
|
310
|
+
)
|
|
311
|
+
continue
|
|
312
|
+
|
|
313
|
+
try:
|
|
314
|
+
write_codex_auth(self._dir, new_auth)
|
|
315
|
+
except OSError as e:
|
|
316
|
+
log.warning("failed to update codex auth.json: %s", e)
|
|
317
|
+
continue
|
|
318
|
+
|
|
319
|
+
self._token_expires_at = new_exp
|
|
320
|
+
log.debug(
|
|
321
|
+
"rotated codex access_token for lease %s (exp=%s)",
|
|
322
|
+
self._lease_id, new_exp,
|
|
323
|
+
)
|
|
324
|
+
except asyncio.CancelledError:
|
|
325
|
+
return
|
|
326
|
+
|
|
327
|
+
async def _post_poll_token(self) -> dict:
|
|
328
|
+
assert self._lease_id is not None
|
|
329
|
+
r = await self._http.post(
|
|
330
|
+
f"{self._pool_url}/credentials/lease/{self._lease_id}/token",
|
|
331
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
332
|
+
)
|
|
333
|
+
if r.status_code >= 400:
|
|
334
|
+
detail = _detail_or_text(r)
|
|
335
|
+
raise PoolUpstreamError(
|
|
336
|
+
str(detail.get("code") or f"HTTP{r.status_code}"),
|
|
337
|
+
str(detail.get("message") or r.text[:500]),
|
|
338
|
+
)
|
|
339
|
+
return r.json()
|
|
340
|
+
|
|
341
|
+
async def _post_lease(self) -> dict:
|
|
342
|
+
body: dict[str, Any] = {"provider": "codex"}
|
|
343
|
+
if self._user_id:
|
|
344
|
+
body["user_id"] = self._user_id
|
|
345
|
+
if self._request_id_req:
|
|
346
|
+
body["request_id"] = self._request_id_req
|
|
347
|
+
if self._required_model:
|
|
348
|
+
body["required_model"] = self._required_model
|
|
349
|
+
if self._required_features:
|
|
350
|
+
body["required_features"] = list(self._required_features)
|
|
351
|
+
try:
|
|
352
|
+
r = await self._http.post(
|
|
353
|
+
f"{self._pool_url}/credentials/lease",
|
|
354
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
355
|
+
json=body,
|
|
356
|
+
)
|
|
357
|
+
except (httpx.ConnectError, httpx.ReadTimeout) as e:
|
|
358
|
+
raise PoolConnectionError("ConnectError", str(e)) from e
|
|
359
|
+
except httpx.HTTPError as e:
|
|
360
|
+
raise PoolConnectionError("HTTPError", str(e)) from e
|
|
361
|
+
|
|
362
|
+
if r.status_code in (401, 403):
|
|
363
|
+
raise PoolAuthError(
|
|
364
|
+
f"HTTP{r.status_code}", r.text[:500] or "authorization failed",
|
|
365
|
+
)
|
|
366
|
+
if r.status_code >= 400:
|
|
367
|
+
detail = _detail_or_text(r)
|
|
368
|
+
raise PoolUpstreamError(
|
|
369
|
+
str(detail.get("code") or f"HTTP{r.status_code}"),
|
|
370
|
+
str(detail.get("message") or r.text[:500]),
|
|
371
|
+
)
|
|
372
|
+
return r.json()
|
|
373
|
+
|
|
374
|
+
async def _delete_lease(
|
|
375
|
+
self, lease_id: str, exc: BaseException | None,
|
|
376
|
+
) -> None:
|
|
377
|
+
body: dict[str, Any] = {}
|
|
378
|
+
if exc is not None:
|
|
379
|
+
body["error_code"] = type(exc).__name__
|
|
380
|
+
body["error_message"] = str(exc)[:2000]
|
|
381
|
+
await self._http.request(
|
|
382
|
+
"DELETE",
|
|
383
|
+
f"{self._pool_url}/credentials/lease/{lease_id}",
|
|
384
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
385
|
+
json=body,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _detail_or_text(r: httpx.Response) -> dict[str, Any]:
|
|
390
|
+
try:
|
|
391
|
+
d = r.json()
|
|
392
|
+
except ValueError:
|
|
393
|
+
return {"message": r.text}
|
|
394
|
+
if isinstance(d, dict) and isinstance(d.get("detail"), dict):
|
|
395
|
+
return d["detail"]
|
|
396
|
+
if isinstance(d, dict):
|
|
397
|
+
return d
|
|
398
|
+
return {"message": str(d)}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Exception hierarchy for PooledClient.
|
|
2
|
+
|
|
3
|
+
Rooted at `ClaudeSDKError` so that production code using
|
|
4
|
+
`except ClaudeSDKError:` catches pool-side failures the same way it catches
|
|
5
|
+
native SDK failures.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from claude_agent_sdk import ClaudeSDKError # type: ignore
|
|
11
|
+
except ImportError: # pragma: no cover
|
|
12
|
+
class ClaudeSDKError(Exception): # type: ignore
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PoolError(ClaudeSDKError):
|
|
17
|
+
"""Base class for all pool-side failures surfaced to the client."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, code: str, message: str):
|
|
20
|
+
super().__init__(f"{code}: {message}")
|
|
21
|
+
self.code = code
|
|
22
|
+
self.message = message
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PoolConnectionError(PoolError):
|
|
26
|
+
"""Network-level failure talking to the pool server."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PoolAuthError(PoolError):
|
|
30
|
+
"""401/403 from the pool server."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PoolAcquireTimeoutError(PoolError):
|
|
34
|
+
"""Pool could not find a suitable account within the acquire timeout."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class PoolUpstreamError(PoolError):
|
|
38
|
+
"""A session-level error reported by the pool (usually from the SDK on the worker).
|
|
39
|
+
|
|
40
|
+
Typically these originate from Anthropic — rate limits, quota, OAuth
|
|
41
|
+
expired, etc. `code` is the worker's exception class name (e.g.
|
|
42
|
+
ClaudeSDKError, ProcessError) and `message` is its str().
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PoolProtocolError(PoolError):
|
|
47
|
+
"""Pool returned an event we could not interpret."""
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sub-pool-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client + `sp-claude` / `sp-codex` CLIs for a sub-pool credential broker.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Zephyroam/sub-pool-client
|
|
6
|
+
Project-URL: Repository, https://github.com/Zephyroam/sub-pool-client
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Requires-Dist: claude-agent-sdk>=0.1.63
|
|
9
|
+
Requires-Dist: click>=8.1
|
|
10
|
+
Requires-Dist: httpx>=0.27
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# sub-pool-client
|
|
14
|
+
|
|
15
|
+
Python client + interactive CLIs for a `sub-pool` server — a
|
|
16
|
+
credential broker for N Claude **and** OpenAI Codex subscription
|
|
17
|
+
accounts.
|
|
18
|
+
|
|
19
|
+
You get three things in one package:
|
|
20
|
+
|
|
21
|
+
1. **`sp-claude`** — a `claude` CLI wrapper. Leases a Claude account
|
|
22
|
+
from the pool, runs the real `claude` binary against a per-session
|
|
23
|
+
`CLAUDE_CONFIG_DIR`, rotates the access_token in the background, and
|
|
24
|
+
swaps accounts transparently if the leased one cools mid-run.
|
|
25
|
+
2. **`sp-codex`** — same flow for OpenAI Codex. Leases a Codex
|
|
26
|
+
`auth.json`, drops it into an isolated `CODEX_HOME`, spawns the
|
|
27
|
+
real `codex` binary, and rotates the token in the background.
|
|
28
|
+
3. **`PooledClient` / `PooledCodexClient`** — Python SDK classes for
|
|
29
|
+
programs and services. `PooledClient` is a drop-in subclass of
|
|
30
|
+
`ClaudeSDKClient` from the official `claude-agent-sdk`;
|
|
31
|
+
`PooledCodexClient` is a thin async wrapper around `codex exec`.
|
|
32
|
+
|
|
33
|
+
The agent loop — tool execution, filesystem I/O, hooks, MCP servers,
|
|
34
|
+
the codex subprocess — all stays on the consumer's machine. The pool
|
|
35
|
+
only sees lease lifecycles.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install git+https://github.com/Zephyroam/sub-pool-client
|
|
41
|
+
# or
|
|
42
|
+
uv pip install git+https://github.com/Zephyroam/sub-pool-client
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Environment
|
|
46
|
+
|
|
47
|
+
Both the CLIs and the SDK read:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
export SUB_POOL_URL=http://your-pool-host:8787
|
|
51
|
+
export SUB_POOL_KEY=cp-... # admin issues this from the sub-pool UI
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`SUB_POOL_KEY`'s strategy decides which accounts you can reach.
|
|
55
|
+
|
|
56
|
+
## 1. CLIs
|
|
57
|
+
|
|
58
|
+
### `sp-claude` — `claude` wrapper
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
sp-claude --setup # one-time interactive config wizard
|
|
62
|
+
sp-claude # start the claude REPL on a leased account
|
|
63
|
+
sp-claude "explain this" # single-prompt mode
|
|
64
|
+
sp-claude --account alice # pin to a specific account
|
|
65
|
+
sp-claude --status # show effective config and exit
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`sp-claude --setup` writes pool URL + API key to `~/.sub-pool/cli.toml`
|
|
69
|
+
at `0o600`. Subsequent invocations exec `claude` against a per-session
|
|
70
|
+
config dir that holds the leased `.credentials.json`. The persistent
|
|
71
|
+
home (`~/.sub-pool/claude-home/`) keeps your conversation history
|
|
72
|
+
across sessions and is isolated from `~/.claude/` — `sp-claude` never
|
|
73
|
+
reads or writes your real claude config.
|
|
74
|
+
|
|
75
|
+
If the leased account starts cooling (Anthropic rate-limit or quota
|
|
76
|
+
window), a background watcher swaps to a different account
|
|
77
|
+
transparently. Your running session sees one continuous `claude`
|
|
78
|
+
process; only the access_token under the hood changes.
|
|
79
|
+
|
|
80
|
+
### `sp-codex` — `codex` wrapper
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
sp-codex --setup
|
|
84
|
+
sp-codex # interactive REPL on a leased Codex account
|
|
85
|
+
sp-codex exec "summarize ." # one-shot
|
|
86
|
+
sp-codex --account codex1
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Shares `~/.sub-pool/cli.toml` with `sp-claude`. Persistent
|
|
90
|
+
`CODEX_HOME` lives at `~/.sub-pool/codex-home/`.
|
|
91
|
+
|
|
92
|
+
## 2. Python SDK
|
|
93
|
+
|
|
94
|
+
### `PooledClient` (Claude)
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import asyncio
|
|
98
|
+
from claude_agent_sdk import ClaudeAgentOptions
|
|
99
|
+
from sub_pool_client import PooledClient
|
|
100
|
+
|
|
101
|
+
async def main():
|
|
102
|
+
options = ClaudeAgentOptions(system_prompt="Be terse.")
|
|
103
|
+
async with PooledClient(options=options) as client:
|
|
104
|
+
print(f"leased {client.account} lease_id={client.lease_id}")
|
|
105
|
+
await client.query("List three prime numbers.")
|
|
106
|
+
async for msg in client.receive_response():
|
|
107
|
+
print(type(msg).__name__, "->", msg)
|
|
108
|
+
|
|
109
|
+
asyncio.run(main())
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`PooledClient` subclasses `ClaudeSDKClient`, so every option the SDK
|
|
113
|
+
accepts (hooks, MCP servers, `cwd`, `allowed_tools`,
|
|
114
|
+
`permission_mode`) works unchanged.
|
|
115
|
+
|
|
116
|
+
#### Rate-limit handling
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from claude_agent_sdk import ClaudeSDKError
|
|
120
|
+
|
|
121
|
+
async with PooledClient(options=options) as client:
|
|
122
|
+
try:
|
|
123
|
+
await client.query("...")
|
|
124
|
+
async for msg in client.receive_response():
|
|
125
|
+
...
|
|
126
|
+
except ClaudeSDKError as e:
|
|
127
|
+
if "429" in str(e) or "rate" in str(e).lower():
|
|
128
|
+
await client.report_error("RateLimit", str(e))
|
|
129
|
+
raise
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`report_error` posts to `/credentials/lease/{id}/report-error`; the
|
|
133
|
+
pool marks the account COOLING so the next lease skips it.
|
|
134
|
+
|
|
135
|
+
#### Concurrent agents
|
|
136
|
+
|
|
137
|
+
Multiple `async with PooledClient()` calls in the same process — or
|
|
138
|
+
across sibling processes — with identical routing inputs (`user_id`,
|
|
139
|
+
`required_model`) **share a single lease**. Coordination happens
|
|
140
|
+
through `~/.sub-pool/client/<hash>/` (flock + holder list). First
|
|
141
|
+
arriver leases; later arrivers refcount; last out releases. So N
|
|
142
|
+
parallel agents on one account work up to Anthropic's per-account
|
|
143
|
+
concurrency limit. Vary `user_id` (with the `sticky_user` strategy)
|
|
144
|
+
to force different accounts in parallel.
|
|
145
|
+
|
|
146
|
+
### `PooledCodexClient` (Codex)
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
import asyncio
|
|
150
|
+
from sub_pool_client import PooledCodexClient
|
|
151
|
+
|
|
152
|
+
async def main():
|
|
153
|
+
async with PooledCodexClient() as codex:
|
|
154
|
+
proc = await codex.exec(
|
|
155
|
+
"summarize this repository",
|
|
156
|
+
cwd=".",
|
|
157
|
+
model="gpt-5.5",
|
|
158
|
+
)
|
|
159
|
+
stdout, stderr = await proc.communicate()
|
|
160
|
+
print(stdout.decode())
|
|
161
|
+
|
|
162
|
+
asyncio.run(main())
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`PooledCodexClient` writes the leased (sanitized) `auth.json` into an
|
|
166
|
+
isolated `CODEX_HOME` and spawns `codex exec` against it. A
|
|
167
|
+
background poll task rotates the on-disk `auth.json` before the
|
|
168
|
+
access_token expires. On a backend error, call
|
|
169
|
+
`await codex.report_error("RateLimit", "...")` so the pool cools the
|
|
170
|
+
account.
|
|
171
|
+
|
|
172
|
+
## Pool invariants this client relies on
|
|
173
|
+
|
|
174
|
+
- The pool exclusively owns the `refresh_token` chain (both Anthropic
|
|
175
|
+
and OpenAI). Leases hand out only the access_token; the
|
|
176
|
+
`refreshToken` field in the leased credentials file is blank.
|
|
177
|
+
- Token rotation happens through `POST
|
|
178
|
+
/credentials/lease/{lease_id}/token` — a consumer crash can never
|
|
179
|
+
leak the pool's refresh state.
|
|
180
|
+
- `account_name`s come from the pool's admin config. The pool decides
|
|
181
|
+
which account fulfills each lease based on the API key's strategy.
|
|
182
|
+
|
|
183
|
+
The `sub-pool` server (admin UI, strategy reference, account
|
|
184
|
+
lifecycle) is hosted separately — point this client at whatever pool
|
|
185
|
+
URL your admin gave you via `SUB_POOL_URL` above.
|
|
186
|
+
|
|
187
|
+
## Layout under `~/.sub-pool/`
|
|
188
|
+
|
|
189
|
+
```
|
|
190
|
+
~/.sub-pool/
|
|
191
|
+
├── cli.toml # sp-claude / sp-codex shared config (0o600)
|
|
192
|
+
├── claude-home/ # sp-claude persistent CLAUDE_CONFIG_DIR
|
|
193
|
+
├── codex-home/ # sp-codex persistent CODEX_HOME
|
|
194
|
+
└── client/<hash>/ # PooledClient / PooledCodexClient
|
|
195
|
+
# cross-process lease coordination
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Override the SDK shared-dir root with `SUB_POOL_CLIENT_DIR`.
|
|
199
|
+
|
|
200
|
+
## Examples
|
|
201
|
+
|
|
202
|
+
- `examples/hello.py` — `PooledClient` end-to-end with a retry loop on 429.
|
|
203
|
+
- `examples/codex_hello.py` — `PooledCodexClient` running `codex exec`.
|
|
204
|
+
|
|
205
|
+
## License
|
|
206
|
+
|
|
207
|
+
(TBD — defer to upstream)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
sub_pool_client/__init__.py,sha256=9O-MrmhjHBKdTGhktQSVfPJ5HFh7TUZgVtbyA2LAmX0,501
|
|
2
|
+
sub_pool_client/_cli_core.py,sha256=fLc3faFWS2-ycoydV6RM1rsTRxzbI5_3k7dQpTLozVQ,19411
|
|
3
|
+
sub_pool_client/_cli_provider.py,sha256=hlVLt6S82ATd7Vszs762YVAu2yNJu9Tjb4b_qx3dc94,4906
|
|
4
|
+
sub_pool_client/_health_watcher.py,sha256=fJnMzVfjDYYz0uKop1nW3BMshKxEszGqavd26xz6xc4,2679
|
|
5
|
+
sub_pool_client/_shared.py,sha256=KivGnKPa-cPg0EQh0bApDRhmy3CAIw40QAPCBcQF3N4,10180
|
|
6
|
+
sub_pool_client/_swap.py,sha256=I9IB9KSV3PXUUuC3zrBCR1B9nn53fsRPiWmXyOd5AVs,4301
|
|
7
|
+
sub_pool_client/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
|
|
8
|
+
sub_pool_client/cli_claude.py,sha256=NZv-OHhl8oVANdeuFzu-QKZvYQ92KecuoF7IxrwANL0,2180
|
|
9
|
+
sub_pool_client/cli_codex.py,sha256=x2stJXhn55Pv4wRKD6alpHm7Ny8-h8MEmhAntcXFFuk,2295
|
|
10
|
+
sub_pool_client/client.py,sha256=GS2AQJaPSI3D7hT0EjXtfDYqc03yySZUGpOM4AUuiOI,18456
|
|
11
|
+
sub_pool_client/codex.py,sha256=Mr9zgMsn_yc9Y_na5tFHsoT5tUl8gP-itfYmLNICkwQ,14893
|
|
12
|
+
sub_pool_client/errors.py,sha256=HLcH51C_GG0mvINpHx87qyaATcXH6GSYaLLEcC2Eb84,1401
|
|
13
|
+
sub_pool_client-0.1.0.dist-info/METADATA,sha256=umveG3GkMbkqWXC9NpaQkK30QlpN40F-k6obfL2ErLs,7168
|
|
14
|
+
sub_pool_client-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
15
|
+
sub_pool_client-0.1.0.dist-info/entry_points.txt,sha256=3zb9zaZdsCVWbdRvgN6n4sfVS0Ou5wA_klOb_bfNvX0,104
|
|
16
|
+
sub_pool_client-0.1.0.dist-info/RECORD,,
|