sub-pool-client 0.6.8__tar.gz → 0.7.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 (21) hide show
  1. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/PKG-INFO +2 -2
  2. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/pyproject.toml +1 -1
  3. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_cli_core.py +128 -1
  4. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_swap.py +7 -2
  5. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_version.py +2 -2
  6. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/cli_claude.py +13 -0
  7. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/.github/workflows/publish.yml +0 -0
  8. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/.gitignore +0 -0
  9. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/README.md +0 -0
  10. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/examples/codex_hello.py +0 -0
  11. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/examples/hello.py +0 -0
  12. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/meta/README.md +0 -0
  13. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/meta/pyproject.toml +0 -0
  14. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/__init__.py +0 -0
  15. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_cli_provider.py +0 -0
  16. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_health_watcher.py +0 -0
  17. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/_shared.py +0 -0
  18. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/cli_codex.py +0 -0
  19. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/client.py +0 -0
  20. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/codex.py +0 -0
  21. {sub_pool_client-0.6.8 → sub_pool_client-0.7.0}/sub_pool_client/errors.py +0 -0
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sub-pool-client
3
- Version: 0.6.8
3
+ Version: 0.7.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
7
7
  Requires-Python: >=3.12
8
- Requires-Dist: claude-agent-sdk>=0.1.63
8
+ Requires-Dist: claude-agent-sdk>=0.2.115
9
9
  Requires-Dist: click>=8.1
10
10
  Requires-Dist: httpx>=0.27
11
11
  Description-Content-Type: text/markdown
@@ -5,7 +5,7 @@ description = "Python client + `sp-claude` / `sp-codex` CLIs for a sub-pool cred
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
7
  dependencies = [
8
- "claude-agent-sdk>=0.1.63",
8
+ "claude-agent-sdk>=0.2.115",
9
9
  "httpx>=0.27",
10
10
  "click>=8.1",
11
11
  ]
@@ -323,12 +323,15 @@ class PoolHTTP:
323
323
 
324
324
  async def lease(self, provider: CliProvider, *,
325
325
  account: str | None = None,
326
- user_id: str | None = None) -> dict:
326
+ user_id: str | None = None,
327
+ required_model: str | None = None) -> dict:
327
328
  body: dict[str, Any] = dict(provider.lease_body_extras)
328
329
  if account:
329
330
  body["account"] = account
330
331
  if user_id:
331
332
  body["user_id"] = user_id
333
+ if required_model:
334
+ body["required_model"] = required_model
332
335
  r = await self._client.post("/credentials/lease", json=body)
333
336
  r.raise_for_status()
334
337
  return r.json()
@@ -353,6 +356,124 @@ class PoolHTTP:
353
356
  # ============================================================ session main
354
357
 
355
358
 
