sub-pool-client 0.12.2__tar.gz → 0.13.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.
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/PKG-INFO +1 -1
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_cli_core.py +123 -2
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_cli_provider.py +34 -1
- sub_pool_client-0.13.0/sub_pool_client/_cred_guard.py +202 -0
- sub_pool_client-0.13.0/sub_pool_client/_session_log.py +161 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_version.py +2 -2
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/.github/workflows/publish.yml +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/.gitignore +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/README.md +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/examples/codex_hello.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/examples/hello.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/meta/README.md +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/meta/pyproject.toml +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/pyproject.toml +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/__init__.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_api_proxy.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_auth_watch.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_client_id.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_harbor_common.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_health_watcher.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_shared.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_swap.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/_usage.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/cli_claude.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/cli_codex.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/cli_grok.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/cli_muse.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/client.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/codex.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/errors.py +0 -0
- {sub_pool_client-0.12.2 → sub_pool_client-0.13.0}/sub_pool_client/harbor.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sub-pool-client
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.13.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,8 +25,9 @@ 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.
|
|
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 (
|
|
32
33
|
LeaseRequestId,
|
|
@@ -710,6 +711,19 @@ async def run_session(
|
|
|
710
711
|
required_model = model_from_args(prompt_args)
|
|
711
712
|
|
|
712
713
|
pool = PoolHTTP(cfg, kind=f"sp-{provider.name}")
|
|
714
|
+
slog_holder: dict = {}
|
|
715
|
+
slog = _session_log.SessionLog(
|
|
716
|
+
_session_log.default_path(SP_ROOT, provider.name), provider.name,
|
|
717
|
+
current=slog_holder,
|
|
718
|
+
)
|
|
719
|
+
slog_token = _session_log.CURRENT.set(slog)
|
|
720
|
+
slog.start(
|
|
721
|
+
client_version=client_version(), bin_path=bin_path, args=prompt_args,
|
|
722
|
+
interactive=not any(a in ("-p", "--print") for a in prompt_args),
|
|
723
|
+
watch_output=_auth_watch.should_watch(),
|
|
724
|
+
others=_session_log.other_sessions(provider.name),
|
|
725
|
+
stripped_env=sorted(k for k in provider.bypass_env_vars if k in os.environ),
|
|
726
|
+
)
|
|
713
727
|
# Set once we hold a lease. The outer finally releases whatever it points
|
|
714
728
|
# at by then (a swap may have advanced it), however the session ends —
|
|
715
729
|
# including a failure before the child ever starts (e.g. a missing binary).
|
|
@@ -725,11 +739,18 @@ async def run_session(
|
|
|
725
739
|
)
|
|
726
740
|
except httpx.HTTPStatusError as e:
|
|
727
741
|
click.echo(_describe_http_error(e, "lease"), err=True)
|
|
742
|
+
slog.event("lease", result="failed", **_session_log.error_fields(e))
|
|
728
743
|
return 3
|
|
729
744
|
except httpx.HTTPError as e:
|
|
730
745
|
click.echo(f"[sp-{provider.name}] pool unreachable: {e}", err=True)
|
|
746
|
+
slog.event("lease", result="failed", **_session_log.error_fields(e))
|
|
731
747
|
return 3
|
|
732
748
|
current = {"lease": lease}
|
|
749
|
+
slog.current = current
|
|
750
|
+
slog.event(
|
|
751
|
+
"lease", result="ok", model=required_model,
|
|
752
|
+
expires_in_s=round(float(lease.get("token_expires_at") or 0) - time.time()),
|
|
753
|
+
)
|
|
733
754
|
if verbose:
|
|
734
755
|
log.info("leased %s (lease_id=%s)",
|
|
735
756
|
lease.get("account"), lease.get("lease_id"))
|
|
@@ -840,6 +861,8 @@ async def run_session(
|
|
|
840
861
|
swap_lock = asyncio.Lock()
|
|
841
862
|
|
|
842
863
|
async def on_swap_needed(health: dict) -> None:
|
|
864
|
+
slog.event("unhealthy", reason=_session_log.sample(
|
|
865
|
+
str(health.get("reason") or "unhealthy")), live_swap=live_swap)
|
|
843
866
|
if not live_swap:
|
|
844
867
|
# The child's credential is fixed in its env; a swap would
|
|
845
868
|
# re-point the lease while it keeps spending the old
|
|
@@ -881,9 +904,12 @@ async def run_session(
|
|
|
881
904
|
old_account, new.get("account"),
|
|
882
905
|
(health.get("reason") or "unhealthy")[:80],
|
|
883
906
|
)
|
|
907
|
+
slog.event("swap", result="ok", from_account=old_account,
|
|
908
|
+
reason=_session_log.sample(health.get("reason") or "unhealthy"))
|
|
884
909
|
except NoSwapAvailable as e:
|
|
885
910
|
if verbose:
|
|
886
911
|
log.info("swap deferred: %s", e)
|
|
912
|
+
slog.event("swap", result="deferred", message=_session_log.sample(str(e)))
|
|
887
913
|
|
|
888
914
|
# The proxy was started before the child (it needs a port to hand
|
|
889
915
|
# it), so a request can reach it before these swap helpers exist.
|
|
@@ -906,6 +932,7 @@ async def run_session(
|
|
|
906
932
|
# disk. For an interactive session this is the only recovery:
|
|
907
933
|
# its output can't be watched for 401s (see _auth_watch).
|
|
908
934
|
if token_is_stale(current["lease"], health):
|
|
935
|
+
slog.event("token_rotated_by_pool")
|
|
909
936
|
if verbose:
|
|
910
937
|
log.info("pool rotated %s's token; pulling the "
|
|
911
938
|
"current one", current["lease"].get("account"))
|
|
@@ -930,6 +957,28 @@ async def run_session(
|
|
|
930
957
|
# unit if the pool rejects the key.
|
|
931
958
|
maintenance = [refresher, watcher]
|
|
932
959
|
|
|
960
|
+
# Keeps the credential file the child reads intact; see
|
|
961
|
+
# _cred_guard. Local only, so it isn't part of `maintenance`.
|
|
962
|
+
guard: _cred_guard.CredentialGuard | None = None
|
|
963
|
+
if (provider.inspect_credentials is not None
|
|
964
|
+
and provider.credential_problem is not None):
|
|
965
|
+
def _rewrite_credentials() -> None:
|
|
966
|
+
if not session_dir.is_dir():
|
|
967
|
+
session_dir.mkdir(parents=True, exist_ok=True)
|
|
968
|
+
setup_session_dir(home_dir, session_dir, provider)
|
|
969
|
+
provider.write_credentials(
|
|
970
|
+
session_dir / provider.cred_filename, current["lease"],
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
guard = _cred_guard.CredentialGuard(
|
|
974
|
+
path=session_dir / provider.cred_filename,
|
|
975
|
+
current=current, provider_name=provider.name,
|
|
976
|
+
inspect=provider.inspect_credentials,
|
|
977
|
+
problem=provider.credential_problem,
|
|
978
|
+
rewrite=_rewrite_credentials,
|
|
979
|
+
slog=slog, interval_s=_cred_guard.INTERVAL_S,
|
|
980
|
+
)
|
|
981
|
+
|
|
933
982
|
# Output-driven auth recovery. Detection runs in the pumps (sync,
|
|
934
983
|
# non-blocking); the ACTION runs in one consumer task fed by a
|
|
935
984
|
# size-1 queue, so a burst of auth errors — which is what a dead
|
|
@@ -937,6 +986,10 @@ async def run_session(
|
|
|
937
986
|
# instead of spawning a task per line.
|
|
938
987
|
aux: list[asyncio.Task] = []
|
|
939
988
|
pumps: list[asyncio.Task] = []
|
|
989
|
+
if guard is not None:
|
|
990
|
+
aux.append(asyncio.create_task(
|
|
991
|
+
guard.run(), name=f"sp-{provider.name}-credguard",
|
|
992
|
+
))
|
|
940
993
|
if meter is not None:
|
|
941
994
|
aux.append(asyncio.create_task(
|
|
942
995
|
_poll_usage(meter), name=f"sp-{provider.name}-usage",
|
|
@@ -958,10 +1011,26 @@ async def run_session(
|
|
|
958
1011
|
)
|
|
959
1012
|
signals: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
|
|
960
1013
|
|
|
1014
|
+
blocked_hits: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
|
|
1015
|
+
|
|
961
1016
|
def _on_line(line: str) -> None:
|
|
1017
|
+
if provider.account_blocked is not None:
|
|
1018
|
+
try:
|
|
1019
|
+
blocked = provider.account_blocked(line)
|
|
1020
|
+
except Exception: # noqa: BLE001
|
|
1021
|
+
blocked = False
|
|
1022
|
+
if blocked:
|
|
1023
|
+
with suppress(asyncio.QueueFull):
|
|
1024
|
+
blocked_hits.put_nowait(line)
|
|
962
1025
|
if _auth_watch.looks_like_auth_failure(line):
|
|
1026
|
+
slog.event("auth_signal", sample=_session_log.sample(line))
|
|
963
1027
|
with suppress(asyncio.QueueFull):
|
|
964
1028
|
signals.put_nowait(line)
|
|
1029
|
+
# Not an upstream rejection — the child can't use the file
|
|
1030
|
+
# we gave it. Local fix, never the cool-and-swap ladder.
|
|
1031
|
+
if guard is not None and _cred_guard.looks_like_not_logged_in(line):
|
|
1032
|
+
slog.event("child_not_logged_in", sample=_session_log.sample(line))
|
|
1033
|
+
guard.on_child_signal("child_not_logged_in")
|
|
965
1034
|
if meter is not None:
|
|
966
1035
|
try:
|
|
967
1036
|
meter.on_line(line)
|
|
@@ -971,13 +1040,45 @@ async def run_session(
|
|
|
971
1040
|
async def _consume_signals() -> None:
|
|
972
1041
|
while True:
|
|
973
1042
|
sample = await signals.get()
|
|
1043
|
+
before = len(recovery.history)
|
|
974
1044
|
await recovery.on_signal(sample)
|
|
1045
|
+
if len(recovery.history) > before:
|
|
1046
|
+
slog.event("auth_recovery",
|
|
1047
|
+
steps=recovery.history[before:],
|
|
1048
|
+
attempts=recovery.actions)
|
|
975
1049
|
|
|
976
1050
|
maintenance.append(asyncio.create_task(
|
|
977
1051
|
_consume_signals(), name=f"sp-{provider.name}-authrecover",
|
|
978
1052
|
))
|
|
979
1053
|
aux.append(maintenance[-1])
|
|
980
1054
|
|
|
1055
|
+
async def _report_blocked() -> None:
|
|
1056
|
+
# Once per lease: the pool cools the account on the first
|
|
1057
|
+
# report, and a swap moves us to a new lease anyway.
|
|
1058
|
+
reported: set[str] = set()
|
|
1059
|
+
while True:
|
|
1060
|
+
line = await blocked_hits.get()
|
|
1061
|
+
lease_id = current["lease"]["lease_id"]
|
|
1062
|
+
if lease_id in reported:
|
|
1063
|
+
continue
|
|
1064
|
+
reported.add(lease_id)
|
|
1065
|
+
slog.event("account_blocked", sample=_session_log.sample(line))
|
|
1066
|
+
try:
|
|
1067
|
+
await pool.report_error(
|
|
1068
|
+
lease_id, ACCOUNT_VERIFICATION_CODE,
|
|
1069
|
+
line.strip()[:500])
|
|
1070
|
+
except Exception as e: # noqa: BLE001
|
|
1071
|
+
log.warning("blocked-account report failed: %s", e)
|
|
1072
|
+
await on_swap_needed({
|
|
1073
|
+
"reason": "upstream blocked the account "
|
|
1074
|
+
"(verification required)"})
|
|
1075
|
+
|
|
1076
|
+
if provider.account_blocked is not None:
|
|
1077
|
+
maintenance.append(asyncio.create_task(
|
|
1078
|
+
_report_blocked(), name=f"sp-{provider.name}-blocked",
|
|
1079
|
+
))
|
|
1080
|
+
aux.append(maintenance[-1])
|
|
1081
|
+
|
|
981
1082
|
# Upstream quota exhaustion, for providers that say so on
|
|
982
1083
|
# stderr. Reported once per lease — the account is cooled
|
|
983
1084
|
# after the first, and repeats would only re-log it — with
|
|
@@ -1011,7 +1112,11 @@ async def run_session(
|
|
|
1011
1112
|
lease_id, "RateLimit", line.strip()[:500])
|
|
1012
1113
|
except Exception as e: # noqa: BLE001
|
|
1013
1114
|
log.warning("quota report failed: %s", e)
|
|
1115
|
+
slog.event("quota_reported", result="failed",
|
|
1116
|
+
**_session_log.error_fields(e))
|
|
1014
1117
|
else:
|
|
1118
|
+
slog.event("quota_reported", result="ok",
|
|
1119
|
+
sample=_session_log.sample(line))
|
|
1015
1120
|
if verbose:
|
|
1016
1121
|
log.info("reported quota exhaustion on %s",
|
|
1017
1122
|
current["lease"].get("account"))
|
|
@@ -1038,6 +1143,7 @@ async def run_session(
|
|
|
1038
1143
|
# A revoked / expired key fails every call; retrying just
|
|
1039
1144
|
# polls a dead key forever. Report once and stop.
|
|
1040
1145
|
pool.on_key_rejected = None
|
|
1146
|
+
slog.event("key_rejected", status=status)
|
|
1041
1147
|
click.echo(
|
|
1042
1148
|
f"[sp-{provider.name}] API key rejected by the pool "
|
|
1043
1149
|
f"({status}) — stopping lease maintenance. The session "
|
|
@@ -1052,6 +1158,8 @@ async def run_session(
|
|
|
1052
1158
|
|
|
1053
1159
|
try:
|
|
1054
1160
|
exit_code = await proc.wait()
|
|
1161
|
+
slog.event("child_exit", code=exit_code,
|
|
1162
|
+
duration_s=round(time.time() - started_at, 1))
|
|
1055
1163
|
# The child can exit with bytes still in the pipe buffers.
|
|
1056
1164
|
# Let the pumps run to EOF so the caller sees every byte,
|
|
1057
1165
|
# but never hang the exit on a stuck reader.
|
|
@@ -1088,10 +1196,16 @@ async def run_session(
|
|
|
1088
1196
|
commit_session_to_home(session_dir, home_dir, provider)
|
|
1089
1197
|
shutil.rmtree(session_dir, ignore_errors=True)
|
|
1090
1198
|
return exit_code
|
|
1199
|
+
except BaseException as e:
|
|
1200
|
+
slog.event("session_error", **_session_log.error_fields(e))
|
|
1201
|
+
raise
|
|
1091
1202
|
finally:
|
|
1092
1203
|
if current is not None:
|
|
1093
1204
|
await pool.release(current["lease"]["lease_id"], usage=usage)
|
|
1205
|
+
slog.event("released", usage=None if usage is None else {
|
|
1206
|
+
k: usage.get(k) for k in ("input_tokens", "output_tokens", "model")})
|
|
1094
1207
|
await pool.aclose()
|
|
1208
|
+
_session_log.CURRENT.reset(slog_token)
|
|
1095
1209
|
|
|
1096
1210
|
|
|
1097
1211
|
def _start_usage(
|
|
@@ -1142,14 +1256,21 @@ async def _refresh_once(
|
|
|
1142
1256
|
except Exception as e: # noqa: BLE001
|
|
1143
1257
|
if verbose:
|
|
1144
1258
|
log.info("token refresh failed: %s", e)
|
|
1259
|
+
_session_log.emit("token_refresh", result="failed",
|
|
1260
|
+
**_session_log.error_fields(e))
|
|
1145
1261
|
return False
|
|
1146
1262
|
if current["lease"]["lease_id"] != old_lease_id:
|
|
1147
1263
|
if verbose:
|
|
1148
1264
|
log.info("token refresh dropped (lease swapped during refresh)")
|
|
1265
|
+
_session_log.emit("token_refresh", result="dropped_swapped")
|
|
1149
1266
|
return False
|
|
1150
1267
|
merged = {**current["lease"], **new}
|
|
1151
1268
|
current["lease"] = merged
|
|
1152
1269
|
provider.write_credentials(session_dir / provider.cred_filename, merged)
|
|
1270
|
+
_session_log.emit(
|
|
1271
|
+
"token_refresh", result="ok",
|
|
1272
|
+
expires_in_s=round(float(merged.get("token_expires_at") or 0) - time.time()),
|
|
1273
|
+
)
|
|
1153
1274
|
if verbose:
|
|
1154
1275
|
log.info("token refreshed (expires_at=%s)",
|
|
1155
1276
|
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)
|
|
@@ -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
|
|
@@ -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.
|
|
22
|
-
__version_tuple__ = version_tuple = (0,
|
|
21
|
+
__version__ = version = '0.13.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 13, 0)
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|