Repository navigation
fix(errors): stop leaking raw provider errors to users — allocation_exhausted + unclassified passthrough (ENG-15627 G1+G2) - #47
Conversation
…g (ENG-15627 G1)
The boon-llm-gateway returns a 429 with body
{"error":"allocation_exhausted","message":"Token allocation exhausted..."}
when an org's token allocation is spent. This fell through the failover
classifier, so the user saw either the raw `allocation_exhausted` code
(formatAssistantErrorText) or the bare "LLM request failed." fallback
(formatUserFacingAssistantErrorText) — the string in the Arguijo customer
screenshot.
Add allocation_exhausted / "token allocation exhausted" to
ERROR_PATTERNS.billing so isBillingErrorMessage classifies it and the
cascade routes it to the sanitized billing copy before the raw-passthrough
leak point.
Tests: output-level (formatAssistantErrorText / formatUserFacing never leak
the code or emit the generic fallback) + classifier-level (isBillingErrorMessage
+ classifyFailoverReason → "billing", incl. bare code/message forms).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
resolveAssistantFailoverErrorMessage built the user-facing FailoverError message from the RAW formatAssistantErrorText output plus a `lastAssistant.errorMessage?.trim()` fallback slot. When no classifier branch recognized the provider error, formatAssistantErrorText falls through to echoing the raw errorMessage, so raw provider bodies reached the user verbatim (e.g. an unclassified provider-internal string). Guard the formatted text with isRawAssistantErrorPassthrough (the same check formatUserFacingAssistantErrorText already applies) and drop the raw errorMessage slot. A raw passthrough now falls through to the classified tail (timeout / rate-limit / billing / auth / generic "LLM request failed."). The raw text remains preserved out-of-band on FailoverError.rawError for operator debugging (existing test unchanged). Export isRawAssistantErrorPassthrough from the embedded-agent-helpers barrel. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
I'll analyze this and get back to you. |
There was a problem hiding this comment.
cubic analysis
No issues found across 6 files
Linked issue analysis
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Classify boon-llm-gateway allocation_exhausted as a billing error so user-facing message shows sanitized billing/top-up copy instead of raw JSON or generic "LLM request failed." | ERROR_PATTERNS was extended to match allocation_exhausted / token allocation exhausted and tests were added to assert classification and that formatUserFacingAssistantErrorText does not leak the raw JSON or generic fallback. |
| ✅ | Prevent unclassified raw provider text from being surfaced as the user-facing failover message; preserve raw text out-of-band (FailoverError.rawError) while routing user text to classified messaging (timeout/rate-limit/billing/auth/generic) | assistant-failover logic now guards formatted text with the raw-passthrough check and drops the previous raw-error fallback; tests verify the user-facing message does not contain raw provider text and that rawError still carries the original string for operators. |
There was a problem hiding this comment.
CI is red on checks-node-agentic-agents-embedded — the very suite this PR touches — so this isn't landable yet. 3 tests fail, all from the same root cause the G2 change introduced:
AssertionError: expected Error: [vitest] No "isRawAssistantErrorPassthrough" export is defined on the "…" mock to be an instance of MockedFailoverError
run.codex-server-error-fallback.test.ts:71— throws FailoverError for Codex server_error when model fallbacks are configuredrun.cross-provider-fallback-error-context.test.ts:89/140— uses the current attempt assistant for fallback errors instead of stale session historyrun.cross-provider-fallback-error-context.test.ts:178— falls back to the session assistant when compaction removes the current attempt slice
Why: G2 added an isRawAssistantErrorPassthrough(...) call inside resolveAssistantFailoverErrorMessage. Those two sibling tests vi.mock() the embedded-agent-helpers barrel with an explicit export list that predates this dependency, so the mock has no isRawAssistantErrorPassthrough stub. The mock throws on the missing export before the code can reach the real FailoverError throw — hence toBeInstanceOf(MockedFailoverError) fails.
Fix: add an isRawAssistantErrorPassthrough stub to the mocked barrel in both failing test files (default it to return false so the classified tail runs as before; add a true case if you want to assert the passthrough-suppression path). The 730 tests cited in the description pass because they exercise the helper suites directly — these two use the mocked barrel and weren't updated for the new call.
Everything else looks clean: cubic found no issues, ENG-15627 G1/G2 acceptance criteria both met, the classifier + passthrough-guard approach is sound, and FailoverError.rawError preserving the raw text out-of-band is the right call. Just needs the two mocks patched and CI green, then I'm happy to re-review.
… harness (ENG-15627 G2) G2 added an isRawAssistantErrorPassthrough import to assistant-failover.ts. The shared embedded-run test harness vi.mock's ../embedded-agent-helpers.js with an explicit export list, so the new import resolved to undefined and threw in three fallback tests (cross-provider-fallback-error-context, codex-server-error-fallback). Add the mock (default false = not a passthrough, preserving prior behavior) with a reset alongside the sibling probes. Fixes the checks-node-agentic-agents-embedded CI shard. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Verified on f9264c7: fix is exactly the mock-completeness gap I flagged — isRawAssistantErrorPassthrough now stubbed (default false, preserving prior behavior) in the shared embedded-run harness. checks-node-agentic-agents-embedded is GREEN, 0 failing checks across the rollup, commit verified-signed. Ship it. 🧙
… "switch API key" (ENG-15627 G1)
G1 classified boon-llm-gateway allocation_exhausted as billing, which stopped
the raw-code leak but inherited the generic API-key billing copy: "...top up or
switch to a different API key" naming the gateway provider. That copy is wrong
for a gateway customer — they authenticate with one BOON_API_KEY against an
org-level allocation, so there is no other key to switch to, and the provider
name should not leak into user copy.
Add isAllocationExhaustedErrorMessage + dedicated ALLOCATION_EXHAUSTED_USER_TEXT
("This account has reached its usage allocation. Top up your allocation or
contact your account team, then try again.") and return it from
formatAssistantErrorText before the generic billing formatter runs. Allocation
is still classified as billing for failover/retry behavior; only the user copy
changes. Copy matches the token_allocation_exhausted sentence in G5's
message-origin schema.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rail (ENG-16330) (#62) * feat(errors): intelligent-messaging core — outcome-aware surfacing classifier + path trail (ENG-16330) Pure-logic core (no wiring yet) for extending #53's outcome-awareness to the recovered-non-zero-exec class: classifyToolSurfacing (passthrough | immediate | buffer-recoverable), a per-turn error buffer that on turn-SUCCESS hides the recovered⚠️ failed badges and emits a human-readable path trail, on turn-FAILURE flushes them as real failures (no #53/#47/#48/#50 regression), and sanitizeGeneratedSessionName (salty-shore → "a background command"). Model-facing isToolResultError untouched. 10/10 unit tests green. Handler/turn-close wiring (handleToolExecutionEnd buffer + handleMessageEnd flush) follows in the next commit. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(errors): wire intelligent-messaging buffer into tool-end + turn-close (ENG-16330) Wires the tested core into the streaming path: - handlers.types: add per-turn `intelligentMessagingBuffer?: TurnErrorBuffer` to state (+ Pick). - handleToolExecutionEnd: classifyToolSurfacing → a "buffer-recoverable" exec/tmux/process error is recorded to the per-turn buffer instead of emitting the live⚠️ badge (terminal auth/quota/delivery errors + non-recoverable tools still emit immediately; model-facing isToolResultError unchanged). - handleMessageEnd (turn close): resolve the buffer — success (normal stopReason + non-empty reply, confabulation guard) → emit a neutral path-trail note; failure → flush honest failure badges (no #53/#47/#48/#50 regression); clear buffer to prevent double-emit. Verified: 107/107 tests green (10 new intelligent-messaging + 97 existing handler/media, no regression); tsc + oxlint clean on all changed files. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(errors): don't skip after_tool_call hook when buffering a recoverable error (ENG-16330) The buffer branch early-returned before the after_tool_call plugin-hook fire + stream boundary, so a buffered recoverable exec/process error suppressed the hook (broke after-tool-call.fires-once + owned-tool-runtime-contract tests). Gate ONLY the emitToolResultOutput call on the buffering decision (if/else); the hook + stream boundary now run in all cases. Buffering defers the channel badge only, never plugin hooks. Verified: the 2 previously-failing agents-core tests + core + handler tests → 87/87 green. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(errors): address cubic review on ENG-16330 turn-close buffer resolution (PR #62) - P1: only resolve the buffer on a TERMINAL assistant outcome (stop/end_turn); a toolUse (in-progress) turn leaves the buffer intact so continuing tool steps + the real final reply still reach it — no premature failure flush mid-turn. - P1: clear the buffer at the suppressVisibleAssistantOutput (commentary) early return so a commentary-phase turn's buffered errors can't leak into the next turn. - P2: gate both path-trail + failure-badge emissions on ctx.shouldEmitToolOutput() (respect non-full verbosity / output-disabled). - P2: success guard now accepts a media-only silent reply (cleanedText empty + hasMedia) as a valid successful turn, not a false failure. - P2: add a test for the looksTerminal branch (recoverable tool + terminal signal unauthorized/forbidden/quota/invalid_api_key → "immediate", not buffered). Verified: 88/88 green (core + the 2 prior-regression tests + handlers); tsc + oxlint clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(errors): cover tmux buffer-recoverable classification (cubic P2, PR #62) tmux is in RECOVERABLE_TOOL_NAMES alongside exec/process but was untested; add the missing classifyToolSurfacing case. 12/12 green. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(errors): flush buffered failures on ALL terminal outcomes; keep buffer across commentary steps (cubic P1 round 2, PR #62) Two round-2 P1s from cubic, both my prior over-correction: - terminalOutcome was `stop || end_turn`, so error/abort/length/max_tokens turns silently DROPPED buffered non-zero tool failures. `toolUse` is the only CONTINUING outcome — flip to `stopReason !== "toolUse"` so every terminal result resolves the buffer; the turnSucceeded guard already picks success (path trail) vs. failure (honest badges). - clearing the buffer at the suppressVisibleAssistantOutput (commentary) early return dropped earlier-in-turn recoverable errors before the real terminal reply could surface them. A commentary step is mid-turn, not a boundary — leave the buffer intact (same as the non-assistant/transcript-only return); only the terminal outcome resolves/clears it. Verified: 89/89 green (core + handlers + the 2 prior-regression tests); tsc clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
…inal status (ENG-16330) The user-facing "⚠️ 🧰 Process: <session> failed" badge is built at buildEmbeddedRunPayloads (payloads.ts) from ctx.state.lastToolError, NOT by emitToolResultOutput. A backgrounded exec/process/tmux session that exits non-zero but which the agent recovers from — the turn still produces a real reply — rendered a terminal "failed" badge, giving the user the wrong intuition ("the agent broke"). Widen shouldMarkNonTerminalToolErrorWarning from middlewareError-only to also treat a recovered exec/bash/process/tmux error as non-terminal. The caller already gates this on hasUserFacingAssistantReply, so the reframe only fires when the turn actually produced a reply; on a reply-less genuine failure the honest "⚠️ … failed" badge still surfaces (no #53/#47/#48/#50 regression). write/edit/message stay strict — a failed write with a "done" reply is still flagged as confabulation. Reuses the shipped ENG-15627 G4 continuation note ("↻ A step didn't complete, but I kept going"); no new copy, no raw generated session names. Supersedes the buffer approach in PR #62, which intercepted emitToolResultOutput (live streamed output) — a different sink from the badge, so the badge was never reached. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…inal status (ENG-16330) (#64) * fix(errors): reframe recovered exec/process/tmux failures as non-terminal status (ENG-16330) The user-facing "⚠️ 🧰 Process: <session> failed" badge is built at buildEmbeddedRunPayloads (payloads.ts) from ctx.state.lastToolError, NOT by emitToolResultOutput. A backgrounded exec/process/tmux session that exits non-zero but which the agent recovers from — the turn still produces a real reply — rendered a terminal "failed" badge, giving the user the wrong intuition ("the agent broke"). Widen shouldMarkNonTerminalToolErrorWarning from middlewareError-only to also treat a recovered exec/bash/process/tmux error as non-terminal. The caller already gates this on hasUserFacingAssistantReply, so the reframe only fires when the turn actually produced a reply; on a reply-less genuine failure the honest "⚠️ … failed" badge still surfaces (no #53/#47/#48/#50 regression). write/edit/message stay strict — a failed write with a "done" reply is still flagged as confabulation. Reuses the shipped ENG-15627 G4 continuation note ("↻ A step didn't complete, but I kept going"); no new copy, no raw generated session names. Supersedes the buffer approach in PR #62, which intercepted emitToolResultOutput (live streamed output) — a different sink from the badge, so the badge was never reached. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(errors): drop inert tmux from recoverable exec class (ENG-16330, cubic P2) tmux is neither in MUTATING_TOOL_NAMES nor exec-like, so resolveToolErrorWarningPolicy already sets showWarning=false (no badge at all) once a reply exists — it never reached shouldMarkNonTerminalToolErrorWarning. Listing it was dead code implying a path that never fires. Remove it and document why it's intentionally absent. Recovered exec/bash/process reframe unchanged; 60/60 tests green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * revert(errors): unwind #62 buffer/path-trail; keep single payloads.ts reframe (ENG-16330) #62 (merged) buffered the emitToolResultOutput call and added a turn-close '🔧 Recovered…' path-trail note — but that is a DIFFERENT sink from the actual badge. The '⚠️ 🧰 Process: <session> failed' badge is built in buildEmbeddedRunPayloads (payloads.ts) from ctx.state.lastToolError, which handleToolExecutionEnd still sets unconditionally regardless of the buffer. So on boon today the badge STILL fires alongside #62's new note — the user gets both, and the headline symptom is unfixed. This PR's payloads.ts reframe fixes the real sink. Keeping #62's machinery on top would emit two redundant recovery notes (🔧 + ↻) and leaves two overlapping paths for one behavior. Per one-canonical-path policy, unwind #62: - delete src/agents/intelligent-messaging.ts + its test - restore the 3 handler files (messages/tools/types) to pre-#62 state Net result: one seam — shouldMarkNonTerminalToolErrorWarning reframes recovered exec/bash/process errors on a successful turn into the shipped G4 note; reply-less genuine failures keep the honest badge; write/edit/message stay strict. 60/60 payloads.errors + 69/69 handlers.tools green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>

Related: ENG-15627
What Problem This Solves
Fixes an issue where users would see raw internal error strings instead of an actionable message when their LLM request failed. Two concrete leaks on the assistant-failover path:
allocation_exhausted(the Arguijo customer screenshot). When an org's token allocation is spent, boon-llm-gateway returns a 429 with body{"error":"allocation_exhausted","message":"Token allocation exhausted. Contact sales..."}. This fell through the failover classifier, so the user saw either the rawallocation_exhaustedcode or the bare"LLM request failed.".resolveAssistantFailoverErrorMessagebuilt the user-facingFailoverError.messagefrom the rawformatAssistantErrorTextoutput plus alastAssistant.errorMessage?.trim()fallback slot. When no classifier branch recognized the error, the raw provider body reached the user verbatim.Why This Change Was Made
allocation_exhausted/"token allocation exhausted"toERROR_PATTERNS.billingsoisBillingErrorMessageclassifies it and the cascade routes it to the sanitized billing copy before the raw-passthrough leak point.context_length_exceededwas already handled (Context overflow), so no change there.isRawAssistantErrorPassthrough(the same checkformatUserFacingAssistantErrorTextalready applies) and drop the rawerrorMessageslot. A raw passthrough now falls through to the classified tail (timeout / rate-limit / billing / auth / generic). The raw text is still preserved out-of-band onFailoverError.rawErrorfor operator debugging.Non-goals: the orphaned-
tool_usehistory repair (ENG-15615), and the larger G3/G4/G5 +MessageOrigin/OperationOutcomework — separate PRs.User Impact
Customers hitting a spent token allocation now see actionable billing copy ("returned a billing error — ... top up or switch...") instead of
allocation_exhaustedorLLM request failed.. More broadly, no unclassified raw provider body can reach the user-facing failure message anymore; operators still get the raw text viaFailoverError.rawErrorand logs.Evidence
embedded-agent-helpers/**,embedded-agent-helpers.*,failover-error,assistant-failover,payloads.errors,handlers.lifecycle).formatUserFacingAssistantErrorTexton the gateway body went from"LLM request failed."→"⚠️ boon-llm-gateway (…) returned a billing error — …".🤖 Generated with Claude Code
Summary by cubic
Stops leaking raw provider error text during assistant failover and shows clear, sanitized messages. Adds dedicated allocation‑exhausted billing copy for
boon-llm-gatewayand blocks unclassified raw passthroughs (ENG-15627 G1, G2).allocation_exhaustedand "token allocation exhausted" as billing inERROR_PATTERNS.billingsoboon-llm-gateway429s route to billing handling (ENG-15627 G1).formatAssistantErrorText(no provider name, no "switch API key") for gateway customers with a singleBOON_API_KEY.resolveAssistantFailoverErrorMessage, guard withisRawAssistantErrorPassthroughand remove thelastAssistant.errorMessagefallback; unclassified raw bodies never reach users (raw remains inFailoverError.rawError) (ENG-15627 G2).isRawAssistantErrorPassthroughin the embedded-run harness to prevent undefined imports and stabilize CI.Written for commit 8316731. Summary will update on new commits.