sub-pool-client 0.12.0__tar.gz → 0.12.2__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 (29) hide show
  1. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/PKG-INFO +1 -1
  2. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_cli_core.py +168 -18
  3. sub_pool_client-0.12.2/sub_pool_client/_harbor_common.py +114 -0
  4. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_version.py +2 -2
  5. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/cli_claude.py +16 -4
  6. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/cli_codex.py +16 -4
  7. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/cli_grok.py +16 -4
  8. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/cli_muse.py +16 -4
  9. sub_pool_client-0.12.2/sub_pool_client/harbor.py +160 -0
  10. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/.github/workflows/publish.yml +0 -0
  11. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/.gitignore +0 -0
  12. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/README.md +0 -0
  13. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/examples/codex_hello.py +0 -0
  14. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/examples/hello.py +0 -0
  15. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/meta/README.md +0 -0
  16. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/meta/pyproject.toml +0 -0
  17. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/pyproject.toml +0 -0
  18. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/__init__.py +0 -0
  19. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_api_proxy.py +0 -0
  20. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_auth_watch.py +0 -0
  21. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_cli_provider.py +0 -0
  22. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_client_id.py +0 -0
  23. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_health_watcher.py +0 -0
  24. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_shared.py +0 -0
  25. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_swap.py +0 -0
  26. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/_usage.py +0 -0
  27. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/client.py +0 -0
  28. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/sub_pool_client/codex.py +0 -0
  29. {sub_pool_client-0.12.0 → sub_pool_client-0.12.2}/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.0
3
+ Version: 0.12.2
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
@@ -45,6 +45,16 @@ log = logging.getLogger("sp")
45
45
  # state lives in subdirs named by `CliProvider.home_subdir`.
46
46
  SP_ROOT = Path.home() / ".sub-pool"
47
47
  CONFIG_PATH = SP_ROOT / "cli.toml"
48
+ DEFAULT_KEY = "default" # the name of [pool].api_key
49
+ _KEY_NAME_RE = __import__("re").compile(r"\A[A-Za-z0-9_-]{1,32}\Z")
50
+
51
+
52
+ class KeyChoiceError(Exception):
53
+ def __init__(self, name: str, available: list[str]):
54
+ self.name, self.available = name, available
55
+ super().__init__(
56
+ f"no key named {name!r} in {CONFIG_PATH} "
57
+ f"(configured: {', '.join(available) or 'none'})")
48
58
 
49
59
 
50
60
  # ============================================================ config
@@ -57,7 +67,12 @@ class Config:
57
67
 
58
68
  [pool]
59
69
  url = "https://pool.example.com"
60
- api_key = "cp-..."
70
+ api_key = "cp-..." # the key used when nothing else is chosen
71
+ default_key = "home" # optional: a name from [keys] instead
72
+
73
+ [keys] # optional named keys — one per sub-pool, say
74
+ home = "cp-..."
75
+ travel = "cp-..."
61
76
 
62
77
  [claude]
63
78
  bin = "claude" # optional, defaults to PATH lookup
@@ -69,13 +84,29 @@ class Config:
69
84
 
70
85
  Per-provider sections are optional; absent values fall back to
71
86
  the provider's `default_bin` and an empty default account.
87
+
88
+ Which key a run uses: `--key NAME`, else $SUB_POOL_KEY_NAME, else a raw
89
+ $SUB_POOL_KEY, else `default_key`, else `api_key`. The name "default"
90
+ always means `[pool].api_key`. `key_name` records the choice.
72
91
  """
73
92
 
74
93
  def __init__(self, pool_url: str, api_key: str,
75
- per_provider: dict[str, dict[str, str]] | None = None):
94
+ per_provider: dict[str, dict[str, str]] | None = None,
95
+ *, keys: dict[str, str] | None = None,
96
+ default_key: str | None = None, key_name: str = DEFAULT_KEY):
76
97
  self.pool_url = pool_url.rstrip("/")
77
- self.api_key = api_key
98
+ self.api_key = api_key # the key this run uses
78
99
  self._per_provider = per_provider or {}
100
+ self.keys = dict(keys or {}) # named keys from [keys]
101
+ self.default_key = default_key # [pool].default_key
102
+ self.key_name = key_name # which one api_key is
103
+ self._base_key = api_key # [pool].api_key, for write()
104
+
105
+ def all_keys(self) -> dict[str, str]:
106
+ """Every configured key by name, "default" being [pool].api_key."""
107
+ out = {DEFAULT_KEY: self._base_key} if self._base_key else {}
108
+ out.update(self.keys)
109
+ return out
79
110
 
80
111
  def bin_for(self, provider: CliProvider) -> str:
81
112
  return (self._per_provider.get(provider.name, {}).get("bin")
@@ -99,7 +130,7 @@ class Config:
99
130
  return existing
100
131
 
101
132
  @classmethod
102
- def load(cls) -> "Config | None":
133
+ def load(cls, key_name: str | None = None) -> "Config | None":
103
134
  """Resolve pool_url + api_key from env vars first, falling back
