Skip to content

feat(errors): add MessageOrigin gateway-failure code schema (ENG-15627 G5) - #48

Merged
monac24 merged 5 commits into
boonfrom
eng-15627-message-origin
Jul 14, 2026
Merged

monac24 merged 5 commits into
boonfrom
eng-15627-message-origin

Conversation

@monac24

@monac24 monac24 commented Jul 14, 2026 •

Copy link
Copy Markdown

Related: ENG-15627
Stacked on #47 (G1+G2). Base will retarget to boon once #47 merges.

What Problem This Solves

Downstream error-conveying guardrails (retry-before-emit, progress-draft continuity, subagent status) need a single source of truth for what failure state the session is in and how the user should act on it. Today there is no such type — MessageOrigin is specified in docs/concepts/message-lifecycle-refactor.md but not implemented, so every failure emit path invents its own copy and echo handling.

Why This Change Was Made

Introduces src/channels/message/message-origin.ts implementing the design-doc MessageOrigin shape exactly (so the lifecycle refactor adopts it, not a fork), extended for ENG-15627:

  • GATEWAY_FAILURE_CODES — the three pre-existing design-doc codes plus seven classifier-backed classes (token_allocation_exhausted, model_context_length_exceeded, provider_rate_limit_shared, provider_upstream_5xx, provider_malformed_history, agent_failed_transient_after_retries, subagent_still_working).
  • Per code: a canonical user-facing sentence (never the raw machine code) + a retryAffordance (user_can_retry | will_auto_retry | requires_operator | requires_billing_action).
  • resolveEmittableGatewayFailure — the fail-closed invariant that makes G2 mechanical: a coded failure emits as-is; an uncoded failure is dropped in non-direct chats (silent-reply policy) and downgraded to agent_failed_transient_after_retries in DMs.

Non-goals: channel encode/decode wiring (lands with the lifecycle refactor), and G3/G4 behavior that consumes these codes (separate PRs).

User Impact

No user-visible change yet — this is the schema foundation. Once G3/G4 consume it, users get consistent, classified, cross-channel failure copy instead of ad-hoc per-path prose, and operational failure output stops being accepted as bot input in shared rooms.

Evidence

  • TDD: RED (module missing) → GREEN.
  • 8 focused unit tests: code registry membership, non-empty/non-raw copy for every code, retry-affordance coverage + specific routings, origin builder shape, and all three fail-closed resolver branches.
  • Runs in the real channels vitest shard; barrel export loads cleanly in a consumer; oxlint clean.

🤖 Generated with Claude Code


Summary by cubic

Implements the MessageOrigin gateway_failure schema (ENG-15627 G5) so downstream guardrails have a single, typed source of failure state and user guidance, including a token_allocation_exhausted code. No user-visible changes yet.

  • New Features
    • GATEWAY_FAILURE_CODES: 3 existing codes plus 7 new classes — token_allocation_exhausted, model_context_length_exceeded, provider_rate_limit_shared, provider_upstream_5xx, provider_malformed_history, agent_failed_transient_after_retries, subagent_still_working.
    • Canonical user-facing sentence and RetryAffordance per code (user_can_retry | will_auto_retry | requires_operator | requires_billing_action).
    • makeGatewayFailureOrigin builds a schema-versioned openclaw gateway_failure origin with drop_bot_room_echo.
    • resolveEmittableGatewayFailure: pass through classified codes; drop uncoded failures in rooms; downgrade uncoded DMs to agent_failed_transient_after_retries.
    • Barrel exports from src/channels/message/index.ts now include these functions and types.

Written for commit 4694b08. 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 encountered an error —— View job


I'll analyze this and get back to you.

@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 3 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
✅ Add token_allocation_exhausted to the MessageOrigin gateway-failure codes GATEWAY_FAILURE_CODES includes token_allocation_exhausted in the newly added message-origin.ts.
✅ Provide a canonical, non-raw user-facing 'top up' sentence for token_allocation_exhausted CODE_COPY defines a human-facing sentence for token_allocation_exhausted and tests assert every code has non-empty/non-raw copy.
✅ Map token_allocation_exhausted to a billing retry-affordance (requires_billing_action) CODE_RETRY_AFFORDANCE maps token_allocation_exhausted to requires_billing_action and the tests assert this mapping.
✅ Implement fail-closed resolver so uncoded failures are dropped in group chats and downgraded in DMs (prevent raw string leakage) resolveEmittableGatewayFailure implements the fail-closed policy and tests verify dropping in non-direct chats and downgrading in DMs.
✅ Export MessageOrigin gateway-failure symbols for downstream consumers index.ts was modified to export the new functions/types so downstream code can import the schema.

Re-trigger cubic

… 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]>
@monac24
monac24 force-pushed the eng-15627-message-origin branch from ee951b4 to 7556085 Compare July 14, 2026 22:01
monac24 and others added 2 commits July 14, 2026 15:12
… "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]>
…7 G5)

Introduces the MessageOrigin type from message-lifecycle-refactor.md as a
real, tested module (src/channels/message/message-origin.ts) so downstream
guardrails have a single source of truth for "what failure state are we in."

- GATEWAY_FAILURE_CODES: the three design-doc codes
  (agent_failed_before_reply, missing_api_key, model_login_expired) plus the
  seven ENG-15627 classes (token_allocation_exhausted,
  model_context_length_exceeded, provider_rate_limit_shared,
  provider_upstream_5xx, provider_malformed_history,
  agent_failed_transient_after_retries, subagent_still_working).
- Per code: a canonical user-facing sentence (never the raw machine code) and
  a retryAffordance (user_can_retry | will_auto_retry | requires_operator |
  requires_billing_action).
- makeGatewayFailureOrigin builds the schema-versioned openclaw origin.
- resolveEmittableGatewayFailure is the fail-closed invariant that makes G2
  mechanical: a coded failure emits as-is; an uncoded failure is dropped in
  non-direct chats (silent-reply policy) and downgraded to
  agent_failed_transient_after_retries in DMs — a raw string can never leak as
  a coded emit.

Schema only; channel encode/decode wiring lands with the lifecycle refactor.
Exported from the channels/message barrel.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@monac24
monac24 force-pushed the eng-15627-message-origin branch from 7556085 to 4694b08 Compare July 14, 2026 22:12
Base automatically changed from eng-15627-error-conveying to boon July 14, 2026 22:28

@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.

Reviewed. Clean, well-scoped fix for the ENG-15627 P0 (Arguijo raw allocation_exhausted / "LLM request failed." leak).

The classifier addition + dedicated non-raw billing copy fix the reported symptom, and the G2 raw-passthrough guard in resolveAssistantFailoverErrorMessage is the right defensive move — drops the lastAssistant.errorMessage verbatim slot so no unclassified provider body can leak, while preserving rawError out-of-band for operators. message-origin.ts faithfully implements the design-doc shape and the fail-closed resolver is a sound invariant (uncoded → dropped in rooms, downgraded to a safe generic in DMs).

Tests hit exactly the right cases: bare-code + JSON-body billing classification, and the "gibberish never reaches the user, rawError still keeps it" assertion. 107 checks green, cubic clean, no open threads.

Approving.

@monac24
monac24 merged commit fb3e2ff into boon Jul 14, 2026
146 checks passed
@monac24
monac24 deleted the eng-15627-message-origin branch July 14, 2026 22:43
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