Repository navigation
feat(cli): name an upstream refusal instead of reporting the silence it causes (TASK-096) - #1823
Conversation
ca632b1 to
29a63c0
Compare
|
Required refresh — Provably content-free: Take the gate at |
|
Vera's hold (71090/71091) is addressed at Two tests added, differing in exactly one input — the refusal — so moving the conjunct reddens exactly one and its name says which side moved:
Measured with a 5-mutation ledger, not asserted. Restore is from a byte-equality-checked snapshot; the earlier ledger's
The two survivors are explained, not hidden, and the explanation is why I did not pin them: Worth saying plainly: the half that carries the traffic is the batch half, and it is now pinned on both sides of the conjunct. |
…it causes (TASK-096)
A pi seat whose model route refuses exits 0 with no assistant text, so the
wrapper logged `no wrapper-post (empty output)` — the same line a seat with
nothing to say produces. Measured cost: a 429 budget refusal read as an agent
fault for two and a half days (Kai, 2026-09-20 .. 2026-09-22; 30+ spawns).
Reproduced against a local route before writing anything, and every fixture in
the tests is a verbatim line from that run (pi 0.84.1, this host):
429 JSON body, retried 3x:
{"type":"auto_retry_end","success":false,"attempt":3,
"finalError":"429: {\"message\":\"Budget has been exceeded! …\"}"}
502 HTML body, retried 3x:
{"type":"auto_retry_end","success":false,"attempt":3,
"finalError":"502 <html><head><title>502 Bad Gateway</title></head>…"}
401 echoing the key, NOT retried (no auto_retry_end at all):
{"type":"message_end","message":{"role":"assistant","content":[],
"stopReason":"error","errorMessage":"401: {\"message\":\"Invalid API key
provided: sk-…\"}"}}
Three things the reproduction settled that the row could not:
- The separator is not fixed. `429: {…}` has a colon; `502 <html>…` does not.
A parser that required the colon would have kept the whole string as the
"body", failed to parse it as JSON, and reported the status alone with no
sign that a body had ever been seen.
- A 401 is never retried, so `auto_retry_end` does not exist for it. The
refusal read has to work off `message_end` too, or the case Vera named in
the ruling is the one case it cannot report.
- LiteLLM puts its budget text at a TOP-LEVEL `message`, not under `error`.
The ruling says "JSON `error.message`". Keeping only that would have named
the status and still hidden the budget line that motivated the row, so the
keep-list is `error.message` first, then a top-level `message`, and nothing
else. Disclosed rather than assumed — flagged to wren on the PR.
The keep-list is a keep-list, not a strip-list (Vera 70876, Wren 70877): one
named field of a parsed JSON body, truncated to 256, else the status alone.
On top of it the exact-match refusal: if the kept text contains a credential
this spawn was handed — the declared provider key, or the seat token — the
text is dropped and the status stands alone. A known value, not a guessed
shape.
The turn result now carries the refusal, and the wrapper reports it:
[inbox.batch] upstream refused 429: Budget has been exceeded! Current cost…
[inbox.batch] upstream refused 401
[inbox.batch] upstream refused 502
`grep 'upstream refused'` finds every refusal; the old line survives only for
genuine silence, which the second run-loop test pins.
No retry is added. pi's own ladder (2s/4s/8s, three attempts) has already run
by the time this line is written, and a refused route is refused on the next
attempt too.
Disclosed behaviour change: a refused turn now acks `no_action` WITH a reason
(`upstream-refused-<status>`) instead of `no_action` bare. For a human wake the
bare form is read as "the agent declined" and hands the message to one
remaining listener; nothing about the agent's choice happened here, the model
never ran. Under a route-wide refusal, declining would queue every other seat
behind the same wall.
Out of scope, named rather than implied: claude and codex already REJECT on a
non-2xx and the wrapper logs their detail, so they do not have this exit-0
hole — but their detail is an unscrubbed stderr/stdout tail and names no HTTP
status. That is a real residual and it gets its own measurement, not a
ride-along on this diff.
Evidence: cli suite 759 passed / 10 skipped / 46 suites; `eslint src` clean;
13 mutations, all RED, no survivors, each reddening the test it names.
…r (TASK-096) The release outcome keys on the PRESENCE of a reason, not its value: `outcome === 'no_action' && !turnResult?.reason` decides whether a silent human wake reaches the kernel as `declined` (one remaining listener may take it) or `completed`. Vera (71090/71091) deleted that conjunct at both sites and the full cli suite stayed green, because nothing paired a reason-bearing `no_action` with a bare one on the same path — the NO_REPLY test has no reason, and the claim-held stand-down releases nothing at all. Two tests, differing in exactly one input (the refusal), so moving the conjunct reddens exactly one and its name says which side moved: - a human broadcast refused upstream releases `completed`, and the ack carries `reason: 'upstream-refused-429'` with the status/detail; - the paired control: the same wake with no refusal still releases `declined`. Measured with a 5-mutation ledger, not asserted: - dropping the conjunct at the BATCH site (:1653) → RED on the new pair; - inverting it there → RED on the new pair and on the existing NO_REPLY decline; - mangling the reason string → RED on the two naming tests; - dropping or inverting it at the SINGLE-EVENT site (:1148) → SURVIVED, and that is explained rather than hidden: `processEvent` is reached only for `PRIVATE_RESPONSE_EVENT_TYPES` (`agent.ask`, `agent.ask.response`) or for a group with no podId, and `message.posted` — the only type the `declined` branch names — is never private. A podless event cannot hold a claim the kernel honours either, so that conjunct governs a branch its own event type cannot reach with a claim held. The routing gets restructured by TASK-099, which is where a third outcome belongs; pinning it here would pin a reachable-nothing. Test-only; no version bump (the guard watches cli/src).
7856496 to
36ba1f7
Compare
…ime scope Follow-up to Vera's 71082 on the merged #1823. Both limits are inherent to exact-match refusal rather than defects in it, so they belong in the module header where the next reader meets the rule, not in a thread where they get rediscovered. a. The match is exact and against this spawn's values only, so a credential that arrives transformed — base64 inside a proxy error, percent-encoded in a URL echo — does not match and the text is kept. Matching transformed shapes would reintroduce the class rule 1 exists to avoid. b. The keep-list can still surface someone else's secret: a third party's key relayed in an upstream error is undetectable here, because the one inventory this module has is the values it was itself handed. Scope: the reader is wired into the pi adapter only. The first draft of this paragraph claimed codex and claude share pi's silence — Vera 71177 held it, and the tree agrees with her: claude rejects on a non-zero exit and reports stdout with it (a `-p` run writes quota conditions there), and codex rejects on `turnFailedMessage` even at exit 0. So their gap is the opposite one — the text they raise is the raw tail, unscrubbed, and carries no HTTP status for the run loop to key a refusal on. That is adapter work, filed as TASK-103. Comment-only under cli/src, so the version moves 0.1.66 -> 0.1.67: the guard compares paths, and a published version mapping to two artifacts is the defect it exists to catch. cli 46 suites / 761 passed, eslint src clean.
…ime scope (#1827) Follow-up to Vera's 71082 on the merged #1823. Both limits are inherent to exact-match refusal rather than defects in it, so they belong in the module header where the next reader meets the rule, not in a thread where they get rediscovered. a. The match is exact and against this spawn's values only, so a credential that arrives transformed — base64 inside a proxy error, percent-encoded in a URL echo — does not match and the text is kept. Matching transformed shapes would reintroduce the class rule 1 exists to avoid. b. The keep-list can still surface someone else's secret: a third party's key relayed in an upstream error is undetectable here, because the one inventory this module has is the values it was itself handed. Scope: the reader is wired into the pi adapter only. The first draft of this paragraph claimed codex and claude share pi's silence — Vera 71177 held it, and the tree agrees with her: claude rejects on a non-zero exit and reports stdout with it (a `-p` run writes quota conditions there), and codex rejects on `turnFailedMessage` even at exit 0. So their gap is the opposite one — the text they raise is the raw tail, unscrubbed, and carries no HTTP status for the run loop to key a refusal on. That is adapter work, filed as TASK-103. Comment-only under cli/src, so the version moves 0.1.66 -> 0.1.67: the guard compares paths, and a published version mapping to two artifacts is the defect it exists to catch. cli 46 suites / 761 passed, eslint src clean.
…097 triage
Recut per wren 71373/71374:
- Status is no longer "open": (D) was ruled, and the split is the point — (B)
per-route on the public/anon surface is now a builder's row under this task,
(A) mount-level on /api/agents/runtime is Sam's own order, gated on the
per-token steady state being measured against the existing 120/60s and on a
runtime 429 reading as a NAMED refusal in one seat's tool path.
- Callbacks and long-polls are NOT exemptions: they carry the IP tier with the
token tier off, because a retry storm from a third party is still an IP.
Registering phase4IpRateLimit alone is exactly that shape.
- Scope of (B), measured: public/anon means no auth/token/member/scope
middleware in the registration chain with string literals stripped, so a path
like /invite/:token cannot masquerade as a guard. 9 of 200 sites qualify, one
of them a test-file app, so 8 production sites, all GET — and only 3 of those
are actionable (the OAuth redirect target, /registration-policy,
/verify-email); five are liveness/meta and stay exemption candidates.
- The 429-body requirement is written down with its gap: the existing bodies in
agentsRuntime.ts are {message, code} with no status and no named reason, so
the current shape is not enough for #1823's reader, and the name has to
separate a PLATFORM 429 from an UPSTREAM one, which is a different fact.
- Flagged for the (A) budget: the fleet's seats share one egress IP (one host,
launchd supervisor), so an IP-tier-only bucket is a FLEET-Aggregate bucket,
not a per-seat one. 3000/60s is 50/s against ~30 seats reconnecting long-polls
on the order of once per 30s, but that is headroom, not the measurement (A)
needs.
- The 78 is reconciled and it was a page, not a population: vera's query was the
alerts call without --paginate — the first 100 open alerts of all rules, 78 of
which happened to be this one; with --paginate it is 349. Her "38 in one file"
comes from the same page and is unmeasured.
Docs-only: no version slot.
…eader The two adapters report LOUDLY already — claude rejects on a non-zero exit and reports stdout with it, codex rejects on turnFailedMessage even at exit 0. What they did not do is the two things pi's refusal log learned in #1823/#1827: - the tail was raw, so a body echoing a credential this spawn was handed went into an error message. For codex's turn.failed branch that message is posted into a pod as the agent's reply; - no status was attached, so the circuit breaker keyed on regex alone against a provider that had already answered 429. scrubAdapterFailure in upstream-refusal.js is now the shared reader: a non-JSON tail is kept whole and exact-match redacted (claude's usage-limit line is prose and is the whole diagnostic value), a JSON body is reduced to one named field, and the first 4xx/5xx the tail names — at the start or mid-string, since claude joins stderr and stdout with ' | ' — is attached as error.status for classifySpawnFailure. Existing message shapes are preserved. cli 0.1.69. 10/10 mutation ledger, clean baseline, sha256 restores.
…eader (#1831) * fix(cli): the codex and claude failure tails go through the refusal reader The two adapters report LOUDLY already — claude rejects on a non-zero exit and reports stdout with it, codex rejects on turnFailedMessage even at exit 0. What they did not do is the two things pi's refusal log learned in #1823/#1827: - the tail was raw, so a body echoing a credential this spawn was handed went into an error message. For codex's turn.failed branch that message is posted into a pod as the agent's reply; - no status was attached, so the circuit breaker keyed on regex alone against a provider that had already answered 429. scrubAdapterFailure in upstream-refusal.js is now the shared reader: a non-JSON tail is kept whole and exact-match redacted (claude's usage-limit line is prose and is the whole diagnostic value), a JSON body is reduced to one named field, and the first 4xx/5xx the tail names — at the start or mid-string, since claude joins stderr and stdout with ' | ' — is attached as error.status for classifySpawnFailure. Existing message shapes are preserved. cli 0.1.69. 10/10 mutation ledger, clean baseline, sha256 restores. * fix(cli): gate the whole-tail fallback on the body SHAPE, and anchor the status to a shape Two holds from Vera on 75b5016, both correct and both the same family: a rule whose predicate collapses cases that are not alike. 1. `keptRefusalDetail` returns null for four reasons — non-JSON, a non-object JSON, no keep-listed field, and a field that echoed a handed credential — and `scrubAdapterFailure` sent all four down one fallback that emits the whole body. So the case the file's own comment says is dropped ('the status is worth keeping; the text is not') was kept, and since exact-match cannot see a TRANSFORMED shape (limit (a) in that header) a key that arrived base64'd or percent-encoded shipped — on the codex turn.failed branch, which the run loop posts as the agent's reply. The fallback is now gated on the shape being not a JSON object, which is the property that actually decides the question. 2. Reading a status mid-tail is not enough on its own: the body boundary has to move with it. A tail of `warn: retrying | 429: {json}` found the status and then handed the WHOLE joined string to the body rules, which no longer looked like a body, so the credential-echoing case fell through to 'keep it all' anyway. Finding the status and the body are now one function (M16 pins it). Also tightens statusInText: a bare three-digit scan read '500 tokens', '"max_tokens": 500' and 'retry in 500 seconds' as 500, and the classifier tests the status FIELD before the message — so a count misread as a status stands the fleet down on a refusal that never happened (Vera 71352). A status is now read only where the tail names it (status/code/HTTP) or where it opens a pipe-segment followed by a colon, which is the shape claude's stderr|stdout join produces. Ledger 16/16 red on a clean baseline; cli suite 47 suites / 776 passed. * fix(cli): read a versioned HTTP status line, and treat a JSON array as a body Vera 71359 and 71360, both measured against 993fff4 — both correct. **1. `HTTP/1.1 429 Too Many Requests` read `status: null`.** The named-shape pattern handles `HTTP 429`, but its `\W{0,4}` gap cannot reach a VERSIONED line: the `1` in `/1.1` is a word character, so `HTTP` and `429` are not within four non-word characters of each other. The single most canonical refusal shape there is classified as an unclassified runtime failure — the misclassification this whole row exists to remove. It gets its own pattern rather than a looser gap, because widening the gap would start reading `/v1/models responded 500` as a status. `HTTP/2 503` is covered too, and the shape is narrow: a path that merely looks like a version is not a status line. A status LINE names the status but its reason phrase is prose, so it marks no body boundary — the whole text stays the body and exact-match protects it, as with `HTTP 503`. **2. `isJsonObject` excluded arrays, so a JSON array tail took the prose path.** Measured: `[{"error":{"message":"boom","api_key":"..."}}]` came back whole under exact-match alone. An array is structured upstream data with fields this code does not know — exactly the case rule 1 exists for. The gate is now `isStructuredBody` (object OR array). A JSON *string* still counts as prose: `"Too many requests"` has no fields to reduce, so it keeps its wording. Version recut to 0.1.68 per Wren 71355 (main never skips a version); the #1828 cli half takes 0.1.69 when it opens, and whichever lands second rebases. Ledger 18/18 red on a clean baseline, including three new mutations aimed at these two fixes, and two mutations re-anchored after the rename (a stale anchor is reported as SURVIVED, so a ledger needs re-anchoring whenever the line it points at moves). cli suite 47 suites / 778 passed; lint:cli clean.
…097 triage
Recut per wren 71373/71374:
- Status is no longer "open": (D) was ruled, and the split is the point — (B)
per-route on the public/anon surface is now a builder's row under this task,
(A) mount-level on /api/agents/runtime is Sam's own order, gated on the
per-token steady state being measured against the existing 120/60s and on a
runtime 429 reading as a NAMED refusal in one seat's tool path.
- Callbacks and long-polls are NOT exemptions: they carry the IP tier with the
token tier off, because a retry storm from a third party is still an IP.
Registering phase4IpRateLimit alone is exactly that shape.
- Scope of (B), measured: public/anon means no auth/token/member/scope
middleware in the registration chain with string literals stripped, so a path
like /invite/:token cannot masquerade as a guard. 9 of 200 sites qualify, one
of them a test-file app, so 8 production sites, all GET — and only 3 of those
are actionable (the OAuth redirect target, /registration-policy,
/verify-email); five are liveness/meta and stay exemption candidates.
- The 429-body requirement is written down with its gap: the existing bodies in
agentsRuntime.ts are {message, code} with no status and no named reason, so
the current shape is not enough for #1823's reader, and the name has to
separate a PLATFORM 429 from an UPSTREAM one, which is a different fact.
- Flagged for the (A) budget: the fleet's seats share one egress IP (one host,
launchd supervisor), so an IP-tier-only bucket is a FLEET-Aggregate bucket,
not a per-seat one. 3000/60s is 50/s against ~30 seats reconnecting long-polls
on the order of once per 30s, but that is headroom, not the measurement (A)
needs.
- The 78 is reconciled and it was a page, not a population: vera's query was the
alerts call without --paginate — the first 100 open alerts of all rules, 78 of
which happened to be this one; with --paginate it is 349. Her "38 in one file"
comes from the same page and is unmeasured.
Docs-only: no version slot.
…K-097) (#1832) * docs(audits): triage the CodeQL js/missing-rate-limiting backlog (TASK-097) Reconciles the two disagreeing counts and separates the defect from its instances, then frames the enforcement choice for Wren + Sam. Measured at 58232e6: - 349 open alerts = 200 distinct sites in 33 files (3 of them test-file apps). The ref=refs/heads/main filter is a no-op: filtered and repo-wide both return 349, because every alert's most-recent instance is already on main. - 322 of the 349 were created in 2026-04 (3 in September) — a five-month-old backlog that re-attributes to any PR touching a shared dataflow node, which is why none of it may be dismissed per-PR. - They are TRUE POSITIVES, not indirection: walking from each flagged line back to its enclosing registration shows 0 of 200 sites carry a limiter anywhere in the chain, while the 7 phase4RateLimit routes in agentsRuntime.ts are absent from the alert set entirely. The query recognises our inline limiter shape. - The repo already owns a burn-down list for this surface: the route rate-limit guard's baseline, 232 registrations (204 limited, 0 fresh violations). - Exemption candidates are narrow and named: 3 test-file apps, 6 health/status reads, 3 third-party-triggered callbacks, 2 long-poll reads. The enforcement choice is not mine to take — a limiter on the agent-runtime family changes behaviour for every seat — so the doc ends with four options and a recommendation, plus the one count I could not reproduce (Vera's 78). Docs-only: no version slot. * docs(audits): fold wren's ruling and vera's correction into the TASK-097 triage Recut per wren 71373/71374: - Status is no longer "open": (D) was ruled, and the split is the point — (B) per-route on the public/anon surface is now a builder's row under this task, (A) mount-level on /api/agents/runtime is Sam's own order, gated on the per-token steady state being measured against the existing 120/60s and on a runtime 429 reading as a NAMED refusal in one seat's tool path. - Callbacks and long-polls are NOT exemptions: they carry the IP tier with the token tier off, because a retry storm from a third party is still an IP. Registering phase4IpRateLimit alone is exactly that shape. - Scope of (B), measured: public/anon means no auth/token/member/scope middleware in the registration chain with string literals stripped, so a path like /invite/:token cannot masquerade as a guard. 9 of 200 sites qualify, one of them a test-file app, so 8 production sites, all GET — and only 3 of those are actionable (the OAuth redirect target, /registration-policy, /verify-email); five are liveness/meta and stay exemption candidates. - The 429-body requirement is written down with its gap: the existing bodies in agentsRuntime.ts are {message, code} with no status and no named reason, so the current shape is not enough for #1823's reader, and the name has to separate a PLATFORM 429 from an UPSTREAM one, which is a different fact. - Flagged for the (A) budget: the fleet's seats share one egress IP (one host, launchd supervisor), so an IP-tier-only bucket is a FLEET-Aggregate bucket, not a per-seat one. 3000/60s is 50/s against ~30 seats reconnecting long-polls on the order of once per 30s, but that is headroom, not the measurement (A) needs. - The 78 is reconciled and it was a page, not a population: vera's query was the alerts call without --paginate — the first 100 open alerts of all rules, 78 of which happened to be this one; with --paginate it is 349. Her "38 in one file" comes from the same page and is unmeasured. Docs-only: no version slot. * docs(audits): strike the 78, carry (A)'s two constraints (TASK-097) Per wren 71383/71384/71385: - §7 closes with both figures re-run today and the explicit statement that nothing about the list narrows: 349 records, 200 sites, 33 files, and the 232-registration burn-down baseline all stand. - §6 gains the two constraints (A) inherits. The store is in-memory and the backend runs replicaCount: 1 today, so the existing 120/60s budget is coherent only because there is one replica — at >1 it multiplies per replica unless the store is shared, and nothing in the config says so. And the derived floor of 12 requests/min per seat (daemon intervalMs default 5000, agent.js:850, before claims/renewals/heartbeats/tool calls) is labelled derived from source, which is why (A) waits on the sampled req.rateLimit.used instrument rather than on the derivation. Docs-only: no version slot. * docs(audits): precondition (0), the budgets' status, the instrument's scope (TASK-097) Four changes, three of them other people's findings landing in the doc: - §6 gains the trusted-proxy precondition (0) verbatim (vera 71399, TASK-110). Both tiers assume an IP key the caller cannot choose, and cf-connecting-ip is caller-supplied, so every "per IP" figure in the doc reads as "per key the caller may be able to choose" until that row lands. - The three per-route budgets are labelled threat-model numbers (vera 71390): the ingress access log holds 5,417 requests over 24h with zero hits on /verify-email and /registration-policy, so nothing exists to confirm or contradict them. They stay. - §6 records that nothing persists a per-token rate today (vera 71378) and that the counter instrument's shape is vera's scope while the build is Kai's under TASK-109, including her quoted scope: a watermark log registered immediately after phase4RateLimit, reading req.rateLimit, emitting only at used >= RATE_LIMIT_OBSERVE_WATERMARK (default 60). - §7 credits the 78's reconciliation to vera (71371, restated 71385) rather than leaving it unattributed. Docs-only: no version slot. * docs(audits): record the instrument's final field set, tier and removal (TASK-097 §6) The §6 entry for the instrument (built as TASK-109) now records what it actually emits and what it deliberately does not: - the line: key shortened to prefix + first 12 chars, route taken from `req.route.path` (pattern only, never `req.originalUrl`), `used`, `resetInSeconds`, `replica`; `limit` and `remaining` dropped because one restates the constant 120 and the other is arithmetic on the rest; - that it measures the TOKEN tier alone, because it is mounted last and last wins in a stack, with the IP tier explicitly not observed (vera 71402, recorded rather than implied per wren 71410); - that every count is per backend replica, the store being in-memory and per-process (vera 71406); - that it is a lower bound by construction — the limiter answers the request that crosses the ceiling, so the observer never runs for it; - that the row names its own removal (vera 71402). * docs(audits): fold the probes ruling — /stats/public takes the IP tier (§5, §6) wren 71392, carried as the outstanding fold on this PR (71409/71422). The rule, stated so the next probe is decided rather than re-litigated: a probe qualifies for exemption on "does an anonymous hit do database work". health.ts (x2), pg-status.ts (x2) and docs.ts (a file read) stay exempt — a limiter on a liveness probe can be the outage. GET /stats/public runs three `countDocuments` per hit with no cache, so it does not qualify and takes the IP tier at 600/60s, beside the OAuth callback. §5's class row no longer calls the whole class an exemption candidate, and §6 lists GET /public with its budget instead of as a candidate, which moves (B)'s actionable surface from 3 routes to 4.
…t Scan has been red since #1823 (#1857) cli/__tests__/upstream-refusal.test.mjs (#1823) builds a synthetic cm_agent_ token from two repeated hex digits. It matches cm_agent_[0-9a-f]{64}, so gitleaks, which scans all of main's history, has failed every push since. A real token is 64 random hex characters, about 3.9 bits per character; the fixture is 1.1. entropy = 3.0 keeps every real token and drops the look-alikes. Proven with zricethezav/gitleaks against two controls: the old config flags a random token and the synthetic one; the new config flags the random token and not the synthetic one. Claude-Session: https://claude.ai/code/session_01HKsctA2DktPwtsEaaTdyAr Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
TASK-096 — name an upstream refusal instead of reporting the silence it causes
Row: TASK-096 · Gate: wren (structure) + vera (functional)
A pi seat whose model route refuses exits 0 with no assistant text. The wrapper therefore logged
— the same line a seat with nothing to say produces. Measured cost: a
429 Budget has been exceededread as an agent fault for two and a half days (Kai, 2026-09-20 → 2026-09-22; 30+ spawns,~52seach, twelve remedies proposed against a seat that was never broken).The reproduction, before any code
A local HTTP route answering 429 / 502-HTML / 401-echoing-the-key, and pi pointed at it through a temp
PI_CODING_AGENT_DIR. Verbatim output (pi 0.84.1, this host, 2026-09-22):429JSON body{"type":"auto_retry_end","success":false,"attempt":3,"finalError":"429: {\"message\":\"Budget has been exceeded! Current cost: 12.34, Max budget: 10.00\",\"type\":\"budget_exceeded\",\"code\":\"429\"}"}502HTML body{"type":"auto_retry_end","success":false,"attempt":3,"finalError":"502 <html><head><title>502 Bad Gateway</title></head><body>nginx</body></html>"}401echoing the key{"type":"message_end","message":{"role":"assistant","content":[],"stopReason":"error","errorMessage":"401: {\"message\":\"Invalid API key provided: sk-…\"}"}}auto_retry_endexists in the streamExit code is
0in all three. Every fixture in the tests is one of these lines, copied, not written.Three facts the reproduction settled that the row could not:
429: {…}has a colon;502 <html>…has a space. A parser that required the colon would have kept502 <html>…as the whole "body", failed to parse it as JSON, and reported the status alone with no sign a body had ever been seen.message_end, or the exact case Vera named in the ruling is the one case it cannot report.message, not undererror. The ruling says "JSONerror.message"; keeping only that would have named the status and still hidden the line that motivated this row.Pick-up for @wren: the keep-list is therefore
error.messagefirst, then a top-levelmessage, and nothing else — both are one named field of a parsed body, so the keep-list property survives, but it is one field wider than the ruling's literal wording. Called out rather than assumed.The keep-list
cli/src/lib/upstream-refusal.js:statusFromError/bodyFromError— one prefix regex, both separator forms, 4xx/5xx only. A leading4040 tokens over budgetis not a status.keptRefusalDetail(raw, { credentials })— parses the body; keeps one named string field (error.message, elsemessage), whitespace-collapsed, truncated to 256 including the ellipsis. HTML, non-JSON, a JSON body with neither field, an array, a nestedmessageobject: all keep nothing. Null rather than a partial guess, so "status alone" is a code path and not a fallback accident.provider.apiKeyEnv, defaultCOMMONLY_LITELLM_KEY) and the seat's own runtime token, snapshotted in the adapter beforewithholdRuntimeCredentialstrips the child copy.redactKnownCredentials— same exact-match rule for text kept for its whole shape; ignores values under 8 characters so ordinary prose is never corrupted.readUpstreamRefusal(stdout)—auto_retry_endis terminal and wins,message_endcovers the never-retried case, a stream with no refusal yields null.describeUpstreamRefusal—upstream refused 429: <detail>orupstream refused 429.The reporting
grep 'upstream refused'finds every refusal. The oldno wrapper-post (empty output)line is gone for this case, not merely accompanied — the second run-loop test pins that genuine silence still reads as silence. Theagent.askpath gets the same treatment (upstream refused 429 — no private response).No retry is added. pi's own ladder (three attempts, 2s/4s/8s) has already run by the time this line is written, and a refused route is refused on the next attempt too.
Disclosed behaviour change
A refused turn now acks
{ outcome: 'no_action', reason: 'upstream-refused-429', details: { status, detail? } }instead ofno_actionbare. For amessage.postedfrom a human, the bare form is read as declined and the kernel hands the message to one remaining listener. Nothing about the agent's choice happened here — the model never ran — and under a route-wide refusal, declining queues every other seat behind the same wall. Say what happened and let the event close.This is beyond the row's literal ask (the log line). Flagging it because it moves the ack, not just the log.
Out of scope, named rather than implied
claudeandcodexreject on a non-2xx and the wrapper already logs their detail — they do not have pi's exit-0 hole, so the incident this row came from is not reachable on them. But their detail is an unscrubbed stderr/stdout tail and names no HTTP status. That is a real residual on the same surface, and it gets its own measurement (what does each CLI actually print on a 4xx?) rather than a ride-along on this diff. Not claimed as covered here.Evidence
cli/__tests__/upstream-refusal.test.mjs— 21 tests. Every refusal fixture is a verbatim measured line.cli/__tests__/adapters.pi.test.mjs— 4 added: 429 resolves with status + kept body; 401 echoing the key yieldsdetail: nulland the key appears nowhere in what the turn returns; HTML 502 yieldsdetail: null; a genuinely empty turn still reportsupstream: null.cli/__tests__/run-loop.test.mjs— 2 added: the log line is present,no wrapper-postis absent, the ack carries the reason; and an empty turn with no refusal still logsno wrapper-post (empty output)and acks bareno_action.cd cli && npx eslint srcclean.cli/package.json→ 0.1.66, version line only./tmp/kai096-mutate.py): the credential refusal, themessagefallback, the colon-only separator, themessage_endpath, theauto_retry_endprecedence, the redaction length floor, the truncation, the seat token in the credential list, the status in the log clause, the adapter's read, the adapter's credential hand-off, the wrapper's log branch, the wrapper's ack reason.One mutation from the first pass was discarded as not a test: removing the
continue;after theauto_retry_endblock is a no-op, because the next branch testsevent?.type === 'message_end'and this event is not one. Replaced with one that actually disables the branch. Left in the ledger's comments so the next reader does not re-derive it.A harness keeper this cost, now recorded
The first mutation run ended with
git checkout -- clito restore the tree. That reverts tracked files to HEAD, which on a branch carrying uncommitted work destroys the work, not the mutation: it ate this PR'spi.jsandagent.jsedits mid-run (re-applied; the diff above is the second pass). The ledger now snapshots every file it touches before the first mutation and restores from that snapshot, and asserts byte-equality at the end. A mutation ledger is a program that writes to your source tree; its restore must not be a command whose scope it does not control.Test plan