104
135
  to `~/.sub-pool/cli.toml`. Per-provider sections (bin paths /
105
136
  default accounts) come from the TOML only — env vars cover the
@@ -108,6 +139,7 @@ class Config:
108
139
 
109
140
  Returns None only when neither source supplies both pool_url
110
141
  AND api_key — that's the "go run --setup" signal in main().
142
+ Raises KeyChoiceError for a key name that isn't configured.
111
143
  """
112
144
  env_url = (os.environ.get("SUB_POOL_URL") or "").strip()
113
145
  env_key = (os.environ.get("SUB_POOL_KEY") or "").strip()
@@ -119,7 +151,23 @@ class Config:
119
151
 
120
152
  pool = data.get("pool") or {}
121
153
  pool_url = env_url or (pool.get("url") or "")
122
- api_key = env_key or (pool.get("api_key") or "")
154
+ base_key = str(pool.get("api_key") or "")
155
+ keys = {str(k): str(v) for k, v in (data.get("keys") or {}).items()
156
+ if isinstance(v, str) and v.strip()}
157
+ default_key = str(pool.get("default_key") or "") or None
158
+ named = {DEFAULT_KEY: base_key, **keys} if base_key else dict(keys)
159
+
160
+ chosen = key_name or (os.environ.get("SUB_POOL_KEY_NAME") or "").strip() or None
161
+ if chosen is not None:
162
+ if chosen not in named:
163
+ raise KeyChoiceError(chosen, sorted(named))
164
+ api_key, key_name = named[chosen], chosen
165
+ elif env_key:
166
+ api_key, key_name = env_key, "env"
167
+ elif default_key and default_key in named:
168
+ api_key, key_name = named[default_key], default_key
169
+ else:
170
+ api_key, key_name = base_key, DEFAULT_KEY
123
171
  if not pool_url or not api_key:
124
172
  return None
125
173
 
@@ -131,16 +179,24 @@ class Config:
131
179
  k: str(v) for k, v in section.items()
132
180
  if isinstance(v, (str, int, float))
133
181
  }
134
- return cls(pool_url=pool_url, api_key=api_key,
135
- per_provider=per_provider)
182
+ cfg = cls(pool_url=pool_url, api_key=api_key, per_provider=per_provider,
183
+ keys=keys, default_key=default_key, key_name=key_name)
184
+ cfg._base_key = base_key or (api_key if key_name == "env" else "")
185
+ return cfg
136
186
 
137
187
  def write(self) -> None:
138
188
  SP_ROOT.mkdir(parents=True, exist_ok=True)
139
189
  body = (
140
190
  "[pool]\n"
141
191
  f"url = {_toml_str(self.pool_url)}\n"
142
- f"api_key = {_toml_str(self.api_key)}\n"
192
+ f"api_key = {_toml_str(self._base_key or self.api_key)}\n"
143
193
  )
194
+ if self.default_key:
195
+ body += f"default_key = {_toml_str(self.default_key)}\n"
196
+ if self.keys:
197
+ body += "\n[keys]\n"
198
+ for name, key in self.keys.items():
199
+ body += f"{name} = {_toml_str(key)}\n"
144
200
  for name in ("claude", "codex"):
145
201
  section = self._per_provider.get(name)
146
202
  if not section:
@@ -199,19 +255,34 @@ def run_setup(provider: CliProvider) -> int:
199
255
  "bin": (existing.bin_for(provider) if existing else provider.default_bin),
200
256
  "default_account": default_account,
201
257
  }
202
- cfg = Config(pool_url=pool_url, api_key=api_key, per_provider=per_provider)
258
+ cfg = Config(pool_url=pool_url, api_key=api_key, per_provider=per_provider,
259
+ keys=existing.keys if existing else None,
260
+ default_key=existing.default_key if existing else None)
203
261
  cfg.write()
204
262
  click.echo(f"\nWrote {CONFIG_PATH}")
205
263
  return 0
206
264
 
207
265
 
208
- def run_status(provider: CliProvider) -> int:
209
- cfg = Config.load()
266
+ def _load_or_report(provider: CliProvider, key_name: str | None) -> "Config | None":
267
+ try:
268
+ cfg = Config.load(key_name)
269
+ except KeyChoiceError as e:
270
+ click.echo(f"[sp-{provider.name}] {e}", err=True)
271
+ return None
272
+ if cfg is None:
273
+ click.echo(f"No pool config — run `sp-{provider.name} --setup` first.", err=True)
274
+ return cfg
275
+
276
+
277
+ def run_status(provider: CliProvider, key_name: str | None = None) -> int:
278
+ cfg = _load_or_report(provider, key_name)
210
279
  if cfg is None:
211
- click.echo(f"No config — run `sp-{provider.name} --setup`", err=True)
212
280
  return 1
213
281
  click.echo(f"pool_url {cfg.pool_url}")
214
- click.echo(f"api_key {cfg.api_key[:12]}…")
282
+ click.echo(f"api_key {cfg.api_key[:12]}… (key: {cfg.key_name})")
283
+ others = [n for n in cfg.all_keys() if n != cfg.key_name]
284
+ if others:
285
+ click.echo(f"other keys {', '.join(others)} (pick one with --key NAME)")
215
286
  click.echo(f"provider {provider.name}")
216
287
  click.echo(f"binary {cfg.bin_for(provider)}")
217
288
  click.echo(f"default_acct {cfg.default_account_for(provider) or '(strategy)'}")
@@ -219,6 +290,88 @@ def run_status(provider: CliProvider) -> int:
219
290
  return 0
220
291
 
221
292
 
293
+ def run_add_key(provider: CliProvider, name: str) -> int:
294
+ """`sp-* --add-key NAME`: store another API key under NAME in cli.toml
295
+ (prompted, hidden), e.g. one per sub-pool. Use it with `--key NAME`."""
296
+ if not _KEY_NAME_RE.match(name) or name == DEFAULT_KEY:
297
+ click.echo("key names are 1-32 letters, digits, '-' or '_' "
298
+ f"(and not {DEFAULT_KEY!r})", err=True)
299
+ return 2
300
+ cfg = _load_or_report(provider, None)
301
+ if cfg is None:
302
+ return 1
303
+ key = click.prompt(f"API key for {name!r} (cp-...)", hide_input=True).strip()
304
+ if not key:
305
+ click.echo("empty key", err=True)
306
+ return 2
307
+ cfg.keys[name] = key
308
+ if click.confirm(f"Use {name!r} by default?", default=False):
309
+ cfg.default_key = name
310
+ cfg.write()
311
+ click.echo(f"Saved {name!r} in {CONFIG_PATH}. Use it with `sp-{provider.name} --key {name}`.")
312
+ return 0
313
+
314
+
315
+ def _whoami_lines(name: str, chosen: bool, r: httpx.Response | None, err: str | None) -> list[str]:
316
+ mark = "*" if chosen else " "
317
+ if err is not None:
318
+ return [f"{mark} {name:10} ✗ {err}"]
319
+ if r.status_code == 404:
320
+ return [f"{mark} {name:10} ? the pool is too old for --whoami"]
321
+ if r.status_code in (401, 403):
322
+ return [f"{mark} {name:10} ✗ key rejected (revoked, expired or wrong)"]
323
+ if r.status_code >= 400:
324
+ return [f"{mark} {name:10} ✗ HTTP {r.status_code}"]
325
+ d = r.json()
326
+ pool = d.get("pool") or {}
327
+ fence = ", ".join(pool.get("allowed_ips") or []) or "any address"
328
+ verdict = {None: "✓ can lease from here",
329
+ "ip": f"✗ not from this address (pool allows {fence})",
330
+ "client_version": "✗ client too old — pip install -U sub-pool-client"}
331
+ lines = [f"{mark} {name:10} {d['key']['name']!r} in sub-pool {pool.get('name')!r} — "
332
+ f"{verdict.get(d.get('blocked_by'), d.get('blocked_by'))}",
333
+ f" {'':10} new leases from: {fence}"]
334
+ return lines
335
+
336
+
337
+ async def _whoami(cfg: Config, kind: str, names: list[str]) -> list[str]:
338
+ keys = cfg.all_keys()
339
+ if cfg.key_name not in keys: # a raw $SUB_POOL_KEY
340
+ keys = {cfg.key_name: cfg.api_key, **keys}
341
+ out: list[str] = []
342
+ info: dict | None = None
343
+ async with httpx.AsyncClient(base_url=cfg.pool_url, headers=client_headers(kind),
344
+ timeout=httpx.Timeout(15.0, connect=10.0)) as c:
345
+ for name in names:
346
+ try:
347
+ r = await c.get("/credentials/whoami",
348
+ headers={"Authorization": f"Bearer {keys[name]}"})
349
+ out += _whoami_lines(name, name == cfg.key_name, r, None)
350
+ if r.status_code == 200 and info is None:
351
+ info = r.json()
352
+ except httpx.HTTPError as e:
353
+ out += _whoami_lines(name, name == cfg.key_name, None, f"pool unreachable: {e}")
354
+ if info is not None:
355
+ cl = info.get("client") or {}
356
+ out.append(f"your IP {info.get('your_ip')} client {cl.get('sent') or kind}"
357
+ + (f" minimum {cl['min_version']}" if cl.get("min_version") else ""))
358
+ return out
359
+
360
+
361
+ def run_whoami(provider: CliProvider, key_name: str | None = None) -> int:
362
+ """`sp-* --whoami`: for every configured key (or just `--key NAME`), which
363
+ sub-pool it is in, the pool's IP allowlist, and whether a new lease would
364
+ be allowed from here right now. * marks the key a plain run would use."""
365
+ cfg = _load_or_report(provider, key_name)
366
+ if cfg is None:
367
+ return 1
368
+ names = [cfg.key_name] if key_name else list(dict.fromkeys(
369
+ [cfg.key_name, *cfg.all_keys()]))
370
+ for line in asyncio.run(_whoami(cfg, f"sp-{provider.name}", names)):
371
+ click.echo(line)
372
+ return 0
373
+
374
+
222
375
  # ============================================================ session dir
223
376
 
224
377
 
@@ -531,13 +684,10 @@ async def run_session(
531
684
  account: str | None,
532
685
  bin_override: str | None,
533
686
  verbose: bool,
687
+ key_name: str | None = None,
534
688
  ) -> int:
535
- cfg = Config.load()
689
+ cfg = _load_or_report(provider, key_name)
536
690
  if cfg is None:
537
- click.echo(
538
- f"No pool config — run `sp-{provider.name} --setup` first.",
539
- err=True,
540
- )
541
691
  return 2
542
692
  try:
543
693
  check_pool_url(cfg.pool_url)
@@ -0,0 +1,114 @@
1
+ """Harbor-free helpers behind `sub_pool_client.harbor` (kept apart so they can
2
+ be tested, and imported, without the `harbor` package)."""
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shlex
8
+
9
+ VENV = "/opt/subpool-client-venv"
10
+ URL_ENV, KEY_ENV = "SUB_POOL_URL", "SUB_POOL_KEY"
11
+
12
+ _RELEASE = re.compile(r"\A\d+\.\d+\.\d+\Z")
13
+
14
+
15
+ def client_requirement(version: str | None) -> str:
16
+ """What the sandbox pip-installs. Default: this very client version, so a
17
+ trial runs the client the host was tested with; a dev / local build (no
18
+ such release on PyPI) or "latest" takes the newest release instead."""
19
+ if version in (None, ""):
20
+ from sub_pool_client._client_id import client_version
21
+ version = client_version()
22
+ if version == "latest" or not _RELEASE.match(version):
23
+ return "sub-pool-client"
24
+ return f"sub-pool-client=={version}"
25
+
26
+
27
+ def install_command(requirement: str) -> str:
28
+ """Root shell that puts sub-pool-client in VENV, whatever Python the task
29
+ image has (or lacks). Ported from harbor-hub's audit runner."""
30
+ req = shlex.quote(requirement)
31
+ return (
32
+ "set -euo pipefail; "
33
+ f'venv="{VENV}"; '
34
+ 'bootstrap_venv="/opt/subpool-bootstrap-venv"; '
35
+ 'python_bin="$(command -v python3 || command -v python || true)"; '
36
+ 'if [ -z "$python_bin" ]; then '
37
+ "if command -v apt-get >/dev/null 2>&1; then "
38
+ "apt-get update; DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-venv; "
39
+ "elif command -v apk >/dev/null 2>&1; then apk add --no-cache python3 py3-pip; "
40
+ 'else echo "Python 3 is required for sub-pool-client" >&2; exit 127; fi; '
41
+ 'python_bin="$(command -v python3 || command -v python || true)"; '
42
+ "fi; "
43
+ 'if [ ! -x "$bootstrap_venv/bin/python" ]; then '
44
+ 'if ! "$python_bin" -m venv "$bootstrap_venv"; then '
45
+ 'rm -rf "$bootstrap_venv"; '
46
+ "if command -v apt-get >/dev/null 2>&1; then "
47
+ "apt-get update; DEBIAN_FRONTEND=noninteractive apt-get install -y python3-venv; "
48
+ "elif command -v apk >/dev/null 2>&1; then apk add --no-cache py3-pip; "
49
+ 'else echo "The Python venv module is required for sub-pool-client" >&2; exit 127; fi; '
50
+ '"$python_bin" -m venv "$bootstrap_venv"; '
51
+ "fi; fi; "
52
+ # Task images may export their own site-packages via PYTHONPATH:
53
+ # isolated mode + a forced reinstall keeps uv inside this venv.
54
+ '"$bootstrap_venv/bin/python" -I -m pip install '
55
+ "--upgrade --force-reinstall --no-cache-dir uv; "
56
+ 'test -x "$bootstrap_venv/bin/uv"; '
57
+ 'UV_PYTHON_INSTALL_DIR="/opt/subpool-python" '
58
+ '"$bootstrap_venv/bin/uv" venv --allow-existing --python 3.12 "$venv"; '
59
+ f'"$bootstrap_venv/bin/uv" pip install --python "$venv/bin/python" --no-cache {req}; '
60
+ 'chmod -R a+rX "$venv"'
61
+ )
62
+
63
+
64
+ def pool_env(extra_env: dict[str, str] | None, key_name: str | None) -> dict[str, str]:
65
+ """SUB_POOL_URL / SUB_POOL_KEY for the sandbox, in order: the agent's own
66
+ extra_env (`--ae`), the named key from the host's cli.toml
67
+ (`--ak subpool_key=NAME`), the host environment, the host's default
68
+ cli.toml key. Raises ValueError when none supplies both — better at
69
+ construction than as a failed lease inside every trial."""
70
+ extra = dict(extra_env or {})
71
+ url, key = extra.get(URL_ENV), extra.get(KEY_ENV)
72
+ if not (url and key):
73
+ from sub_pool_client._cli_core import Config, KeyChoiceError
74
+ try:
75
+ cfg = Config.load(key_name) if key_name else None
76
+ except KeyChoiceError as e:
77
+ raise ValueError(str(e)) from None
78
+ if cfg is not None:
79
+ url, key = url or cfg.pool_url, key or cfg.api_key
80
+ url = url or os.environ.get(URL_ENV)
81
+ key = key or os.environ.get(KEY_ENV)
82
+ if not (url and key):
83
+ cfg = Config.load()
84
+ if cfg is not None:
85
+ url, key = url or cfg.pool_url, key or cfg.api_key
86
+ if not (url and key):
87
+ raise ValueError(
88
+ "sub-pool agent needs SUB_POOL_URL and SUB_POOL_KEY: pass them with "
89
+ "`--ae SUB_POOL_URL=… --ae SUB_POOL_KEY=…`, pick a saved key with "
90
+ "`--ak subpool_key=NAME`, export them, or run `sp-claude --setup`")
91
+ return {**extra, URL_ENV: url, KEY_ENV: key}
92
+
93
+
94
+ CLAUDE_WRAPPER = r"""#!/bin/sh
95
+ set -eu
96
+
97
+ direct="$HOME/.local/bin/claude-harbor-direct"
98
+ sp_claude="/opt/subpool-client-venv/bin/sp-claude"
99
+ harbor_sessions="${CLAUDE_CONFIG_DIR:-/logs/agent/sessions}"
100
+ pool_home="$HOME/.sub-pool/claude-home"
101
+
102
+ # Keep Harbor's session/trajectory locations visible through sp-claude's
103
+ # temporary CLAUDE_CONFIG_DIR. The OAuth credential itself stays private to
104
+ # sp-claude and is never copied into the job output.
105
+ mkdir -p "$pool_home"
106
+ for name in debug projects shell-snapshots statsig todos skills; do
107
+ mkdir -p "$harbor_sessions/$name"
108
+ if [ ! -e "$pool_home/$name" ] && [ ! -L "$pool_home/$name" ]; then
109
+ ln -s "$harbor_sessions/$name" "$pool_home/$name"
110
+ fi
111
+ done
112
+
113
+ exec "$sp_claude" --claude-bin "$direct" -- "$@"
114
+ """
@@ -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.0'
22
- __version_tuple__ = version_tuple = (0, 12, 0)
21
+ __version__ = version = '0.12.2'
22
+ __version_tuple__ = version_tuple = (0, 12, 2)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -41,7 +41,9 @@ import sys
41
41
 
42
42
  import click
43
43
 
44
- from sub_pool_client._cli_core import run_session, run_setup, run_status
44
+ from sub_pool_client._cli_core import (
45
+ run_add_key, run_session, run_setup, run_status, run_whoami,
46
+ )
45
47
  from sub_pool_client._cli_provider import CLAUDE
46
48
 
47
49
 
@@ -52,6 +54,12 @@ from sub_pool_client._cli_provider import CLAUDE
52
54
  @click.argument("claude_args", nargs=-1, type=click.UNPROCESSED)
53
55
  @click.option("--setup", is_flag=True, help="One-time pool config wizard.")
54
56
  @click.option("--status", is_flag=True, help="Show current config + exit.")
57
+ @click.option("--key", "key_name", default=None, metavar="NAME",
58
+ help="Use the API key saved under NAME in cli.toml (see --add-key).")
59
+ @click.option("--whoami", is_flag=True,
60
+ help="Show each configured key's sub-pool and whether it can lease from here.")
61
+ @click.option("--add-key", default=None, metavar="NAME",
62
+ help="Save another API key under NAME (e.g. one per sub-pool).")
55
63
  @click.option("--account", default=None,
56
64
  help="Bind to a specific account, skipping round-robin order. "
57
65
  "Subject to the api key's strategy eligibility.")
@@ -59,13 +67,17 @@ from sub_pool_client._cli_provider import CLAUDE
59
67
  help="Override path to `claude` binary.")
60
68
  @click.option("--verbose", is_flag=True,
61
69
  help="Print swap / refresh events to stderr.")
62
- def main(claude_args, setup, status, account, claude_bin, verbose) -> None:
70
+ def main(claude_args, setup, status, key_name, whoami, add_key, account, claude_bin, verbose) -> None:
63
71
  if setup:
64
72
  sys.exit(run_setup(CLAUDE))
65
73
  if status:
66
- sys.exit(run_status(CLAUDE))
74
+ sys.exit(run_status(CLAUDE, key_name))
75
+ if whoami:
76
+ sys.exit(run_whoami(CLAUDE, key_name))
77
+ if add_key:
78
+ sys.exit(run_add_key(CLAUDE, add_key))
67
79
  code = asyncio.run(run_session(
68
- CLAUDE, claude_args, account, claude_bin, verbose,
80
+ CLAUDE, claude_args, account, claude_bin, verbose, key_name,
69
81
  ))
70
82
  sys.exit(code)
71
83
 
@@ -28,7 +28,9 @@ import sys
28
28
 
29
29
  import click
30
30
 
31
- from sub_pool_client._cli_core import run_session, run_setup, run_status
31
+ from sub_pool_client._cli_core import (
32
+ run_add_key, run_session, run_setup, run_status, run_whoami,
33
+ )
32
34
  from sub_pool_client._cli_provider import CODEX
