From c28b33ec384d6fb6607222b581030585d9bdcfaa Mon Sep 17 00:00:00 2001 From: Rishi Tamrakar Date: Mon, 24 Aug 2026 00:58:35 +0200 Subject: [PATCH] fix(subagents): keep the failure cause on pending-error timeout announces (#125357) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(subagents): keep the failure cause on pending-error timeout announces A run that fails inside the lifecycle error retry grace window is handed to waiters as `status: "timeout"` with the failure text attached and `pendingError: true` (createPendingErrorTimeoutSnapshot). applySubagentWaitOutcome rebuilt that as a bare `{ status: "timeout" }`, dropping the cause, and the announce status label had no slot for it — so the parent agent was told only "timed out" for a child that had actually errored, and could neither retry appropriately nor report the real blocker. Two other consumers of the same wait result already treat this shape as a failure with a cause (isPendingErrorAgentWaitTimeout in sessions-send-tool, isDeliveryFailureWait in sessions-send-tool.a2a); the subagent announce path was the outlier. Keep the cause when `pendingError === true` and render it as "timed out: ". Genuine budget timeouts carry no pendingError and are unchanged. Tests: 3 unit cases for applySubagentWaitOutcome (pending-error timeout keeps the cause; budget timeout has none; wait error text without pendingError is ignored) and an announce format case asserting the "timed out: " label. * fix(agents): bound the task-completion status label in prompt context statusLabel embeds caller-supplied error text ("failed: ", and now "timed out: "), but only the child result was capped before being projected into the parent agent's prompt — a large provider or lifecycle error could enter the model context unbounded and crowd out the result and the reply instruction. Cap the single status line at the shared internal-event formatting boundary, which covers both the pre-existing "failed: " path and the new timeout cause. Tests: a large-error status label is truncated with a marker and keeps its prefix; ordinary status labels are unchanged. * fix(agents): reuse truncateUtf16Safe for the status-label cap The status-label cap used a raw String.slice, which can split a UTF-16 surrogate pair when provider or lifecycle error text ends on an astral character, sending a dangling surrogate into the parent agent's prompt. Reuse the existing truncateUtf16Safe primitive instead of a parallel implementation, matching agent-run-terminal-reply.ts. Test: an emoji landing exactly on the truncation boundary keeps the label within the cap, ends with the marker, and leaves no unpaired surrogate or replacement character. * fix(subagents): keep main's subagent cancellation classifier The branch predated openclaw#125407, which replaced the generic classifier here with classifySubagentTerminalOutcome so explicit restart/aborted stop reasons stay cancellations while real provider timeouts still classify as timeouts. Resolving the merge with the generic call would have reverted that. Keep main's classifier and apply the pending-error cause inside its timeout case; the two are orthogonal. A pending-error snapshot carries no stopReason (createPendingErrorTimeoutSnapshot drops it), so the cancellation override never fires for it. Test: restart and aborted stop reasons with blocked liveness stay cancellations rather than being reported as failures. * refactor(subagents): reuse canonical status label truncation --------- Co-authored-by: Peter Steinberger --- src/agents/internal-events.test.ts | 55 ++++++++++++ src/agents/internal-events.ts | 17 +++- .../announce/subagent-announce-output.test.ts | 86 +++++++++++++++++++ .../announce/subagent-announce-output.ts | 18 +++- .../subagent-announce.format.e2e.test.ts | 9 ++ .../subagents/announce/subagent-announce.ts | 4 +- 6 files changed, 185 insertions(+), 4 deletions(-) diff --git a/src/agents/internal-events.test.ts b/src/agents/internal-events.test.ts index d4bed8e269c..75a495491d6 100644 --- a/src/agents/internal-events.test.ts +++ b/src/agents/internal-events.test.ts @@ -7,6 +7,8 @@ import { const MAX_CHILD_RESULT_CHARS = 6_000; const CHILD_RESULT_TRUNCATION_NOTICE = "\n[child result truncated]"; +const MAX_STATUS_LABEL_CHARS = 500; +const STATUS_LABEL_TRUNCATION_MARKER = "…[truncated]"; function taskCompletionEvent(result: string): AgentInternalEvent { return { @@ -23,6 +25,14 @@ function taskCompletionEvent(result: string): AgentInternalEvent { }; } +function extractStatusLine(prompt: string): string { + const status = prompt.match(/^status: (.*)$/m)?.[1]; + if (status === undefined) { + throw new Error("Expected status line"); + } + return status; +} + function extractChildResult(prompt: string): string { const result = prompt.match(/\n([\s\S]*?)\n<\/prompt-data>/)?.[1]; if (result === undefined) { @@ -52,4 +62,49 @@ describe("agent internal events", () => { extractChildResult(formatAgentInternalEventsForPrompt([taskCompletionEvent(result)])), ).toBe(result); }); + + it("bounds status labels carrying caller-supplied error text", () => { + const event = { + ...taskCompletionEvent("result"), + status: "timeout", + statusLabel: `timed out: ${"e".repeat(MAX_STATUS_LABEL_CHARS)}-unbounded-tail`, + } satisfies AgentInternalEvent; + const status = extractStatusLine(formatAgentInternalEventsForPrompt([event])); + + expect(status.length).toBeLessThanOrEqual(MAX_STATUS_LABEL_CHARS); + expect(status.endsWith(STATUS_LABEL_TRUNCATION_MARKER)).toBe(true); + expect(status).not.toContain("unbounded-tail"); + expect(status.startsWith("timed out: ")).toBe(true); + }); + + it("never splits a surrogate pair when truncating a status label", () => { + // Land an astral character exactly on the truncation boundary. + const marker = STATUS_LABEL_TRUNCATION_MARKER; + const keep = MAX_STATUS_LABEL_CHARS - marker.length; + const event = { + ...taskCompletionEvent("result"), + status: "timeout", + statusLabel: `${"a".repeat(keep - 1)}\u{1F600}${"b".repeat(50)}`, + } satisfies AgentInternalEvent; + const status = extractStatusLine(formatAgentInternalEventsForPrompt([event])); + + expect(status.length).toBeLessThanOrEqual(MAX_STATUS_LABEL_CHARS); + expect(status.endsWith(marker)).toBe(true); + const truncated = status.slice(0, -marker.length); + // A dangling high surrogate would make this false. + expect(truncated).toBe(truncated.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, "")); + expect(truncated.includes("\uFFFD")).toBe(false); + }); + + it("keeps ordinary status labels unchanged", () => { + const event = { + ...taskCompletionEvent("result"), + status: "error", + statusLabel: "failed: model returned no output", + } satisfies AgentInternalEvent; + + expect(extractStatusLine(formatAgentInternalEventsForPrompt([event]))).toBe( + "failed: model returned no output", + ); + }); }); diff --git a/src/agents/internal-events.ts b/src/agents/internal-events.ts index 65c3125d23d..a5344fd6a40 100644 --- a/src/agents/internal-events.ts +++ b/src/agents/internal-events.ts @@ -4,6 +4,7 @@ * blocks or plain prompt text. */ import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce"; +import { truncateWithMarker } from "@openclaw/normalization-core/utf16-slice"; import { formatGeneratedAttachmentLines, mediaUrlsFromGeneratedAttachments, @@ -42,6 +43,12 @@ type TaskCompletionPromptMode = "plain" | "protected"; const MAX_TASK_COMPLETION_RESULT_ESCAPED_CHARS = 6_000; const TASK_COMPLETION_RESULT_TRUNCATION_NOTICE = "\n[child result truncated]"; +// Status labels embed provider/lifecycle error text ("failed: ", +// "timed out: "), which is caller-supplied and unbounded. Keep the +// single status line short so a large error cannot crowd out the child result +// or the reply instruction in the parent's prompt. +const MAX_TASK_COMPLETION_STATUS_LABEL_CHARS = 500; +const TASK_COMPLETION_STATUS_LABEL_TRUNCATION_MARKER = "…[truncated]"; /** Internal event variants that can be rendered into agent prompt context. */ export type AgentInternalEvent = AgentTaskCompletionInternalEvent; @@ -152,7 +159,15 @@ function formatTaskCompletionEvent( const sessionId = sanitizeSingleLineField(event.childSessionId ?? "unknown", "unknown"); const announceType = sanitizeSingleLineField(event.announceType, "unknown"); const taskLabel = sanitizeSingleLineField(event.taskLabel, "unnamed task"); - const statusLabel = sanitizeSingleLineField(event.statusLabel, event.status); + const statusLabel = truncateWithMarker( + sanitizeSingleLineField(event.statusLabel, event.status), + MAX_TASK_COMPLETION_STATUS_LABEL_CHARS, + { + marker: TASK_COMPLETION_STATUS_LABEL_TRUNCATION_MARKER, + reserve: TASK_COMPLETION_STATUS_LABEL_TRUNCATION_MARKER.length, + trimEnd: true, + }, + ); const result = formatChildResultDataBlock(event.result); const attachmentLines = formatGeneratedAttachmentLines(event.attachments); const mediaDirectiveLines = formatGeneratedMediaDirectiveLines(event); diff --git a/src/agents/subagents/announce/subagent-announce-output.test.ts b/src/agents/subagents/announce/subagent-announce-output.test.ts index 10cd189dadd..04ee9c22fc0 100644 --- a/src/agents/subagents/announce/subagent-announce-output.test.ts +++ b/src/agents/subagents/announce/subagent-announce-output.test.ts @@ -862,4 +862,90 @@ describe("applySubagentWaitOutcome", () => { elapsedMs: 50, }); }); + + it.each(["restart", "aborted"] as const)( + "keeps %s stop reasons as cancellation even when liveness is blocked", + (stopReason) => { + // classifySubagentTerminalOutcome must win over the generic classifier + // here: blocked liveness alone would read as a failure, but an explicit + // restart/aborted stop reason owns the outcome (openclaw#125407). + const applied = applySubagentWaitOutcome({ + wait: { + status: "ok", + startedAt: 100, + endedAt: 150, + stopReason, + livenessState: "blocked", + error: "Context overflow: prompt too large for the model.", + }, + outcome: undefined, + }); + + expect(applied.outcome).toEqual({ + status: "error", + error: "subagent run terminated", + startedAt: 100, + endedAt: 150, + elapsedMs: 50, + }); + }, + ); + + it("keeps the failure cause on pending-error timeout wait snapshots", () => { + const applied = applySubagentWaitOutcome({ + wait: { + status: "timeout", + startedAt: 100, + endedAt: 150, + pendingError: true, + error: "model returned an unrecoverable tool-call sequence", + }, + outcome: undefined, + }); + + expect(applied.outcome).toEqual({ + status: "timeout", + error: "model returned an unrecoverable tool-call sequence", + startedAt: 100, + endedAt: 150, + elapsedMs: 50, + }); + }); + + it("leaves genuine budget timeouts without a cause", () => { + const applied = applySubagentWaitOutcome({ + wait: { + status: "timeout", + startedAt: 100, + endedAt: 150, + }, + outcome: undefined, + }); + + expect(applied.outcome).toEqual({ + status: "timeout", + startedAt: 100, + endedAt: 150, + elapsedMs: 50, + }); + }); + + it("ignores wait error text when the run did not end in a pending error", () => { + const applied = applySubagentWaitOutcome({ + wait: { + status: "timeout", + startedAt: 100, + endedAt: 150, + error: "waited too long", + }, + outcome: undefined, + }); + + expect(applied.outcome).toEqual({ + status: "timeout", + startedAt: 100, + endedAt: 150, + elapsedMs: 50, + }); + }); }); diff --git a/src/agents/subagents/announce/subagent-announce-output.ts b/src/agents/subagents/announce/subagent-announce-output.ts index 34d014b40aa..6ba99f5054e 100644 --- a/src/agents/subagents/announce/subagent-announce-output.ts +++ b/src/agents/subagents/announce/subagent-announce-output.ts @@ -352,10 +352,24 @@ export function applySubagentWaitOutcome(params: { // primary normalizers, so apply the canonical classification here instead // of re-enumerating reason groups. if (terminalOutcome) { + // Keep main's subagent-specific classifier: it preserves explicit + // restart/aborted stop reasons as cancellation while still letting real + // provider timeouts through (openclaw#125407). switch (classifySubagentTerminalOutcome(terminalOutcome)) { - case "timeout": - outcome = { status: "timeout" }; + case "timeout": { + // A run that failed inside the lifecycle error retry grace window is + // surfaced to waiters as a timeout carrying the failure text and + // `pendingError: true` (see createPendingErrorTimeoutSnapshot). Keep + // that cause so the announce can report why the child died instead of + // a bare "timed out". Genuine budget timeouts have no pendingError and + // stay unchanged. + const pendingErrorText = + params.wait?.pendingError === true ? (terminalOutcome.error ?? waitError) : undefined; + outcome = pendingErrorText + ? { status: "timeout", error: pendingErrorText } + : { status: "timeout" }; break; + } case "cancellation": outcome = { status: "error", error: "subagent run terminated" }; break; diff --git a/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts b/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts index 8d524fb6d76..04a52a948e2 100644 --- a/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts +++ b/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts @@ -1456,6 +1456,15 @@ describe("subagent announce formatting", () => { expectedStatus: "timed out", spawnMode: undefined, }, + { + childSessionId: "child-session-direct-timeout-cause", + requesterSessionId: "requester-session-timeout-cause", + childRunId: "run-direct-completion-timeout-cause", + replyText: "partial output", + outcome: { status: "timeout", error: "child run failed before completing" } as const, + expectedStatus: "timed out: child run failed before completing", + spawnMode: undefined, + }, ] as const; for (const testCase of cases) { diff --git a/src/agents/subagents/announce/subagent-announce.ts b/src/agents/subagents/announce/subagent-announce.ts index 0472571d947..e3a230caf7e 100644 --- a/src/agents/subagents/announce/subagent-announce.ts +++ b/src/agents/subagents/announce/subagent-announce.ts @@ -458,7 +458,9 @@ export async function runSubagentAnnounceFlow(params: { outcome.status === "ok" ? "completed; ready for parent review" : outcome.status === "timeout" - ? "timed out" + ? outcome.error + ? `timed out: ${outcome.error}` + : "timed out" : outcome.status === "error" ? `failed: ${outcome.error || "unknown error"}` : "finished with unknown status";