Skip to content

Commit 500fed6

Browse files
steipetePeter Steinberger
andauthored
fix(agents): preserve bounded truthful subagent outcomes (#116932)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 73aa80a commit 500fed6

5 files changed

Lines changed: 404 additions & 21 deletions

File tree

‎src/agents/subagent-announce-output.test.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,54 @@ describe("readSubagentOutput", () => {
121121
expect(deps.callGateway).toHaveBeenCalledOnce();
122122
});
123123

124+
it.each([
125+
{
126+
shape: "OpenAI top-level snake_case function call",
127+
assistant: {
128+
role: "assistant",
129+
content: "Waiting for child completion.",
130+
tool_calls: [{ type: "function", function: { name: "sessions_yield" } }],
131+
},
132+
},
133+
{
134+
shape: "top-level camelCase tool call",
135+
assistant: {
136+
role: "assistant",
137+
content: "Waiting for child completion.",
138+
toolCalls: [{ name: "sessions_yield" }],
139+
},
140+
},
141+
{
142+
shape: "nested content function call",
143+
assistant: {
144+
role: "assistant",
145+
content: [
146+
{ type: "text", text: "Waiting for child completion." },
147+
{ type: "function_call", function: { name: "sessions_yield" } },
148+
],
149+
},
150+
},
151+
])("does not expose a $shape yield turn as completion output", async ({ assistant }) => {
152+
installOutputDeps({
153+
messages: [assistant, { role: "tool", content: '{"status":"yielded"}' }],
154+
});
155+
156+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
157+
});
158+
159+
it.each(["toolUse", "functionCall", "function_call"])(
160+
"reports visible tool activity for provider-specific %s transcript blocks",
161+
async (type) => {
162+
installOutputDeps({
163+
messages: [{ role: "assistant", content: [{ type, name: "read" }] }],
164+
});
165+
166+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBe(
167+
"1 tool call(s) made without visible output.",
168+
);
169+
},
170+
);
171+
124172
it("returns final assistant output that arrives after a sessions_yield wait turn", async () => {
125173
installOutputDeps({
126174
messages: [
@@ -321,6 +369,106 @@ describe("readSubagentOutput", () => {
321369
});
322370

323371
describe("buildChildCompletionFindings", () => {
372+
it("hard-bounds each child result and the aggregate parent prompt", () => {
373+
const findings = buildChildCompletionFindings(
374+
Array.from({ length: 8 }, (_, index) => ({
375+
childSessionKey: `agent:main:subagent:${index}`,
376+
task: `worker ${index}`,
377+
createdAt: index,
378+
completion: { resultText: "🚀".repeat(60_000) },
379+
outcome: { status: "ok" as const },
380+
})),
381+
);
382+
383+
expect(findings).toBeDefined();
384+
expect(findings!.length).toBeLessThanOrEqual(4_096);
385+
expect(findings).toContain("status: ok");
386+
expect(findings).toContain("[child result truncated]");
387+
expect(findings).toContain("additional child completion result");
388+
expect(findings).toContain("</prompt-data>");
389+
for (const character of findings ?? "") {
390+
const code = character.charCodeAt(0);
391+
expect(character.length > 1 || code < 0xd800 || code > 0xdfff).toBe(true);
392+
}
393+
});
394+
395+
it("retains a later actionable failure when an earlier child exceeds the remaining budget", () => {
396+
const findings = buildChildCompletionFindings([
397+
{
398+
childSessionKey: "agent:main:subagent:first",
399+
task: "first large result",
400+
createdAt: 1,
401+
completion: { resultText: "<".repeat(100_000) },
402+
outcome: { status: "ok" },
403+
},
404+
{
405+
childSessionKey: "agent:main:subagent:second",
406+
task: "second large result",
407+
createdAt: 2,
408+
completion: { resultText: "<".repeat(100_000) },
409+
outcome: { status: "ok" },
410+
},
411+
{
412+
childSessionKey: "agent:main:subagent:failure",
413+
task: "later actionable failure",
414+
createdAt: 3,
415+
completion: { resultText: "Permission required." },
416+
outcome: { status: "error", error: "Writable session authorization required." },
417+
},
418+
]);
419+
420+
expect(findings!.length).toBeLessThanOrEqual(4_096);
421+
expect(findings).toContain("first large result");
422+
expect(findings).toContain("later actionable failure");
423+
expect(findings).toContain("status: error: Writable session authorization required.");
424+
expect(findings).toContain("[1 additional child completion result omitted");
425+
});
426+
427+
it("prioritizes an oversized failed completion over an earlier oversized success", () => {
428+
const findings = buildChildCompletionFindings([
429+
{
430+
childSessionKey: "agent:main:subagent:success",
431+
task: "earlier oversized success",
432+
createdAt: 1,
433+
completion: { resultText: "<".repeat(100_000) },
434+
outcome: { status: "ok" },
435+
},
436+
{
437+
childSessionKey: "agent:main:subagent:failure",
438+
task: "later oversized failure",
439+
createdAt: 2,
440+
completion: { resultText: "<".repeat(100_000) },
441+
outcome: { status: "error", error: "Writable session authorization required." },
442+
},
443+
]);
444+
445+
expect(findings!.length).toBeLessThanOrEqual(4_096);
446+
expect(findings).toContain("later oversized failure");
447+
expect(findings).toContain("status: error: Writable session authorization required.");
448+
expect(findings).not.toContain("earlier oversized success");
449+
expect(findings).toContain("[1 additional child completion result omitted");
450+
});
451+
452+
it("keeps escaped child data and oversized failure metadata inside the same hard cap", () => {
453+
const findings = buildChildCompletionFindings([
454+
{
455+
childSessionKey: "agent:main:subagent:child",
456+
label: "L".repeat(20_000),
457+
task: "child task",
458+
createdAt: 1,
459+
completion: { resultText: "<".repeat(100_000) },
460+
outcome: { status: "error", error: "E".repeat(20_000) },
461+
},
462+
]);
463+
464+
expect(findings).toBeDefined();
465+
expect(findings!.length).toBeLessThanOrEqual(4_096);
466+
expect(findings).toContain("status: error:");
467+
expect(findings).toContain("&lt;");
468+
expect(findings).toContain("[child result truncated]");
469+
expect(findings).toContain("</prompt-data>");
470+
});
471+
324472
it("does not convert ANNOUNCE_SKIP child completions into no-output findings", () => {
325473
const findings = buildChildCompletionFindings([
326474
{

‎src/agents/subagent-announce-output.ts‎

Lines changed: 85 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Reads child session output, detects waiting states, and formats completion findings for announcements.
55
*/
66
import { asFiniteNumber } from "@openclaw/normalization-core/number-coercion";
7+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
78
import { isSilentReplyText, SILENT_REPLY_TOKEN } from "../auto-reply/tokens.js";
89
import type { SessionTranscriptRuntimeTarget } from "../config/sessions/session-accessor.js";
910
import { isFastTestRuntimeEnv } from "../infra/env.js";
@@ -28,6 +29,17 @@ import { extractAssistantText, sanitizeTextContent } from "./tools/chat-history-
2829
import { isAnnounceSkip, selectDeliverableSessionsReply } from "./tools/sessions-send-tokens.js";
2930

3031
const FAST_TEST_RETRY_INTERVAL_MS = 8;
32+
const MAX_CHILD_COMPLETION_RESULT_CHARS = 512;
33+
const MAX_CHILD_COMPLETION_FIELD_CHARS = 256;
34+
const MAX_CHILD_COMPLETION_FINDINGS_CHARS = 4_096;
35+
const CHILD_RESULT_TRUNCATION_NOTICE = "\n[child result truncated]";
36+
const ASSISTANT_TOOL_CALL_BLOCK_TYPES = new Set([
37+
"toolCall",
38+
"tool_use",
39+
"toolUse",
40+
"functionCall",
41+
"function_call",
42+
]);
3143

3244
type SubagentAnnounceOutputDeps = {
3345
callGateway: typeof callGateway;
@@ -128,8 +140,7 @@ function countAssistantToolCalls(message: unknown): number {
128140
(block) =>
129141
block &&
130142
typeof block === "object" &&
131-
((block as { type?: unknown }).type === "toolCall" ||
132-
(block as { type?: unknown }).type === "tool_use"),
143+
ASSISTANT_TOOL_CALL_BLOCK_TYPES.has((block as { type?: string }).type ?? ""),
133144
).length
134145
: 0;
135146
const toolCalls =
@@ -358,14 +369,29 @@ function describeSubagentOutcome(outcome?: SubagentRunOutcome): string {
358369
}
359370

360371
function formatChildResultData(resultText?: string | null): string {
372+
const text = resultText?.trim() || "(no output)";
373+
const boundedText =
374+
text.length > MAX_CHILD_COMPLETION_RESULT_CHARS
375+
? `${truncateUtf16Safe(
376+
text,
377+
MAX_CHILD_COMPLETION_RESULT_CHARS - CHILD_RESULT_TRUNCATION_NOTICE.length,
378+
)}${CHILD_RESULT_TRUNCATION_NOTICE}`
379+
: text;
361380
return (
362381
wrapPromptDataBlock({
363382
label: "Child result",
364-
text: resultText?.trim() || "(no output)",
383+
text: boundedText,
384+
maxChars: MAX_CHILD_COMPLETION_RESULT_CHARS,
365385
}) || "Child result: (no output)"
366386
);
367387
}
368388

389+
function truncateChildCompletionField(value: string): string {
390+
return value.length > MAX_CHILD_COMPLETION_FIELD_CHARS
391+
? `${truncateUtf16Safe(value, MAX_CHILD_COMPLETION_FIELD_CHARS - 1)}…`
392+
: value;
393+
}
394+
369395
type ChildCompletionRow = {
370396
childSessionKey: string;
371397
task: string;
@@ -386,6 +412,12 @@ type ChildCompletionRow = {
386412
outcome?: SubagentRunOutcome;
387413
};
388414

415+
type ChildCompletionSection = {
416+
index: number;
417+
text: string;
418+
actionable: boolean;
419+
};
420+
389421
function selectChildCompletionResultText(child: ChildCompletionRow): string | undefined {
390422
const primary = child.completion?.resultText ?? child.delivery?.payload?.frozenResultText;
391423
const fallback =
@@ -429,7 +461,7 @@ export function buildChildCompletionFindings(
429461
: 0;
430462
});
431463

432-
const sections: string[] = [];
464+
const sections: ChildCompletionSection[] = [];
433465
for (const [index, child] of sorted.entries()) {
434466
const resultText = selectChildCompletionResultText(child);
435467
const outcome = describeSubagentOutcome(child.outcome);
@@ -442,18 +474,61 @@ export function buildChildCompletionFindings(
442474
child.childSessionKey.trim() ||
443475
`child ${index + 1}`;
444476
const displayIndex = sections.length + 1;
445-
sections.push(
446-
[`${displayIndex}. ${title}`, `status: ${outcome}`, formatChildResultData(resultText)].join(
447-
"\n",
448-
),
449-
);
477+
sections.push({
478+
index: displayIndex,
479+
actionable: child.outcome?.status !== "ok",
480+
text: [
481+
`${displayIndex}. ${truncateChildCompletionField(title)}`,
482+
`status: ${truncateChildCompletionField(outcome)}`,
483+
formatChildResultData(resultText),
484+
].join("\n"),
485+
});
450486
}
451487

452488
if (sections.length === 0) {
453489
return undefined;
454490
}
455491

456-
return ["Child completion results:", "", ...sections].join("\n\n");
492+
// Escaping can expand bounded child text. Preserve failures before successes,
493+
// keep rendered survivors chronological, and account for omitted completions.
494+
const render = (visibleSections: string[], omittedCount = 0) =>
495+
[
496+
"Child completion results:",
497+
"",
498+
...visibleSections,
499+
...(omittedCount > 0
500+
? [
501+
`[${omittedCount} additional child completion result${omittedCount === 1 ? "" : "s"} omitted to fit the context budget.]`,
502+
]
503+
: []),
504+
].join("\n\n");
505+
const allSections = sections.map((section) => section.text);
506+
if (render(allSections).length <= MAX_CHILD_COMPLETION_FINDINGS_CHARS) {
507+
return render(allSections);
508+
}
509+
const prioritizedSections = [
510+
...sections.filter((section) => section.actionable),
511+
...sections.filter((section) => !section.actionable),
512+
];
513+
let visibleSections: ChildCompletionSection[] = [];
514+
for (const section of prioritizedSections) {
515+
const nextSections = [...visibleSections, section].toSorted(
516+
(left, right) => left.index - right.index,
517+
);
518+
const omittedCount = sections.length - nextSections.length;
519+
if (
520+
render(
521+
nextSections.map((entry) => entry.text),
522+
omittedCount,
523+
).length <= MAX_CHILD_COMPLETION_FINDINGS_CHARS
524+
) {
525+
visibleSections = nextSections;
526+
}
527+
}
528+
return render(
529+
visibleSections.map((section) => section.text),
530+
sections.length - visibleSections.length,
531+
);
457532
}
458533

459534
export function dedupeLatestChildCompletionRows(

‎src/agents/subagent-yield-output.ts‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ function readToolName(value: unknown): string | undefined {
1212
if (!record) {
1313
return undefined;
1414
}
15-
return readTrimmedStringAlias(record, [
16-
"name",
17-
"toolName",
18-
"tool_name",
19-
"functionName",
20-
"function_name",
21-
]);
15+
const aliases = ["name", "toolName", "tool_name", "functionName", "function_name"];
16+
const direct = readTrimmedStringAlias(record, aliases);
17+
if (direct) {
18+
return direct;
19+
}
20+
const nestedFunction = asOptionalRecord(record.function);
21+
return nestedFunction ? readTrimmedStringAlias(nestedFunction, aliases) : undefined;
2222
}
2323

2424
function isToolCallBlock(value: unknown): boolean {
@@ -38,11 +38,21 @@ function isToolCallBlock(value: unknown): boolean {
3838
/** Returns true when an assistant message requested the sessions_yield tool. */
3939
export function assistantCallsSessionsYield(message: unknown): boolean {
4040
const record = asOptionalRecord(message);
41-
if (!record || record.role !== "assistant" || !Array.isArray(record.content)) {
41+
if (!record || record.role !== "assistant") {
4242
return false;
4343
}
44-
return record.content.some(
45-
(block) => isToolCallBlock(block) && readToolName(block) === "sessions_yield",
44+
if (
45+
Array.isArray(record.content) &&
46+
record.content.some(
47+
(block) => isToolCallBlock(block) && readToolName(block) === "sessions_yield",
48+
)
49+
) {
50+
return true;
51+
}
52+
return [record.toolCalls, record.tool_calls].some(
53+
(toolCalls) =>
54+
Array.isArray(toolCalls) &&
55+
toolCalls.some((toolCall) => readToolName(toolCall) === "sessions_yield"),
4656
);
4757
}
4858

0 commit comments

Comments
 (0)