33
35
 
34
36
 
@@ -39,6 +41,12 @@ from sub_pool_client._cli_provider import CODEX
39
41
  @click.argument("codex_args", nargs=-1, type=click.UNPROCESSED)
40
42
  @click.option("--setup", is_flag=True, help="One-time pool config wizard.")
41
43
  @click.option("--status", is_flag=True, help="Show current config + exit.")
44
+ @click.option("--key", "key_name", default=None, metavar="NAME",
45
+ help="Use the API key saved under NAME in cli.toml (see --add-key).")
46
+ @click.option("--whoami", is_flag=True,
47
+ help="Show each configured key's sub-pool and whether it can lease from here.")
48
+ @click.option("--add-key", default=None, metavar="NAME",
49
+ help="Save another API key under NAME (e.g. one per sub-pool).")
42
50
  @click.option("--account", default=None,
43
51
  help="Bind to a specific Codex account, skipping round-robin "
44
52
  "order. Subject to the api key's strategy eligibility.")
@@ -46,13 +54,17 @@ from sub_pool_client._cli_provider import CODEX
46
54
  help="Override path to `codex` binary.")
47
55
  @click.option("--verbose", is_flag=True,
48
56
  help="Print swap / refresh events to stderr.")
49
- def main(codex_args, setup, status, account, codex_bin, verbose) -> None:
57
+ def main(codex_args, setup, status, key_name, whoami, add_key, account, codex_bin, verbose) -> None:
50
58
  if setup:
51
59
  sys.exit(run_setup(CODEX))
52
60
  if status:
53
- sys.exit(run_status(CODEX))
61
+ sys.exit(run_status(CODEX, key_name))
62
+ if whoami:
63
+ sys.exit(run_whoami(CODEX, key_name))
64
+ if add_key:
65
+ sys.exit(run_add_key(CODEX, add_key))
54
66
  code = asyncio.run(run_session(
55
- CODEX, codex_args, account, codex_bin, verbose,
67
+ CODEX, codex_args, account, codex_bin, verbose, key_name,
56
68
  ))
57
69
  sys.exit(code)
58
70
 
@@ -28,7 +28,9 @@ import sys
28
28
 
29
29
  import click
30
30
 
31
- from sub_pool_client._cli_core import run_session, run_setup, run_status
31
+ from sub_pool_client._cli_core import (
32
+ run_add_key, run_session, run_setup, run_status, run_whoami,
33
+ )
32
34
  from sub_pool_client._cli_provider import GROK
33
35
 
34
36
 
@@ -39,6 +41,12 @@ from sub_pool_client._cli_provider import GROK
39
41
  @click.argument("grok_args", nargs=-1, type=click.UNPROCESSED)
40
42
  @click.option("--setup", is_flag=True, help="One-time pool config wizard.")
41
43
  @click.option("--status", is_flag=True, help="Show current config + exit.")
44
+ @click.option("--key", "key_name", default=None, metavar="NAME",
45
+ help="Use the API key saved under NAME in cli.toml (see --add-key).")
46
+ @click.option("--whoami", is_flag=True,
47
+ help="Show each configured key's sub-pool and whether it can lease from here.")
48
+ @click.option("--add-key", default=None, metavar="NAME",
49
+ help="Save another API key under NAME (e.g. one per sub-pool).")
42
50
  @click.option("--account", default=None,
43
51
  help="Bind to a specific Grok account, skipping round-robin "
44
52
  "order. Subject to the api key's strategy eligibility.")
@@ -46,13 +54,17 @@ from sub_pool_client._cli_provider import GROK
46
54
  help="Override path to `grok` binary.")
47
55
  @click.option("--verbose", is_flag=True,
48
56
  help="Print swap / refresh events to stderr.")
49
- def main(grok_args, setup, status, account, grok_bin, verbose) -> None:
57
+ def main(grok_args, setup, status, key_name, whoami, add_key, account, grok_bin, verbose) -> None:
50
58
  if setup:
51
59
  sys.exit(run_setup(GROK))
52
60
  if status:
53
- sys.exit(run_status(GROK))
61
+ sys.exit(run_status(GROK, key_name))
62
+ if whoami:
63
+ sys.exit(run_whoami(GROK, key_name))
64
+ if add_key:
65
+ sys.exit(run_add_key(GROK, add_key))
54
66
  code = asyncio.run(run_session(
55
- GROK, grok_args, account, grok_bin, verbose,
67
+ GROK, grok_args, account, grok_bin, verbose, key_name,
56
68
  ))
57
69
  sys.exit(code)
58
70
 
@@ -34,7 +34,9 @@ import sys
34
34
 
35
35
  import click
36
36
 
37
- from sub_pool_client._cli_core import run_session, run_setup, run_status
37
+ from sub_pool_client._cli_core import (
38
+ run_add_key, run_session, run_setup, run_status, run_whoami,
39
+ )
38
40
  from sub_pool_client._cli_provider import MUSE