359
+ # `claude` flags we know take no value, so a `--model` following one is a
360
+ # real flag rather than that option's argument. Deliberately a small
361
+ # allow-list of switches people actually combine with --model, NOT an
362
+ # attempt to mirror claude's option table: an entry going stale only costs
363
+ # us a detection (safe), while a missing entry costs nothing at all.
364
+ _CLAUDE_VALUELESS_FLAGS = frozenset({
365
+ "-p", "--print", "-c", "--continue", "-r", "--resume",
366
+ "--verbose", "--debug", "--dangerously-skip-permissions",
367
+ "--no-color", "--strict-mcp-config", "--include-partial-messages",
368
+ "--replay-user-messages", "--fork-session", "--help", "-h",
369
+ "--version", "-v",
370
+ })
371
+
372
+
373
+ # `--model` values that SELECT a model rather than naming one. Verified
374
+ # against claude 2.1.220: `default` resolves to whatever the user configured,
375
+ # `best` and `opusplan` are routing modes (observed running opus-5 and
376
+ # sonnet-5 respectively), `inherit` defers to the parent session.
377
+ #
378
+ # Short names like `sonnet` / `opus` / `fable` are NOT here — those do name a
379
+ # model, and they match upstream's sub-cap display names directly.
380
+ #
381
+ # Read off one binary version, so it will drift. That's tolerable in one
382
+ # direction only: a missing alias means we forward a string no model is
383
+ # called, the pool matches nothing, and the lease goes unfiltered — the same
384
+ # safe outcome as any other miss. It would only bite if a future alias
385
+ # happened to equal the slug of a model that has a sub-cap.
386
+ _CLAUDE_MODEL_ALIASES = frozenset({
387
+ "default", "best", "inherit", "opusplan", "opus-plan", "sonnet-plan",
388
+ "builtindefault",
389
+ })
390
+
391
+
392
+ def _consumes_a_value(token: str) -> bool:
393
+ """Could `token` swallow whatever comes after it?
394
+
395
+ Unknown flags answer True — that's the conservative side. A flag written
396
+ with `=` carries its own value and cannot consume the next token, and a
397
+ non-flag (prompt text, a previous option's value) never could.
398
+ """
399
+ if not token.startswith("-"):
400
+ return False
401
+ if "=" in token:
402
+ return False
403
+ return token not in _CLAUDE_VALUELESS_FLAGS
404
+
405
+
406
+ def model_from_args(args: tuple[str, ...]) -> str | None:
407
+ """Read the model out of the passthrough args, if we can be SURE of it.
408
+
409
+ Read-only: the flag is still forwarded to the upstream CLI untouched, so
410
+ this can't change what the binary does. The pool wants it because some
411
+ models carry their own weekly sub-cap, and a lease issued without knowing
412
+ the model can land on an account whose cap is already spent.
413
+
414
+ This is NOT a reimplementation of `claude`'s argument parser. We don't
415
+ have its full option table, so some inputs are genuinely ambiguous — and
416
+ the two ways of being wrong are not equally bad:
417
+
418
+ - MISS a model -> the lease isn't filtered, so a spent account can be
419
+ handed out and 429. That is the behaviour that predates this feature,
420
+ and it self-corrects.
421
+ - INVENT a model -> the lease is filtered by something the user never
422
+ asked for, which can exclude every healthy account and turn a working
423
+ request into a 503.
424
+
425
+ So ambiguity resolves to None:
426
+
427
+ - scanning stops at `--`; everything after it is prompt text;
428
+ - a `--model` (either spelling) whose preceding token might consume it
429
+ is skipped — `--append-system-prompt --model=x` means `x` is that
430
+ option's value, not a model;
431
+ - a value starting with `-` is declined. `claude` would take it; this
432
+ is a deliberate miss on a shape nobody writes;
433
+ - alias values (`default`, `opusplan`, `inherit`) are declined: they
434
+ select a model rather than naming one, so passing them on would have
435
+ the pool match against a string no model is called.
436
+
437
+ Last occurrence wins, matching how a CLI resolves a repeated flag.
438
+ """
439
+ found: str | None = None
440
+ for i, a in enumerate(args):
441
+ if a == "--":
442
+ break
443
+ is_eq = a.startswith("--model=")
444
+ if not is_eq and a != "--model":
445
+ continue
446
+ # Same guard for both spellings. Applying it only to the bare form
447
+ # let `--append-system-prompt --model=not-a-model` invent a model —
448
+ # the unsafe direction this function exists to avoid.
449
+ if i > 0 and _consumes_a_value(args[i - 1]):
450
+ found = None
451
+ continue
452
+ if is_eq:
453
+ found = _real_model(a[len("--model="):])
454
+ continue
455
+ nxt = args[i + 1] if i + 1 < len(args) else None
456
+ found = _real_model(nxt) if (nxt and not nxt.startswith("-")) else None
457
+ return found
458
+
459
+
460
+ def _real_model(value: str | None) -> str | None:
461
+ """The value, unless it's an alias that selects rather than names.
462
+
463
+ `[1m]` / `[2m]` are context-length suffixes that attach to a model name OR
464
+ an alias — `best[1m]` runs opus-5 exactly as `best` does. The suffix is
465
+ stripped before the alias lookup, or an exact-match check waves it
466
+ through. The suffix is KEPT on the returned value: it's part of what the
467
+ user asked for, and the pool's slug matching handles `sonnet[1m]` against
468
+ a `Sonnet` cap by segment containment.
469
+ """
470
+ v = (value or "").strip()
471
+ if not v:
472
+ return None
473
+ base = v.split("[", 1)[0].strip().lower()
474
+ return None if base in _CLAUDE_MODEL_ALIASES else v
475
+
476
+
356
477
  async def run_session(
357
478
  provider: CliProvider,
358
479
  prompt_args: tuple[str, ...],
@@ -377,12 +498,17 @@ async def run_session(
377
498
  chosen_account = account or cfg.default_account_for(provider)
378
499
  home_dir = SP_ROOT / provider.home_subdir
379
500
  user_id = os.environ.get("USER") or os.environ.get("USERNAME")
501
+ # Declared once at startup: a lease is model-stable in practice, and the
502
+ # upstream CLI's own `/model` switch mid-session is out of scope (the pool
503
+ # would need a re-lease to act on it anyway).
504
+ required_model = model_from_args(prompt_args)
380
505
 
381
506
  pool = PoolHTTP(cfg)
382
507
  try:
383
508
  try:
384
509
  lease = await pool.lease(
385
510
  provider, account=chosen_account, user_id=user_id,
511
+ required_model=required_model,
386
512
  )
387
513
  except httpx.HTTPStatusError as e:
388
514
  click.echo(_describe_http_error(e, "lease"), err=True)
@@ -445,6 +571,7 @@ async def run_session(
445
571
  new = await swap_credentials(
446
572
  pool, current, session_dir, provider,
447
573
  account=chosen_account,
574
+ required_model=required_model,
448
575
  )
449
576
  # swap_credentials already advanced current["lease"]
450
577
  # (incl. token_expires_at) in its sync block; wake the
@@ -45,7 +45,7 @@ class NoSwapAvailable(Exception):
45
45
  async def swap_credentials(
46
46
  pool: "PoolHTTP", current: dict, session_dir: Path,
47
47
  provider: "CliProvider",
48
- *, account: str | None = None,
48
+ *, account: str | None = None, required_model: str | None = None,
49
49
  ) -> dict:
50
50
  """Replace the lease backing `session_dir` with a fresh one.
51
51
 
@@ -70,7 +70,12 @@ async def swap_credentials(
70
70
  """
71
71
  old_lease_id = current["lease"]["lease_id"]
72
72
  try:
73
- new_lease = await pool.lease(provider, account=account)
73
+ # Carry the session's model into the replacement lease too — swapping
74
+ # onto an account whose sub-cap for that model is spent would just
75
+ # trade one 429 for the next.
76
+ new_lease = await pool.lease(
77
+ provider, account=account, required_model=required_model,
78
+ )
74
79
  except httpx.HTTPStatusError as e:
75
80
  # 503 = strategy says no candidate (all cooling / invalid).
76
81
  # Anything else: surface as no-swap-available so the watcher
@@ -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.6.8'
22
- __version_tuple__ = version_tuple = (0, 6, 8)
21
+ __version__ = version = '0.7.0'
22
+ __version_tuple__ = version_tuple = (0, 7, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -12,6 +12,19 @@ Setup / introspection:
12
12
  sp-claude --claude-bin /path # override `claude` binary location
13
13
  sp-claude --verbose # print swap / refresh events to stderr
14
14
 
15
+ Unrecognised arguments pass straight through to `claude`, so anything
16
+ the upstream CLI accepts works here unchanged. One of them is also
17
+ *read* on the way past: `--model` is forwarded to the pool as the
18
+ lease's `required_model`, so accounts whose weekly sub-cap for that
19
+ model is already spent get skipped at pick time instead of handing you
20
+ an immediate 429. The flag still reaches `claude` untouched.
21
+
22
+ That read is conservative, not a second argument parser: where the
23
+ model can't be determined without knowing claude's option table — after
24
+ a `--`, or when `--model` might be the value of the flag before it —
25
+ nothing is declared and the lease goes unfiltered, which is simply the
26
+ behaviour from before this existed.
27
+
15
28
  While the session is alive the credentials file in `CLAUDE_CONFIG_DIR`
16
29
  is kept current — token rotations and mid-session account swaps
17
30
  happen transparently in the background.