sub-pool-client 0.12.2__tar.gz → 0.14.0__tar.gz

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.
Files changed (31) hide show
  1. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/PKG-INFO +1 -1
  2. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_cli_core.py +138 -6
  3. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_cli_provider.py +34 -1
  4. sub_pool_client-0.14.0/sub_pool_client/_cred_guard.py +202 -0
  5. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_harbor_common.py +70 -0
  6. sub_pool_client-0.14.0/sub_pool_client/_session_log.py +161 -0
  7. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_shared.py +58 -1
  8. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_version.py +2 -2
  9. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/client.py +21 -8
  10. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/codex.py +14 -8
  11. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/harbor.py +6 -3
  12. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/.github/workflows/publish.yml +0 -0
  13. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/.gitignore +0 -0
  14. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/README.md +0 -0
  15. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/examples/codex_hello.py +0 -0
  16. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/examples/hello.py +0 -0
  17. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/meta/README.md +0 -0
  18. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/meta/pyproject.toml +0 -0
  19. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/pyproject.toml +0 -0
  20. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/__init__.py +0 -0
  21. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_api_proxy.py +0 -0
  22. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_auth_watch.py +0 -0
  23. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_client_id.py +0 -0
  24. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_health_watcher.py +0 -0
  25. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_swap.py +0 -0
  26. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/_usage.py +0 -0
  27. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/cli_claude.py +0 -0
  28. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/cli_codex.py +0 -0
  29. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/cli_grok.py +0 -0
  30. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/cli_muse.py +0 -0
  31. {sub_pool_client-0.12.2 → sub_pool_client-0.14.0}/sub_pool_client/errors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sub-pool-client
3
- Version: 0.12.2
3
+ Version: 0.14.0
4
4
  Summary: Python client + `sp-claude` / `sp-codex` CLIs for a sub-pool credential broker.
5
5
  Project-URL: Homepage, https://github.com/subs-pool/sub-pool-client
6
6
  Project-URL: Repository, https://github.com/subs-pool/sub-pool-client
@@ -25,10 +25,13 @@ import click
25
25
  import httpx
26
26
 
27
27
  from sub_pool_client._client_id import client_headers
28
- from sub_pool_client import _api_proxy, _auth_watch, _usage
29
- from sub_pool_client._cli_provider import CliProvider
28
+ from sub_pool_client import _api_proxy, _auth_watch, _cred_guard, _session_log, _usage
29
+ from sub_pool_client._client_id import client_version
30
+ from sub_pool_client._cli_provider import ACCOUNT_VERIFICATION_CODE, CliProvider
30
31
  from sub_pool_client._health_watcher import HealthWatcher