39
41
 
40
42
 
@@ -45,6 +47,12 @@ from sub_pool_client._cli_provider import MUSE
45
47
  @click.argument("muse_args", nargs=-1, type=click.UNPROCESSED)
46
48
  @click.option("--setup", is_flag=True, help="One-time pool config wizard.")
47
49
  @click.option("--status", is_flag=True, help="Show current config + exit.")
50
+ @click.option("--key", "key_name", default=None, metavar="NAME",
51
+ help="Use the API key saved under NAME in cli.toml (see --add-key).")
52
+ @click.option("--whoami", is_flag=True,
53
+ help="Show each configured key's sub-pool and whether it can lease from here.")
54
+ @click.option("--add-key", default=None, metavar="NAME",
55
+ help="Save another API key under NAME (e.g. one per sub-pool).")
48
56
  @click.option("--account", default=None,
49
57
  help="Bind to a specific Muse account, skipping round-robin "
50
58
  "order. Subject to the api key's strategy eligibility.")
@@ -52,13 +60,17 @@ from sub_pool_client._cli_provider import MUSE
52
60
  help="Override path to `muse` binary.")
53
61
  @click.option("--verbose", is_flag=True,
54
62
  help="Print lease / quota events to stderr.")
55
- def main(muse_args, setup, status, account, muse_bin, verbose) -> None:
63
+ def main(muse_args, setup, status, key_name, whoami, add_key, account, muse_bin, verbose) -> None:
56
64
  if setup:
57
65
  sys.exit(run_setup(MUSE))
58
66
  if status:
59
- sys.exit(run_status(MUSE))
67
+ sys.exit(run_status(MUSE, key_name))
68
+ if whoami:
69
+ sys.exit(run_whoami(MUSE, key_name))
70
+ if add_key:
71
+ sys.exit(run_add_key(MUSE, add_key))
60
72
  code = asyncio.run(run_session(
61
- MUSE, muse_args, account, muse_bin, verbose,
73
+ MUSE, muse_args, account, muse_bin, verbose, key_name,
62
74
  ))
63
75
  sys.exit(code)
64
76
 
