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";