31
32
  from sub_pool_client._shared import (
33
+ POOL_ENV_VARS,
34
+ without_pool_env,
32
35
  LeaseRequestId,
33
36
  check_pool_url,
34
37
  next_refresh_sleep,
@@ -172,7 +175,7 @@ class Config:
172
175
  return None
173
176
 
174
177
  per_provider: dict[str, dict[str, str]] = {}
175
- for name in ("claude", "codex"):
178
+ for name in _PROVIDER_SECTIONS:
176
179
  section = data.get(name)
177
180
  if isinstance(section, dict):
178
181
  per_provider[name] = {
@@ -197,7 +200,7 @@ class Config:
197
200
  body += "\n[keys]\n"
198
201
  for name, key in self.keys.items():
199
202
  body += f"{name} = {_toml_str(key)}\n"
200
- for name in ("claude", "codex"):
203
+ for name in _PROVIDER_SECTIONS:
201
204
  section = self._per_provider.get(name)
202
205
  if not section:
203
206
  continue
@@ -214,6 +217,12 @@ class Config:
214
217
  f.write(body)
215
218
 
216
219
 
220
+ # Every sp-* CLI's section. Listing only claude and codex here meant [grok]
221
+ # and [muse] were never read, and the next `--setup` rewrote the file without
222
+ # them.
223
+ _PROVIDER_SECTIONS = ("claude", "codex", "grok", "muse")
224
+
225
+
217
226
  def _toml_str(s: str) -> str:
218
227
  """Render `s` as a TOML literal string (no escape interpretation).
219
228
  Falls back to a basic string when `s` contains a literal `'`."""
@@ -710,6 +719,20 @@ async def run_session(
710
719
  required_model = model_from_args(prompt_args)
711
720
 
712
721
  pool = PoolHTTP(cfg, kind=f"sp-{provider.name}")
722
+ slog_holder: dict = {}
723
+ slog = _session_log.SessionLog(
724
+ _session_log.default_path(SP_ROOT, provider.name), provider.name,
725
+ current=slog_holder,
726
+ )
727
+ slog_token = _session_log.CURRENT.set(slog)
728
+ slog.start(
729
+ client_version=client_version(), bin_path=bin_path, args=prompt_args,
730
+ interactive=not any(a in ("-p", "--print") for a in prompt_args),
731
+ watch_output=_auth_watch.should_watch(),
732
+ others=_session_log.other_sessions(provider.name),
733
+ stripped_env=sorted(k for k in (*provider.bypass_env_vars, *POOL_ENV_VARS)
734
+ if k in os.environ),
735
+ )
713
736
  # Set once we hold a lease. The outer finally releases whatever it points
714
737
  # at by then (a swap may have advanced it), however the session ends —
715
738
  # including a failure before the child ever starts (e.g. a missing binary).
@@ -725,11 +748,18 @@ async def run_session(
725
748
  )
726
749
  except httpx.HTTPStatusError as e:
727
750
  click.echo(_describe_http_error(e, "lease"), err=True)
751
+ slog.event("lease", result="failed", **_session_log.error_fields(e))
728
752
  return 3
729
753
  except httpx.HTTPError as e:
730
754
  click.echo(f"[sp-{provider.name}] pool unreachable: {e}", err=True)
755
+ slog.event("lease", result="failed", **_session_log.error_fields(e))
731
756
  return 3
732
757
  current = {"lease": lease}
758
+ slog.current = current
759
+ slog.event(
760
+ "lease", result="ok", model=required_model,
761
+ expires_in_s=round(float(lease.get("token_expires_at") or 0) - time.time()),
762
+ )
733
763
  if verbose:
734
764
  log.info("leased %s (lease_id=%s)",
735
765
  lease.get("account"), lease.get("lease_id"))
@@ -745,7 +775,7 @@ async def run_session(
745
775
  session_dir / provider.cred_filename, lease,
746
776
  )
747
777
 
748
- env = os.environ.copy()
778
+ env = without_pool_env(os.environ)
749
779
  if provider.config_dir_env is not None:
750
780
  env[provider.config_dir_env] = str(session_dir)
751
781
  for k in provider.bypass_env_vars:
@@ -840,6 +870,8 @@ async def run_session(
840
870
  swap_lock = asyncio.Lock()
841
871
 
842
872
  async def on_swap_needed(health: dict) -> None:
873
+ slog.event("unhealthy", reason=_session_log.sample(
874
+ str(health.get("reason") or "unhealthy")), live_swap=live_swap)
843
875
  if not live_swap:
844
876
  # The child's credential is fixed in its env; a swap would
845
877
  # re-point the lease while it keeps spending the old
@@ -881,9 +913,12 @@ async def run_session(
881
913
  old_account, new.get("account"),
882
914
  (health.get("reason") or "unhealthy")[:80],
883
915
  )
916
+ slog.event("swap", result="ok", from_account=old_account,
917
+ reason=_session_log.sample(health.get("reason") or "unhealthy"))
884
918
  except NoSwapAvailable as e:
885
919
  if verbose:
886
920
  log.info("swap deferred: %s", e)
921
+ slog.event("swap", result="deferred", message=_session_log.sample(str(e)))
887
922
 
888
923
  # The proxy was started before the child (it needs a port to hand
889
924
  # it), so a request can reach it before these swap helpers exist.
@@ -906,6 +941,7 @@ async def run_session(
906
941
  # disk. For an interactive session this is the only recovery:
907
942
  # its output can't be watched for 401s (see _auth_watch).
908
943
  if token_is_stale(current["lease"], health):
944
+ slog.event("token_rotated_by_pool")
909
945
  if verbose:
910
946
  log.info("pool rotated %s's token; pulling the "
911
947
  "current one", current["lease"].get("account"))
@@ -930,6 +966,28 @@ async def run_session(
930
966
  # unit if the pool rejects the key.
931
967
  maintenance = [refresher, watcher]
932
968
 
969
+ # Keeps the credential file the child reads intact; see
970
+ # _cred_guard. Local only, so it isn't part of `maintenance`.
971
+ guard: _cred_guard.CredentialGuard | None = None
972
+ if (provider.inspect_credentials is not None
973
+ and provider.credential_problem is not None):
974
+ def _rewrite_credentials() -> None:
975
+ if not session_dir.is_dir():
976
+ session_dir.mkdir(parents=True, exist_ok=True)
977
+ setup_session_dir(home_dir, session_dir, provider)
978
+ provider.write_credentials(
979
+ session_dir / provider.cred_filename, current["lease"],
980
+ )
981
+
982
+ guard = _cred_guard.CredentialGuard(
983
+ path=session_dir / provider.cred_filename,
984
+ current=current, provider_name=provider.name,
985
+ inspect=provider.inspect_credentials,
986
+ problem=provider.credential_problem,
987
+ rewrite=_rewrite_credentials,
988
+ slog=slog, interval_s=_cred_guard.INTERVAL_S,
989
+ )
990
+
933
991
  # Output-driven auth recovery. Detection runs in the pumps (sync,
934
992
  # non-blocking); the ACTION runs in one consumer task fed by a
935
993
  # size-1 queue, so a burst of auth errors — which is what a dead
@@ -937,6 +995,10 @@ async def run_session(
937
995
  # instead of spawning a task per line.
938
996
  aux: list[asyncio.Task] = []
939
997
  pumps: list[asyncio.Task] = []
998
+ if guard is not None:
999
+ aux.append(asyncio.create_task(
1000
+ guard.run(), name=f"sp-{provider.name}-credguard",
1001
+ ))
940
1002
  if meter is not None:
941
1003
  aux.append(asyncio.create_task(
942
1004
  _poll_usage(meter), name=f"sp-{provider.name}-usage",
@@ -958,10 +1020,26 @@ async def run_session(
958
1020
  )
959
1021
  signals: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
960
1022
 
1023
+ blocked_hits: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
1024
+
961
1025
  def _on_line(line: str) -> None:
1026
+ if provider.account_blocked is not None:
1027
+ try:
1028
+ blocked = provider.account_blocked(line)
1029
+ except Exception: # noqa: BLE001
1030
+ blocked = False
1031
+ if blocked:
1032
+ with suppress(asyncio.QueueFull):
1033
+ blocked_hits.put_nowait(line)
962
1034
  if _auth_watch.looks_like_auth_failure(line):
1035
+ slog.event("auth_signal", sample=_session_log.sample(line))
963
1036
  with suppress(asyncio.QueueFull):
964
1037
  signals.put_nowait(line)
1038
+ # Not an upstream rejection — the child can't use the file
1039
+ # we gave it. Local fix, never the cool-and-swap ladder.
1040
+ if guard is not None and _cred_guard.looks_like_not_logged_in(line):
1041
+ slog.event("child_not_logged_in", sample=_session_log.sample(line))
1042
+ guard.on_child_signal("child_not_logged_in")
965
1043
  if meter is not None:
966
1044
  try:
967
1045
  meter.on_line(line)
@@ -971,13 +1049,45 @@ async def run_session(
971
1049
  async def _consume_signals() -> None:
972
1050
  while True:
973
1051
  sample = await signals.get()
1052
+ before = len(recovery.history)
974
1053
  await recovery.on_signal(sample)
1054
+ if len(recovery.history) > before:
1055
+ slog.event("auth_recovery",
1056
+ steps=recovery.history[before:],
1057
+ attempts=recovery.actions)
975
1058
 
976
1059
  maintenance.append(asyncio.create_task(
977
1060
  _consume_signals(), name=f"sp-{provider.name}-authrecover",
978
1061
  ))
979
1062
  aux.append(maintenance[-1])
980
1063
 
1064
+ async def _report_blocked() -> None:
1065
+ # Once per lease: the pool cools the account on the first
1066
+ # report, and a swap moves us to a new lease anyway.
1067
+ reported: set[str] = set()
1068
+ while True:
1069
+ line = await blocked_hits.get()
1070
+ lease_id = current["lease"]["lease_id"]
1071
+ if lease_id in reported:
1072
+ continue
1073
+ reported.add(lease_id)
1074
+ slog.event("account_blocked", sample=_session_log.sample(line))
1075
+ try:
1076
+ await pool.report_error(
1077
+ lease_id, ACCOUNT_VERIFICATION_CODE,
1078
+ line.strip()[:500])
1079
+ except Exception as e: # noqa: BLE001
1080
+ log.warning("blocked-account report failed: %s", e)
1081
+ await on_swap_needed({
1082
+ "reason": "upstream blocked the account "
1083
+ "(verification required)"})
1084
+
1085
+ if provider.account_blocked is not None:
1086
+ maintenance.append(asyncio.create_task(
1087
+ _report_blocked(), name=f"sp-{provider.name}-blocked",
1088
+ ))
1089
+ aux.append(maintenance[-1])
1090
+
981
1091
  # Upstream quota exhaustion, for providers that say so on
982
1092
  # stderr. Reported once per lease — the account is cooled
983
1093
  # after the first, and repeats would only re-log it — with
@@ -1011,7 +1121,11 @@ async def run_session(
1011
1121
  lease_id, "RateLimit", line.strip()[:500])
1012
1122
  except Exception as e: # noqa: BLE001
1013
1123
  log.warning("quota report failed: %s", e)
1124
+ slog.event("quota_reported", result="failed",
1125
+ **_session_log.error_fields(e))
1014
1126
  else:
1127
+ slog.event("quota_reported", result="ok",
1128
+ sample=_session_log.sample(line))
1015
1129
  if verbose:
1016
1130
  log.info("reported quota exhaustion on %s",
1017
1131
  current["lease"].get("account"))
@@ -1038,6 +1152,7 @@ async def run_session(
1038
1152
  # A revoked / expired key fails every call; retrying just
1039
1153
  # polls a dead key forever. Report once and stop.
1040
1154
  pool.on_key_rejected = None
1155
+ slog.event("key_rejected", status=status)
1041
1156
  click.echo(
1042
1157
  f"[sp-{provider.name}] API key rejected by the pool "
1043
1158
  f"({status}) — stopping lease maintenance. The session "
@@ -1052,6 +1167,8 @@ async def run_session(
1052
1167
 
1053
1168
  try:
1054
1169
  exit_code = await proc.wait()
1170
+ slog.event("child_exit", code=exit_code,
1171
+ duration_s=round(time.time() - started_at, 1))
1055
1172
  # The child can exit with bytes still in the pipe buffers.
1056
1173
  # Let the pumps run to EOF so the caller sees every byte,
1057
1174
  # but never hang the exit on a stuck reader.
@@ -1087,11 +1204,19 @@ async def run_session(
1087
1204
  with suppress(Exception):
1088
1205
  commit_session_to_home(session_dir, home_dir, provider)
1089
1206
  shutil.rmtree(session_dir, ignore_errors=True)
1090
- return exit_code
1207
+ # A child killed by signal N reports -N; exit as a shell would (128+N),
1208
+ # not sys.exit(-N) → 256-N, which reads as an ordinary failure.
1209
+ return 128 - exit_code if exit_code < 0 else exit_code
1210
+ except BaseException as e:
1211
+ slog.event("session_error", **_session_log.error_fields(e))
1212
+ raise
1091
1213
  finally:
1092
1214
  if current is not None:
1093
1215
  await pool.release(current["lease"]["lease_id"], usage=usage)
1216
+ slog.event("released", usage=None if usage is None else {
1217
+ k: usage.get(k) for k in ("input_tokens", "output_tokens", "model")})
1094
1218
  await pool.aclose()
1219
+ _session_log.CURRENT.reset(slog_token)
1095
1220
 
1096
1221
 
1097
1222
  def _start_usage(
@@ -1142,14 +1267,21 @@ async def _refresh_once(
1142
1267
  except Exception as e: # noqa: BLE001
1143
1268
  if verbose:
1144
1269
  log.info("token refresh failed: %s", e)
1270
+ _session_log.emit("token_refresh", result="failed",
1271
+ **_session_log.error_fields(e))
1145
1272
  return False
1146
1273
  if current["lease"]["lease_id"] != old_lease_id:
1147
1274
  if verbose:
1148
1275
  log.info("token refresh dropped (lease swapped during refresh)")
1276
+ _session_log.emit("token_refresh", result="dropped_swapped")
1149
1277
  return False
1150
1278
  merged = {**current["lease"], **new}
1151
1279
  current["lease"] = merged
1152
1280
  provider.write_credentials(session_dir / provider.cred_filename, merged)
1281
+ _session_log.emit(
1282
+ "token_refresh", result="ok",
1283
+ expires_in_s=round(float(merged.get("token_expires_at") or 0) - time.time()),
1284
+ )
1153
1285
  if verbose:
1154
1286
  log.info("token refreshed (expires_at=%s)",
1155
1287
  merged.get("token_expires_at"))
@@ -17,7 +17,7 @@ from dataclasses import dataclass
17
17
  from pathlib import Path
18
18
  from typing import Any, Callable
19
19
 
20
- from sub_pool_client import _usage
20
+ from sub_pool_client import _cred_guard, _usage
21
21
 
22
22
 
23
23
  def _write_claude_credentials(path: Path, lease: dict) -> None:
@@ -143,6 +143,24 @@ def _muse_quota_exhausted(line: str) -> bool:
143
143
  "rate_limit_error" in low or "quota exhausted" in low)
144
144
 
145
145
 
146
+ # What claude prints when Anthropic has stopped the account until its owner
147
+ # completes a verification check ("Your account can't receive replies from
148
+ # Claude right now. ... Anthropic Verification Portal: https://portal...").
149
+ # Mirrors sub_pool.accounts._VERIFICATION_MARKERS.
150
+ _CLAUDE_VERIFICATION_MARKERS = (
151
+ "portal.anthropic.com/verify",
152
+ "anthropic verification portal",
153
+ "can't receive replies from claude",
154
+ "can\u2019t receive replies from claude",
155
+ )
156
+ ACCOUNT_VERIFICATION_CODE = "AccountVerificationRequired"
157
+
158
+
159
+ def _claude_needs_verification(line: str) -> bool:
160
+ low = line.lower()
161
+ return any(m in low for m in _CLAUDE_VERIFICATION_MARKERS)
162
+
163
+
146
164
  def _seed_claude_home(home: Path) -> None:
147
165
  """Pre-write a minimal `.claude.json` so Claude Code's first-run
148
166
  onboarding wizard does not appear inside the leased REPL.
@@ -267,6 +285,18 @@ class CliProvider:
267
285
  # it active the session CAN swap (the proxy reads the current lease per
268
286
  # request), overriding `live_swap`.
269
287
  api_proxy: ApiProxySpec | None = None
288
+ # (credential file, lease) -> secret-free description of the file, and
289
+ # that description -> why the CLI couldn't use it (None = fine). Both set:
290
+ # the session runs a `_cred_guard.CredentialGuard` that re-writes a file
291
+ # gone wrong and logs what it found. None: not guarded.
292
+ inspect_credentials: Callable[[Path, dict], dict] | None = None
293
+ credential_problem: Callable[[dict], str | None] | None = None
294
+ # line of child output -> "upstream has blocked this account until its
295
+ # owner acts" (claude: Anthropic's verification check). On a match the
296
+ # session reports it (code ACCOUNT_VERIFICATION_CODE, once per lease) so
297
+ # the pool takes the account out of rotation, then swaps off it. Only
298
+ # seen when output is watched (see _auth_watch.should_watch).
299
+ account_blocked: Callable[[str], bool] | None = None
270
300
 
271
301
 
272
302
  CLAUDE = CliProvider(
@@ -285,6 +315,9 @@ CLAUDE = CliProvider(
285
315
  write_credentials=_write_claude_credentials,
286
316
  init_home=_seed_claude_home,
287
317
  usage=_usage.ClaudeCliUsage,
318
+ inspect_credentials=_cred_guard.inspect_claude_credentials,
319
+ credential_problem=_cred_guard.claude_credential_problem,
320
+ account_blocked=_claude_needs_verification,
288
321
  )
289
322
 
290
323
 
@@ -0,0 +1,202 @@
1
+ """Keep the leased credential file intact for the session's lifetime.
2
+
3
+ `claude` says "Not logged in · Please run /login" for exactly one family of
4
+ reasons: the credential it reads is missing, empty, unparseable, or carries
5
+ no scopes. A token that is merely expired or revoked gets a `401` instead —
6
+ that is `_auth_watch`'s job, not this module's.
7
+
8
+ We write that file atomically and never delete it while the child runs, yet
9
+ users running several sessions at once still see the message now and then,
10
+ and it has not reproduced locally. So this module does two things without
11
+ waiting for the root cause:
12
+
13
+ * **Recover.** Every `interval_s`, and right away when the child prints the
14
+ message, check the file against the lease we hold. If it is wrong, write
15
+ it again from the lease. A long-running session gets back on its feet on
16
+ its next request instead of being stuck until restart.
17
+ * **Record.** Every finding is a `cred_check` event in the session log
18
+ (`_session_log`): what the file looked like (exists, size, parses,
19
+ scopes, expiry, whether its token is the leased one — never the token
20
+ itself), what triggered the check, and what we did. A check the child
21
+ triggered is recorded even when the file was fine — that rules the file
22
+ out, which is evidence too.
23
+
24
+ Only providers that define `credential_problem` are guarded (claude today).
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import json
30
+ import logging
31
+ import time
32
+ from pathlib import Path
33
+ from typing import TYPE_CHECKING, Any, Callable
34
+
35
+ if TYPE_CHECKING:
36
+ from sub_pool_client._session_log import SessionLog
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+ INTERVAL_S = 10.0
41
+ # The only message `claude` prints for a credential it can't use at all.
42
+ _NOT_LOGGED_IN = "not logged in"
43
+ _CONTENT_TYPES = frozenset({"assistant", "user"})
44
+
45
+
46
+ def inspect_claude_credentials(path: Path, lease: dict) -> dict[str, Any]:
47
+ """What `path` holds, compared with `lease`. Never includes a secret."""
48
+ out: dict[str, Any] = {
49
+ "dir_exists": path.parent.is_dir(),
50
+ "exists": path.exists(),
51
+ "is_symlink": path.is_symlink(),
52
+ }
53
+ if not out["exists"]:
54
+ return out
55
+ try:
56
+ st = path.stat()
57
+ out["size"] = st.st_size
58
+ out["age_s"] = round(time.time() - st.st_mtime, 1)
59
+ raw = path.read_text(encoding="utf-8")
60
+ except OSError as e:
61
+ out["read_error"] = type(e).__name__
62
+ return out
63
+ try:
64
+ data = json.loads(raw)
65
+ except ValueError:
66
+ out["parses"] = False
67
+ return out
68
+ out["parses"] = True
69
+ oauth = data.get("claudeAiOauth") if isinstance(data, dict) else None
70
+ out["has_oauth"] = isinstance(oauth, dict)
71
+ if not isinstance(oauth, dict):
72
+ out["keys"] = sorted(data)[:8] if isinstance(data, dict) else type(data).__name__
73
+ return out
74
+ scopes = oauth.get("scopes")
75
+ out["scopes"] = len(scopes) if isinstance(scopes, list) else None
76
+ out["has_inference_scope"] = isinstance(scopes, list) and "user:inference" in scopes
77
+ exp = oauth.get("expiresAt")
78
+ if isinstance(exp, (int, float)):
79
+ out["expires_in_s"] = round(exp / 1000 - time.time(), 1)
80
+ out["has_token"] = bool(oauth.get("accessToken"))
81
+ out["token_matches_lease"] = oauth.get("accessToken") == lease.get("access_token")
82
+ return out
83
+
84
+
85
+ def claude_credential_problem(diag: dict[str, Any]) -> str | None:
86
+ """Why `claude` would refuse (or misuse) the file `diag` describes."""
87
+ if not diag.get("dir_exists"):
88
+ return "session_dir_missing"
89
+ if not diag.get("exists"):
90
+ return "missing"
91
+ if "read_error" in diag:
92
+ return "unreadable"
93
+ if not diag.get("size"):
94
+ return "empty"
95
+ if not diag.get("parses"):
96
+ return "unparseable"
97
+ if not diag.get("has_oauth"):
98
+ return "no_oauth_block"
99
+ if not diag.get("has_token"):
100
+ return "no_token"
101
+ if not diag.get("has_inference_scope"):
102
+ return "no_inference_scope"
103
+ if not diag.get("token_matches_lease"):
104
+ return "token_not_leased"
105
+ return None
106
+
107
+
108
+ def looks_like_not_logged_in(line: str) -> bool:
109
+ """Did the child just say it has no usable credential? Never raises."""
110
+ text = line.strip()
111
+ if not text or _NOT_LOGGED_IN not in text.lower():
112
+ return False
113
+ if text[0] == "{":
114
+ try:
115
+ payload = json.loads(text)
116
+ except ValueError:
117
+ return True
118
+ if isinstance(payload, dict):
119
+ kind = payload.get("type")
120
+ if isinstance(kind, str) and kind.lower() in _CONTENT_TYPES:
121
+ return False # the model talking about logins
122
+ return True
123
+
124
+
125
+ class CredentialGuard:
126
+ """Periodic + on-demand check-and-rewrite of one session's credential."""
127
+
128
+ def __init__(
129
+ self, *, path: Path, current: dict, provider_name: str,
130
+ inspect: Callable[[Path, dict], dict[str, Any]],
131
+ problem: Callable[[dict[str, Any]], str | None],
132
+ rewrite: Callable[[], None],
133
+ slog: "SessionLog", interval_s: float = INTERVAL_S,
134
+ ):
135
+ self.path = path
136
+ self.current = current
137
+ self.provider_name = provider_name
138
+ self._inspect = inspect
139
+ self._problem = problem
140
+ self._rewrite = rewrite
141
+ self.slog = slog
142
+ self.interval_s = interval_s
143
+ # (lease, problem, outcome) already recorded by a periodic check: one
144
+ # a rewrite can't fix (the lease itself carries no scope, say) would
145
+ # otherwise log the same line every interval for the whole session.
146
+ self._seen: set[tuple[Any, str, str]] = set()
147
+ self._last_signal = float("-inf")
148
+
149
+ def on_child_signal(self, trigger: str, *, cooldown_s: float = 5.0) -> None:
150
+ """The child said it isn't logged in: check right now, inline.
151
+
152
+ Inline rather than via the loop because `claude -p` exits right after
153
+ printing it — a deferred check would be cancelled with the session
154
+ and the evidence lost. It is one small file read. Debounced, since a
155
+ burst of failing requests prints the line once each.
156
+ """
157
+ now = time.monotonic()
158
+ if now - self._last_signal < cooldown_s:
159
+ return
160
+ self._last_signal = now
161
+ self.check(trigger)
162
+
163
+ def check(self, trigger: str = "periodic") -> str | None:
164
+ """One check; rewrites and records on a problem. Returns the problem.
165
+
166
+ Synchronous on purpose: the inspection, the rewrite and the read of
167
+ `current["lease"]` happen with no await in between, so a refresh or a
168
+ swap (which update the file and `current` together) can't interleave.
169
+ """
170
+ lease = self.current["lease"]
171
+ try:
172
+ diag = self._inspect(self.path, lease)
173
+ problem = self._problem(diag)
174
+ except Exception as e: # noqa: BLE001 — a guard must never kill a session
175
+ log.debug("credential check raised (ignored): %s", e)
176
+ return None
177
+ if problem is None and trigger == "periodic":
178
+ return None
179
+ action = "none"
180
+ if problem is not None:
181
+ try:
182
+ self._rewrite()
183
+ after = self._problem(self._inspect(self.path, lease))
184
+ action = "rewritten" if after is None else f"rewrite_still_{after}"
185
+ except Exception as e: # noqa: BLE001
186
+ action = f"rewrite_failed:{type(e).__name__}"
187
+ if trigger == "periodic" and problem is not None:
188
+ key = (lease.get("lease_id"), problem, action)
189
+ if key in self._seen:
190
+ return problem
191
+ self._seen.add(key)
192
+ self.slog.event("cred_check", trigger=trigger, problem=problem,
193
+ action=action, file=diag)
194
+ if problem is not None:
195
+ log.info("sp-%s: credential file was %s; %s", self.provider_name,
196
+ problem, action)
197
+ return problem
198
+
199
+ async def run(self) -> None:
200
+ while True:
201
+ self.check()
202
+ await asyncio.sleep(self.interval_s)
@@ -2,9 +2,11 @@
2
2
  be tested, and imported, without the `harbor` package)."""
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import os
6
7
  import re
7
8
  import shlex
9
+ from pathlib import Path
8
10
 
9
11
  VENV = "/opt/subpool-client-venv"
10
12
  URL_ENV, KEY_ENV = "SUB_POOL_URL", "SUB_POOL_KEY"
@@ -110,5 +112,73 @@ for name in debug projects shell-snapshots statsig todos skills; do
110
112
  fi
111
113
  done
112
114
 
115
+ # Harbor registers the task's MCP servers in its own .claude.json; sp-claude
116
+ # runs on the pool home's copy, so carry them over (Harbor's entries win).
117
+ if [ -f "$harbor_sessions/.claude.json" ]; then
118
+ /opt/subpool-client-venv/bin/python -m sub_pool_client._harbor_common \
119
+ merge-claude-mcp "$harbor_sessions/.claude.json" "$pool_home" || true
120
+ fi
121
+
113
122
  exec "$sp_claude" --claude-bin "$direct" -- "$@"
114
123
  """
124
+
125
+ # `__DIRECT__` is replaced with the preserved codex binary at install time.
126
+ CODEX_WRAPPER = r"""#!/bin/sh
127
+ set -eu
128
+
129
+ direct="__DIRECT__"
130
+ sp_codex="/opt/subpool-client-venv/bin/sp-codex"
131
+ harbor_home="${CODEX_HOME:-}"
132
+ pool_home="$HOME/.sub-pool/codex-home"
133
+
134
+ # sp-codex points codex at its own temporary CODEX_HOME. Link in what Harbor
135
+ # put in its CODEX_HOME — the config (MCP servers, base URL), the skills — and
136
+ # the sessions dir Harbor copies the trajectory from when the run ends. The
137
+ # leased auth.json stays private to sp-codex.
138
+ if [ -n "$harbor_home" ]; then
139
+ mkdir -p "$pool_home" "$harbor_home/sessions"
140
+ for name in config.toml skills sessions; do
141
+ if [ -e "$harbor_home/$name" ] && [ ! -e "$pool_home/$name" ] && [ ! -L "$pool_home/$name" ]; then
142
+ ln -s "$harbor_home/$name" "$pool_home/$name"
143
+ fi
144
+ done
145
+ fi
146
+
147
+ exec "$sp_codex" --codex-bin "$direct" -- "$@"
148
+ """
149
+
150
+
151
+ def merge_claude_mcp(src: Path, home: Path) -> None:
152
+ """Merge `mcpServers` from Harbor's .claude.json into the pool home's,
153
+ seeding the pool home first so onboarding state is still in place."""
154
+ from sub_pool_client._cli_provider import CLAUDE
155
+ home.mkdir(parents=True, exist_ok=True)
156
+ if CLAUDE.init_home is not None:
157
+ CLAUDE.init_home(home)
158
+ try:
159
+ theirs = json.loads(src.read_text()).get("mcpServers") or {}
160
+ except (OSError, ValueError, AttributeError):
161
+ return
162
+ if not isinstance(theirs, dict) or not theirs:
163
+ return
164
+ dst = home / ".claude.json"
165
+ try:
166
+ ours = json.loads(dst.read_text()) if dst.exists() else {}
167
+ except ValueError:
168
+ ours = {}
169
+ if not isinstance(ours, dict):
170
+ ours = {}
171
+ servers = ours.get("mcpServers") if isinstance(ours.get("mcpServers"), dict) else {}
172
+ ours["mcpServers"] = {**servers, **theirs}
173
+ tmp = dst.with_name(dst.name + ".tmp")
174
+ tmp.write_text(json.dumps(ours, indent=2))
175
+ os.replace(tmp, dst)
176
+
177
+
178
+ if __name__ == "__main__": # pragma: no cover - exercised inside the sandbox
179
+ import sys
180
+ if len(sys.argv) == 4 and sys.argv[1] == "merge-claude-mcp":
181
+ merge_claude_mcp(Path(sys.argv[2]), Path(sys.argv[3]))
182
+ else:
183
+ sys.exit("usage: python -m sub_pool_client._harbor_common "
184
+ "merge-claude-mcp SRC HOME")
@@ -0,0 +1,161 @@
1
+ """A per-machine event log of what each sp-* session did.
2
+
3
+ `-v` only helps when the user thought to pass it before the failure. This log
4
+ is always on, so "it said Not logged in an hour ago" can be answered after
5
+ the fact: one JSON line per event in `~/.sub-pool/logs/sp-<provider>.log`,
6
+ shared by every concurrent session on the machine (each line carries its
7
+ session id and pid, so they can be told apart and lined up in time).
8
+
9
+ What gets an event: the session's start (client version, platform, mode,
10
+ how many other sessions were running), the lease, every token refresh and
11
+ swap, health turns, auth signals and what the recovery did, credential-file
12
+ checks (`_cred_guard`), the child's exit and the release.
13
+
14
+ Never logged: tokens, keys, prompts, model output. A line of child output is
15
+ recorded only when a detector matched it, truncated to `SAMPLE_CHARS`.
16
+
17
+ `SUB_POOL_SESSION_LOG=0` turns it off; `SUB_POOL_SESSION_LOG=<path>` moves
18
+ it. Writes are best-effort and never raise into the session. Each line goes
19
+ out in one `write` on an O_APPEND fd, so concurrent sessions don't interleave
20
+ inside a line. Past `MAX_BYTES` the file rotates once to `.1`.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import logging
26
+ import os
27
+ import platform
28
+ import secrets
29
+ import sys
30
+ import tempfile
31
+ import time
32
+ from contextvars import ContextVar
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+ MAX_BYTES = 5 << 20
39
+ SAMPLE_CHARS = 200
40
+
41
+
42
+ # The running session's log. Set once in `run_session`; every task it spawns
43
+ # inherits it, so helpers deep in the refresh / swap paths can `emit` without
44
+ # threading a logger through signatures.
45
+ CURRENT: ContextVar["SessionLog | None"] = ContextVar("sp_session_log", default=None)
46
+
47
+
48
+ def emit(name: str, **fields: Any) -> None:
49
+ """Record an event on the current session's log, if there is one."""
50
+ slog = CURRENT.get()
51
+ if slog is not None:
52
+ slog.event(name, **fields)
53
+
54
+
55
+ def error_fields(e: BaseException) -> dict[str, Any]:
56
+ """Secret-free description of a failure: type, HTTP status, short text."""
57
+ out: dict[str, Any] = {"error": type(e).__name__}
58
+ resp = getattr(e, "response", None)
59
+ status = getattr(resp, "status_code", None)
60
+ if status is not None:
61
+ out["status"] = status
62
+ try:
63
+ out["body"] = sample(resp.text)
64
+ except Exception: # noqa: BLE001
65
+ pass
66
+ else:
67
+ out["message"] = sample(str(e))
68
+ return out
69
+
70
+
71
+ def default_path(root: Path, provider: str) -> Path | None:
72
+ raw = os.environ.get("SUB_POOL_SESSION_LOG", "").strip()
73
+ if raw.lower() in ("0", "false", "no", "off"):
74
+ return None
75
+ if raw and raw.lower() not in ("1", "true", "yes", "on"):
76
+ return Path(raw).expanduser()
77
+ return root / "logs" / f"sp-{provider}.log"
78
+
79
+
80
+ def sample(line: str) -> str:
81
+ text = line.strip()
82
+ return text if len(text) <= SAMPLE_CHARS else text[:SAMPLE_CHARS] + "…"
83
+
84
+
85
+ def other_sessions(provider: str) -> int:
86
+ """sp-<provider> session dirs alive in the temp dir right now (ours
87
+ excluded by the caller counting before it creates its own)."""
88
+ try:
89
+ return sum(1 for p in Path(tempfile.gettempdir()).glob(f"sp-{provider}-*")
90
+ if p.is_dir())
91
+ except OSError:
92
+ return -1
93
+
94
+
95
+ class SessionLog:
96
+ def __init__(self, path: Path | None, provider: str, *,
97
+ current: dict | None = None, verbose: bool = False):
98
+ self.path = path
99
+ self.provider = provider
100
+ self.session = secrets.token_hex(4)
101
+ self.current = current if current is not None else {}
102
+ self.verbose = verbose
103
+ self.started = time.monotonic()
104
+ self.events: list[dict[str, Any]] = [] # in-memory copy, for tests
105
+
106
+ def event(self, name: str, **fields: Any) -> None:
107
+ lease = self.current.get("lease") or {}
108
+ entry: dict[str, Any] = {
109
+ "ts": round(time.time(), 3),
110
+ "at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
111
+ "session": self.session, "pid": os.getpid(),
112
+ "provider": self.provider, "event": name,
113
+ "t": round(time.monotonic() - self.started, 1),
114
+ }
115
+ if lease:
116
+ entry["account"] = lease.get("account")
117
+ entry["lease_id"] = lease.get("lease_id")
118
+ entry.update(fields)
119
+ self.events.append(entry)
120
+ if self.verbose:
121
+ log.info("%s %s", name, json.dumps(fields, sort_keys=True, default=str))
122
+ if self.path is None:
123
+ return
124
+ try:
125
+ data = (json.dumps(entry, sort_keys=True, default=str) + "\n").encode()
126
+ self.path.parent.mkdir(parents=True, exist_ok=True)
127
+ try:
128
+ if self.path.stat().st_size > MAX_BYTES:
129
+ os.replace(self.path, self.path.with_name(self.path.name + ".1"))
130
+ except FileNotFoundError:
131
+ pass
132
+ fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
133
+ try:
134
+ os.write(fd, data)
135
+ finally:
136
+ os.close(fd)
137
+ except Exception as e: # noqa: BLE001 — logging must never break a session
138
+ log.debug("session log write failed: %s", e)
139
+
140
+ def start(self, *, client_version: str, bin_path: str, args: tuple[str, ...],
141
+ interactive: bool, watch_output: bool, others: int,
142
+ stripped_env: list[str]) -> None:
143
+ self.event(
144
+ "session_start",
145
+ client_version=client_version,
146
+ platform=f"{platform.system()} {platform.release()} {platform.machine()}",
147
+ python=platform.python_version(),
148
+ bin=bin_path,
149
+ # Flag names only: values can be prompts.
150
+ flags=sorted({a.split("=", 1)[0] for a in args if a.startswith("-")}),
151
+ interactive=interactive, watch_output=watch_output,
152
+ stdin_tty=_isatty(sys.stdin), stdout_tty=_isatty(sys.stdout),
153
+ other_sessions=others, stripped_env=stripped_env,
154
+ )
155
+
156
+
157
+ def _isatty(stream: Any) -> bool | None:
158
+ try:
159
+ return bool(stream.isatty())
160
+ except Exception: # noqa: BLE001
161
+ return None
@@ -100,6 +100,55 @@ def _new_request_id() -> str:
100
100
 
101
101
 
102
102
  RELEASE_ATTEMPTS = 3
103
+
104
+ # The pool credential and where it points. Never handed to a child CLI: the
105
+ # model can run `env` (in a Harbor sandbox, trivially), and the key leases
106
+ # every account in its sub-pool. The child has its own leased credential.
107
+ POOL_ENV_VARS = ("SUB_POOL_KEY", "SUB_POOL_URL", "SUB_POOL_KEY_NAME")
108
+
109
+
110
+ def error_fields(exc: BaseException | None, kinds: tuple[type, ...]) -> dict:
111
+ """The release body's error fields for `exc`, or {} when it is none of
112
+ ours to report.
113
+
114
+ Only exceptions from the pool/SDK layer (`kinds`) say anything about the
115
+ account. A caller's own exception leaving the `async with` (a ValueError,
116
+ a test assertion, a class that happens to be called RateLimitExceeded)
117
+ was being sent as the error code, and the pool classifies codes by
118
+ keyword: a shared account got cooled for a bug in someone's script.
119
+ Cancellation and Ctrl-C are a clean release, not a failure.
120
+ """
121
+ if exc is None or not isinstance(exc, kinds):
122
+ return {}
123
+ return {"error_code": type(exc).__name__, "error_message": str(exc)[:2000]}
124
+
125
+
126
+ async def shielded_cleanup(*steps: Awaitable | None) -> None:
127
+ """Run `steps` in order in their own task, so a cancellation of the
128
+ caller can't stop them half-way.
129
+
130
+ `__aexit__` runs inside the caller's cancel scope. Under anyio (or a
131
+ `TaskGroup` / `asyncio.timeout` tearing down), every await in it is
132
+ cancelled at once, so the release request never went out and the lease
133
+ sat on the account until the reaper. Shielded, the release finishes in
134
+ the background and the cancellation still propagates to the caller.
135
+ """
136
+ async def run() -> None:
137
+ for step in steps:
138
+ if step is None:
139
+ continue
140
+ try:
141
+ await step
142
+ except Exception as e: # noqa: BLE001 — one failed step mustn't skip the rest
143
+ log.warning("cleanup step failed: %s", e)
144
+
145
+ task = asyncio.ensure_future(run())
146
+ await asyncio.shield(task)
147
+
148
+
149
+ def without_pool_env(env: dict[str, str]) -> dict[str, str]:
150
+ """`env` minus POOL_ENV_VARS (a copy)."""
151
+ return {k: v for k, v in env.items() if k not in POOL_ENV_VARS}
103
152
  RELEASE_BACKOFF_S = 0.5
104
153
 
105
154
 
@@ -211,9 +260,14 @@ def dir_key(
211
260
  provider: str = "claude",
212
261
  user_id: str | None = None,
213
262
  required_model: str | None = None,
263
+ required_features: list[str] | None = None,
214
264
  ) -> str:
215
265
  """Deterministic short hash. Same inputs → same shared dir → two
216
- concurrent PooledClient instances meet."""
266
+ concurrent PooledClient instances meet.
267
+
268
+ Everything that narrows which account the pool may pick belongs here:
269
+ a client asking for features X joining a lease issued without them
270
+ would get an account the pool never checked for X."""
217
271
  parts = [
218
272
  provider or "claude",
219
273
  pool_url.rstrip("/"),
@@ -221,6 +275,9 @@ def dir_key(
221
275
  user_id or "",
222
276
  required_model or "",
223
277
  ]
278
+ if required_features:
279
+ # Appended only when set, so existing feature-less dirs keep their key.
280
+ parts.append(",".join(sorted(set(required_features))))
224
281
  digest = hashlib.sha256("|".join(parts).encode()).hexdigest()
225
282
  return digest[:24]
226
283
 
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.12.2'
22
- __version_tuple__ = version_tuple = (0, 12, 2)
21
+ __version__ = version = '0.14.0'
22
+ __version_tuple__ = version_tuple = (0, 14, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -52,6 +52,7 @@ import httpx
52
52
  from claude_agent_sdk import ( # type: ignore
53
53
  ClaudeAgentOptions,
54
54
  ClaudeSDKClient,
55
+ ClaudeSDKError,
55
56
  ResultMessage,
56
57
  )
57
58
 
@@ -59,6 +60,9 @@ from sub_pool_client._client_id import client_headers
59
60
  from sub_pool_client import _usage
60
61
  from sub_pool_client._health_watcher import HealthWatcher
61
62
  from sub_pool_client._shared import (
63
+ shielded_cleanup,
64
+ error_fields,
65
+ POOL_ENV_VARS,
62
66
  LeaseRequestId,
63
67
  check_pool_url,
64
68
  cleanup_dir,
@@ -166,6 +170,7 @@ class PooledClient(ClaudeSDKClient):
166
170
  provider="claude",
167
171
  user_id=self._user_id,
168
172
  required_model=self._required_model,
173
+ required_features=self._required_features,
169
174
  )
170
175
  await sweep_stale_dirs_once()
171
176
  self._dir = shared_dir(key)
@@ -177,6 +182,11 @@ class PooledClient(ClaudeSDKClient):
177
182
  # Any stale override would shadow .credentials.json and defeat
178
183
  # the whole shared-refresh model, so drop it explicitly.
179
184
  self._base_options.env.pop("CLAUDE_CODE_OAUTH_TOKEN", None)
185
+ # The SDK spawns claude with {**os.environ, **options.env}, so a key
186
+ # can't be removed, only blanked: the child must not see the pool key.
187
+ for k in POOL_ENV_VARS:
188
+ if k in os.environ and k not in self._base_options.env:
189
+ self._base_options.env[k] = ""
180
190
 
181
191
  try:
182
192
  ClaudeSDKClient.__init__(self, options=self._base_options)
@@ -223,10 +233,8 @@ class PooledClient(ClaudeSDKClient):
223
233
  except Exception:
224
234
  log.exception("SDK __aexit__ failed")
225
235
 
226
- await self._leave_lease(exc)
227
-
228
- if self._owned_http:
229
- await self._http.aclose()
236
+ await shielded_cleanup(self._leave_lease(exc),
237
+ self._http.aclose() if self._owned_http else None)
230
238
 
231
239
  async def receive_messages(self) -> AsyncIterator[Any]:
232
240
  """`ClaudeSDKClient.receive_messages`, noting each ResultMessage's
@@ -286,6 +294,14 @@ class PooledClient(ClaudeSDKClient):
286
294
  return
287
295
 
288
296
  # No live holders → we're the first in. Acquire lease.
297
+ if meta.lease_id:
298
+ # Every holder of the previous lease died without
299
+ # releasing it. It still counts against the account
300
+ # until the reaper ends it; release it now (best effort:
301
+ # it may be gone already).
302
+ stale, meta.lease_id = meta.lease_id, None
303
+ with contextlib.suppress(Exception):
304
+ await self._delete_lease(stale, None)
289
305
  lease = await self._post_lease(
290
306
  self._request_id_req or self._lease_rid.value,
291
307
  )
@@ -737,10 +753,7 @@ class PooledClient(ClaudeSDKClient):
737
753
  usage: dict | None = None,
738
754
  ) -> None:
739
755
  """`usage` only on the shared session's final release, never a swap's."""
740
- body: dict[str, Any] = {}
741
- if exc is not None:
742
- body["error_code"] = type(exc).__name__
743
- body["error_message"] = str(exc)[:2000]
756
+ body: dict[str, Any] = error_fields(exc, (ClaudeSDKError,))
744
757
  wire = _usage.to_wire(usage)
745
758
  if wire is not None:
746
759
  body["usage"] = wire
@@ -34,6 +34,9 @@ from sub_pool_client._client_id import client_headers
34
34
  from sub_pool_client import _usage
35
35
  from sub_pool_client._health_watcher import HealthWatcher
36
36
  from sub_pool_client._shared import (
37
+ shielded_cleanup,
38
+ error_fields,
39
+ without_pool_env,
37
40
  LeaseRequestId,
38
41
  check_pool_url,
39
42
  cleanup_dir,
@@ -125,6 +128,7 @@ class PooledCodexClient:
125
128
  provider="codex",
126
129
  user_id=self._user_id,
127
130
  required_model=self._required_model,
131
+ required_features=self._required_features,
128
132
  )
129
133
  await sweep_stale_dirs_once()
130
134
  self._dir = shared_dir(key)
@@ -156,9 +160,8 @@ class PooledCodexClient:
156
160
  except (asyncio.CancelledError, Exception):
157
161
  pass
158
162
  setattr(self, attr, None)
159
- await self._leave_lease(exc)
160
- if self._owned_http:
161
- await self._http.aclose()
163
+ await shielded_cleanup(self._leave_lease(exc),
164
+ self._http.aclose() if self._owned_http else None)
162
165
 
163
166
  @property
164
167
  def codex_home(self) -> Path:
@@ -168,7 +171,7 @@ class PooledCodexClient:
168
171
 
169
172
  @property
170
173
  def env(self) -> dict[str, str]:
171
- env = os.environ.copy()
174
+ env = without_pool_env(os.environ)
172
175
  env["CODEX_HOME"] = str(self.codex_home)
173
176
  # Avoid an ambient API key taking precedence over the leased auth.json.
174
177
  env.pop("OPENAI_API_KEY", None)
@@ -279,6 +282,12 @@ class PooledCodexClient:
279
282
  self._is_poll_leader = True
280
283
  return
281
284
 
285
+ if meta.lease_id:
286
+ # Every holder of the previous lease died without
287
+ # releasing it (see client.py): release it now.
288
+ stale, meta.lease_id = meta.lease_id, None
289
+ with contextlib.suppress(Exception):
290
+ await self._delete_lease(stale, None)
282
291
  lease = await self._post_lease(
283
292
  self._request_id_req or self._lease_rid.value,
284
293
  )
@@ -646,10 +655,7 @@ class PooledCodexClient:
646
655
  usage: dict | None = None,
647
656
  ) -> None:
648
657
  """`usage` only on the shared session's final release, never a swap's."""
649
- body: dict[str, Any] = {}
650
- if exc is not None:
651
- body["error_code"] = type(exc).__name__
652
- body["error_message"] = str(exc)[:2000]
658
+ body: dict[str, Any] = error_fields(exc, (PoolError,))
653
659
  wire = _usage.to_wire(usage)
654
660
  if wire is not None:
655
661
  body["usage"] = wire
@@ -35,6 +35,7 @@ except ImportError as e: # pragma: no cover - exercised only without harbor
35
35
 
36
36
  from sub_pool_client._harbor_common import (
37
37
  CLAUDE_WRAPPER,
38
+ CODEX_WRAPPER,
38
39
  VENV,
39
40
  client_requirement,
40
41
  install_command,
@@ -127,9 +128,11 @@ _CODEX_SWAP = (
127
128
  # Not `[ … ] && continue`: under set -e that AND-list fails the script.
128
129
  'if [ "$target" = "$direct" ]; then continue; fi; '
129
130
  'rm -f "$target"; '
130
- f"printf '#!/bin/sh\\nset -eu\\nexec {VENV}/bin/sp-codex "
131
- '--codex-bin %s -- "$@"\\n\' "$direct" > "$target"; '
132
- 'chmod 755 "$target"; '
131
+ f'"{VENV}/bin/python" -c \'import pathlib, sys; '
132
+ "p = pathlib.Path(sys.argv[1]); "
133
+ "p.write_text(sys.argv[2].replace(\"__DIRECT__\", sys.argv[3])); "
134
+ "p.chmod(0o755)' "
135
+ f'"$target" {shlex.quote(CODEX_WRAPPER)} "$direct"; '
133
136
  "done; "
134
137
  '"$direct" --version; '
135
138
  f'"{VENV}/bin/sp-codex" --help >/dev/null'