@@ -0,0 +1,160 @@
1
+ """Harbor agents that run Claude Code / Codex on a live sub-pool lease.
2
+
3
+ harbor run -d <dataset> \\
4
+ --agent-import-path sub_pool_client.harbor:SubpoolClaudeCode \\
5
+ --ak subpool_key=home # optional: a named key from cli.toml
6
+
7
+ Harbor's own Claude Code / Codex agents take a static token; sub-pool tokens
8
+ are short-lived. These install `sub-pool-client` inside the trial sandbox and
9
+ put a wrapper in front of the native binary, so `sp-claude` / `sp-codex` own
10
+ the lease, token refreshes and account swaps for the agent's whole run.
11
+
12
+ The pool URL and key reach the sandbox through Harbor's agent env (`--ae`),
13
+ which Harbor redacts in its logs; see `_harbor_common.pool_env` for where they
14
+ come from when not passed. Requires the `harbor` package (you run Harbor
15
+ anyway); `import sub_pool_client` itself never needs it.
16
+
17
+ Agent kwargs (`--ak name=value`):
18
+ subpool_key a key name from the host's ~/.sub-pool/cli.toml
19
+ subpool_client_version sub-pool-client to install in the sandbox:
20
+ default = this client's version, or "latest"
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import shlex
25
+ from typing import Any
26
+
27
+ try:
28
+ from harbor.agents.installed.claude_code import ClaudeCode
29
+ from harbor.agents.installed.codex import Codex
30
+ from harbor.environments.base import BaseEnvironment
31
+ except ImportError as e: # pragma: no cover - exercised only without harbor
32
+ raise ImportError(
33
+ "sub_pool_client.harbor needs the `harbor` package: pip install harbor"
34
+ ) from e
35
+
36
+ from sub_pool_client._harbor_common import (
37
+ CLAUDE_WRAPPER,
38
+ VENV,
39
+ client_requirement,
40
+ install_command,
41
+ pool_env,
42
+ )
43
+
44
+ __all__ = ["SubpoolClaudeCode", "SubpoolCodex"]
45
+
46
+
47
+ def _pool_kwargs(kwargs: dict[str, Any]) -> tuple[dict[str, str], str]:
48
+ """Pop our own kwargs; return (extra_env with the pool credentials, the
49
+ sub-pool-client requirement for the sandbox)."""
50
+ key_name = kwargs.pop("subpool_key", None)
51
+ version = kwargs.pop("subpool_client_version", None)
52
+ env = pool_env(kwargs.pop("extra_env", None), key_name)
53
+ return env, client_requirement(version)
54
+
55
+
56
+ _DIRECT_CLAUDE = "$HOME/.local/bin/claude-harbor-direct"
57
+ _WRAPPED_CLAUDE = "$HOME/.local/bin/claude"
58
+
59
+
60
+ class SubpoolClaudeCode(ClaudeCode):
61
+ """Claude Code backed by a live sub-pool subscription-account lease."""
62
+
63
+ _INSTALL_VERSION_COMMAND = (
64
+ 'export PATH="$HOME/.local/bin:$PATH"; '
65
+ f"if test -x {_DIRECT_CLAUDE}; then {_DIRECT_CLAUDE} --version; "
66
+ "else claude --version; fi"
67
+ )
68
+
69
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
70
+ env, self._subpool_requirement = _pool_kwargs(kwargs)
71
+ super().__init__(*args, extra_env=env, **kwargs)
72
+
73
+ @staticmethod
74
+ def name() -> str:
75
+ return "subpool-claude-code"
76
+
77
+ def get_version_command(self) -> str | None:
78
+ return self._INSTALL_VERSION_COMMAND
79
+
80
+ async def install(self, environment: BaseEnvironment) -> None:
81
+ # Claude Code itself is installed exactly as Harbor's own agent does.
82
+ await super().install(environment)
83
+ await self.exec_as_root(environment, command=install_command(self._subpool_requirement))
84
+ # Keep the native binary once, then put the lease wrapper at the path
85
+ # ClaudeCode.run() invokes.
86
+ await self.exec_as_agent(environment, command=(
87
+ "set -euo pipefail; "
88
+ 'mkdir -p "$HOME/.local/bin"; '
89
+ 'export PATH="$HOME/.local/bin:$PATH"; '
90
+ # Harbor's install is a no-op when the image already ships Claude
91
+ # Code, so resolve the binary actually on PATH. This runs before
92
+ # the wrapper exists, so `command -v claude` can't be the wrapper.
93
+ f"if [ ! -e {_DIRECT_CLAUDE} ]; then "
94
+ 'real="$(command -v claude || true)"; '
95
+ 'if [ -z "$real" ]; then echo "claude binary not found on PATH" >&2; exit 127; fi; '
96
+ f'if [ "$real" = "{_WRAPPED_CLAUDE}" ]; then mv {_WRAPPED_CLAUDE} {_DIRECT_CLAUDE}; '
97
+ # Image-provided binary: link, so absolute-path callers still work.
98
+ f'else ln -s "$real" {_DIRECT_CLAUDE}; fi; '
99
+ "fi; "
100
+ f'"{VENV}/bin/python" -c \'import pathlib, sys; '
101
+ 'p = pathlib.Path.home() / ".local/bin/claude"; '
102
+ "p.write_text(sys.argv[1]); p.chmod(0o755)' "
103
+ f"{shlex.quote(CLAUDE_WRAPPER)}; "
104
+ f"{_DIRECT_CLAUDE} --version; "
105
+ f'"{VENV}/bin/sp-claude" --help >/dev/null'
106
+ ))
107
+
108
+
109
+ # The preserved codex stays next to the original: it is a Node ESM launcher
110
+ # that finds its native payload relative to its own directory.
111
+ _DIRECT_CODEX = "codex-harbor-direct"
112
+
113
+ # Resolve codex the way Codex.run() does (through nvm), rename it in place
114
+ # once, then put the wrapper at every path that could win: the nvm-resolved one
115
+ # and the /usr/local/bin symlink Harbor creates.
116
+ _CODEX_SWAP = (
117
+ "set -euo pipefail; "
118
+ "if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; "
119
+ 'real="$(command -v codex || true)"; '
120
+ 'if [ -z "$real" ]; then echo "codex binary not found on PATH" >&2; exit 127; fi; '
121
+ 'resolved="$(readlink -f "$real")"; '
122
+ 'realdir="$(dirname "$resolved")"; '
123
+ f'direct="$realdir/{_DIRECT_CODEX}"; '
124
+ 'if [ ! -e "$direct" ]; then mv "$resolved" "$direct"; chmod 755 "$direct"; fi; '
125
+ 'for target in "$real" /usr/local/bin/codex; do '
126
+ '[ -n "$target" ] || continue; '
127
+ # Not `[ … ] && continue`: under set -e that AND-list fails the script.
128
+ 'if [ "$target" = "$direct" ]; then continue; fi; '
129
+ '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"; '
133
+ "done; "
134
+ '"$direct" --version; '
135
+ f'"{VENV}/bin/sp-codex" --help >/dev/null'
136
+ )
137
+
138
+
139
+ class SubpoolCodex(Codex):
140
+ """Codex backed by a live sub-pool subscription-account lease."""
141
+
142
+ _INSTALL_VERSION_COMMAND = (
143
+ "if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex --version"
144
+ )
145
+
146
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
147
+ env, self._subpool_requirement = _pool_kwargs(kwargs)
148
+ super().__init__(*args, extra_env=env, **kwargs)
149
+
150
+ @staticmethod
151
+ def name() -> str:
152
+ return "subpool-codex"
153
+
154
+ def get_version_command(self) -> str | None:
155
+ return self._INSTALL_VERSION_COMMAND
156
+
157
+ async def install(self, environment: BaseEnvironment) -> None:
158
+ await super().install(environment)
159
+ await self.exec_as_root(environment, command=install_command(self._subpool_requirement))
160
+ await self.exec_as_root(environment, command=_CODEX_SWAP)