Skip to content

fix(errors): stop leaking raw provider errors to users — allocation_exhausted + unclassified passthrough (ENG-15627 G1+G2) - #47

Merged
monac24 merged 4 commits into
boonfrom
eng-15627-error-conveying
Jul 14, 2026
Merged

monac24 merged 4 commits into
boonfrom
eng-15627-error-conveying

Conversation

@monac24

@monac24 monac24 commented Jul 14, 2026 •

Copy link
Copy Markdown

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:

  1. 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 raw allocation_exhausted code or the bare "LLM request failed.".
  2. Any unclassified provider error. 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 error, the raw provider body reached the user verbatim.

Why This Change Was Made

  • G1: 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. context_length_exceeded was already handled (Context overflow), so no change there.
  • G2: guard the failover ladder's 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). The raw text is still preserved out-of-band on FailoverError.rawError for operator debugging.

Non-goals: the orphaned-tool_use history repair (ENG-15615), and the larger G3/G4/G5 + MessageOrigin/OperationOutcome work — 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_exhausted or LLM request failed.. More broadly, no unclassified raw provider body can reach the user-facing failure message anymore; operators still get the raw text via FailoverError.rawError and logs.

Evidence

  • TDD: RED proven for each fix by reverting the source and re-running (test fails), then GREEN with the fix in.
  • 730 tests pass across the error/failover suite (embedded-agent-helpers/**, embedded-agent-helpers.*, failover-error, assistant-failover, payloads.errors, handlers.lifecycle).
  • Live probe before/after G1: formatUserFacingAssistantErrorText on the gateway body went from "LLM request failed." → "⚠️ boon-llm-gateway (…) returned a billing error — …".
  • oxlint clean on all changed files.

🤖 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-gateway and blocks unclassified raw passthroughs (ENG-15627 G1, G2).

  • Bug Fixes
    • Classify allocation_exhausted and "token allocation exhausted" as billing in ERROR_PATTERNS.billing so boon-llm-gateway 429s route to billing handling (ENG-15627 G1).
    • Add dedicated allocation‑exhausted wording in formatAssistantErrorText (no provider name, no "switch API key") for gateway customers with a single BOON_API_KEY.
    • In resolveAssistantFailoverErrorMessage, guard with isRawAssistantErrorPassthrough and remove the lastAssistant.errorMessage fallback; unclassified raw bodies never reach users (raw remains in FailoverError.rawError) (ENG-15627 G2).
    • Tests: cover allocation‑exhausted copy/no raw JSON leaks; mock isRawAssistantErrorPassthrough in the embedded-run harness to prevent undefined imports and stabilize CI.

Written for commit 8316731. Summary will update on new commits.

Review in cubic

monac24 and others added 2 commits July 14, 2026 13:02
…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]>
@claude

claude Bot commented Jul 14, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cubic analysis

No issues found across 6 files

Linked issue analysis

Linked issue: ENG-15627: [P0][Arguijo] boon-agent shows raw "LLM request failed." on token-allocation exhaustion instead of a clear top-up message

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.

Re-trigger cubic

@gandalfboon gandalfboon Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 configured
  • run.cross-provider-fallback-error-context.test.ts:89/140 — uses the current attempt assistant for fallback errors instead of stale session history
  • run.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]>

@gandalfboon gandalfboon Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@monac24
monac24 merged commit 040a0d2 into boon Jul 14, 2026
144 checks passed
@monac24
monac24 deleted the eng-15627-error-conveying branch July 14, 2026 22:28
insomnius pushed a commit that referenced this pull request Jul 22, 2026
…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]>
convyusboy added a commit that referenced this pull request Jul 22, 2026
…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]>
convyusboy added a commit that referenced this pull request Jul 23, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants