Skip to content

Commit 1fedcca

Browse files
authored
fix(agents): finish settled failed-tool turns instead of dropping replies (#118344)
1 parent b36e9af commit 1fedcca

9 files changed

Lines changed: 963 additions & 27 deletions

File tree

‎extensions/qa-lab/src/providers/mock-openai/server.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6943,6 +6943,79 @@ describe("qa mock openai server", () => {
69436943
});
69446944
expect(outputText(laterHeartbeatPayload)).toBe("HEARTBEAT_OK");
69456945
});
6946+
6947+
it("scripts one failure-honest Code Mode terminal-tool continuation (#118274)", async () => {
6948+
const server = await startMockServer();
6949+
const prompt =
6950+
"Failed tool terminal recovery QA check: read the missing file, then respond with exact marker: `QA-FAILED-TOOL-FINALIZED-OK`.";
6951+
const codeModeTools = [
6952+
{
6953+
type: "function",
6954+
name: "exec",
6955+
parameters: {
6956+
type: "object",
6957+
properties: { code: { type: "string" } },
6958+
required: ["code"],
6959+
},
6960+
},
6961+
{
6962+
type: "function",
6963+
name: "wait",
6964+
parameters: {
6965+
type: "object",
6966+
properties: { runId: { type: "string" } },
6967+
required: ["runId"],
6968+
},
6969+
},
6970+
];
6971+
6972+
const toolPlan = await postStreamingResponses(server, {
6973+
model: "gpt-5.6-luna",
6974+
tools: codeModeTools,
6975+
input: [makeUserInput(prompt)],
6976+
});
6977+
const plannedResponse = await toolPlan.text();
6978+
expect(plannedResponse).toContain('"name":"exec"');
6979+
expect(plannedResponse).toContain("qa-failed-terminal-missing-file.txt");
6980+
const plannedRequest = requireRecord(
6981+
await (await fetch(`${server.baseUrl}/debug/last-request`)).json(),
6982+
"failed terminal tool plan",
6983+
);
6984+
expect(plannedRequest.plannedToolName).toBe("read");
6985+
expect(plannedRequest.plannedWireToolName).toBe("exec");
6986+
6987+
const failedToolOutput = makeToolOutputWithCallId(
6988+
String(plannedRequest.plannedToolCallId),
6989+
JSON.stringify({ status: "failed", error: "ENOENT: qa-failed-terminal-missing-file.txt" }),
6990+
);
6991+
const dishonestFinalization = await expectNonStreamingResponsesJson<{
6992+
output?: Array<{ content?: Array<{ text?: string }> }>;
6993+
}>(server, {
6994+
model: "gpt-5.6-luna",
6995+
input: [
6996+
makeUserInput(prompt),
6997+
makeUserInput(QA_SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION),
6998+
failedToolOutput,
6999+
],
7000+
});
7001+
expect(outputText(dishonestFinalization)).toBe("FAILED-TOOL-HONESTY-INSTRUCTION-MISSING");
7002+
7003+
const recovered = await expectNonStreamingResponsesJson<{
7004+
output?: Array<{ content?: Array<{ text?: string }> }>;
7005+
}>(server, {
7006+
model: "gpt-5.6-luna",
7007+
input: [
7008+
makeUserInput(prompt),
7009+
makeUserInput(
7010+
`${QA_SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION} If any tool failed, state that failure plainly and do not claim it succeeded.`,
7011+
),
7012+
failedToolOutput,
7013+
],
7014+
});
7015+
expect(outputText(recovered)).toBe(
7016+
"The requested file could not be read: ENOENT. QA-FAILED-TOOL-FINALIZED-OK",
7017+
);
7018+
});
69467019
});
69477020

69487021
describe("qa mock openai server provider variant tagging", () => {

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ const QA_STREAMING_TOOL_PROGRESS_FAMILY_PROMPT_RE =
173173
const QA_STREAMING_TOOL_PROGRESS_CONTINUATION_RE =
174174
/^Continue with (?:the current Matrix QA scenario|the QA scenario plan and report worked, failed, and blocked items)\.$/i;
175175
const QA_CODE_MODE_TARGET_MARKER = "qa-code-mode-target:";
176+
const QA_FAILED_TOOL_TERMINAL_RECOVERY_PROMPT_RE = /failed tool terminal recovery qa check/i;
176177

177178
function isStreamingToolProgressContinuationText(text: string) {
178179
const trimmed = text.trim();
@@ -542,6 +543,10 @@ async function buildResponsesPayload(
542543
QA_EMPTY_RESPONSE_SIDE_EFFECT_RECOVERY_PROMPT_RE.test(prompt) ||
543544
(prompt.includes(QA_SETTLED_TOOL_TERMINAL_CONTINUATION_NEEDLE) &&
544545
QA_EMPTY_RESPONSE_SIDE_EFFECT_RECOVERY_PROMPT_RE.test(allInputText));
546+
const isActiveFailedToolTerminalRecovery =
547+
QA_FAILED_TOOL_TERMINAL_RECOVERY_PROMPT_RE.test(prompt) ||
548+
(prompt.includes(QA_SETTLED_TOOL_TERMINAL_CONTINUATION_NEEDLE) &&
549+
QA_FAILED_TOOL_TERMINAL_RECOVERY_PROMPT_RE.test(allInputText));
545550
const hasCallableCodeMode = hasCodeModeExecSurface(toolDeclarationBody);
546551
const canCallSessionsSpawn =
547552
hasToolDefinition(toolDeclarationBody, "sessions_spawn") || hasCallableCodeMode;
@@ -756,6 +761,19 @@ async function buildResponsesPayload(
756761
}
757762
return buildAssistantEvents("");
758763
}
764+
if (isActiveFailedToolTerminalRecovery) {
765+
if (allInputText.includes(QA_SETTLED_TOOL_TERMINAL_CONTINUATION_NEEDLE)) {
766+
if (!allInputText.includes("state that failure plainly and do not claim it succeeded")) {
767+
return buildAssistantEvents("FAILED-TOOL-HONESTY-INSTRUCTION-MISSING");
768+
}
769+
const marker = exactMarkerDirective ?? exactReplyDirective ?? "QA-FAILED-TOOL-FINALIZED-OK";
770+
return buildAssistantEvents(`The requested file could not be read: ENOENT. ${marker}`);
771+
}
772+
if (!hasCompletedToolOutput) {
773+
return buildToolCallEventsWithArgs("read", { path: "qa-failed-terminal-missing-file.txt" });
774+
}
775+
return buildAssistantEvents("FAILED-TOOL-TERMINAL-WAS-REPLAYED");
776+
}
759777
if (isHeartbeatPrompt(prompt)) {
760778
return buildAssistantEvents("HEARTBEAT_OK");
761779
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
title: QA channel final reply after a failed terminal tool
2+
3+
scenario:
4+
id: qa-channel-failed-tool-terminal-finalization
5+
surface: channel
6+
coverage:
7+
primary: [agent-runtime.failure-recovery-empty-response-recovery]
8+
secondary: [channels.qa-channel-final-reply, agent-runtime.failure-recovery-retry-policy]
9+
regressionRefs:
10+
- openclaw/openclaw#118274
11+
gatewayConfigPatch:
12+
tools:
13+
codeMode:
14+
enabled: true
15+
objective: Verify a settled failed terminal tool receives one failure-honest, tool-free finalization and one channel reply.
16+
successCriteria:
17+
- Code Mode dispatches exactly one missing-file read and records one failed exec result.
18+
- The failed tool call is never replayed or described as successful.
19+
- The model receives one tools-disabled finalization and qa-channel delivers exactly one visible reply.
20+
codeRefs:
21+
- src/agents/embedded-agent-runner/run/incomplete-turn.ts
22+
- src/agents/embedded-agent-runner/run/code-mode-repair.ts
23+
- extensions/qa-lab/src/providers/mock-openai/server.ts
24+
execution:
25+
kind: flow
26+
suiteIsolation: isolated
27+
isolationReason: Enables Code Mode and verifies one exact tool call and isolated qa-channel delivery.
28+
channel: qa-channel
29+
retryCount: 0
30+
summary: Prove a real failed terminal Code Mode tool still produces one failure-honest qa-channel reply.
31+
config:
32+
requiredProviderMode: mock-openai
33+
channelId: qa-failed-terminal
34+
promptSnippet: Failed tool terminal recovery QA check
35+
retryNeedle: The previous assistant turn completed its tool calls but did not produce a user-visible answer.
36+
failureHonestyNeedle: state that failure plainly and do not claim it succeeded
37+
expectedMarker: QA-FAILED-TOOL-FINALIZED-OK
38+
expectedReply: "The requested file could not be read: ENOENT. QA-FAILED-TOOL-FINALIZED-OK"
39+
40+
flow:
41+
steps:
42+
- name: finalizes one failed Code Mode tool without replaying it
43+
actions:
44+
- assert:
45+
expr: "env.providerMode === config.requiredProviderMode"
46+
message: failed-terminal qa-channel proof requires mock-openai
47+
- call: waitForGatewayHealthy
48+
args:
49+
- ref: env
50+
- 60000
51+
- call: waitForQaChannelReady
52+
args:
53+
- ref: env
54+
- 60000
55+
- call: reset
56+
- set: requestCursorBefore
57+
value:
58+
expr: "(await fetchJson(`${env.mock.baseUrl}/debug/request-cursor`)).cursor"
59+
- set: outboundStartIndex
60+
value:
61+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound').length"
62+
- set: sessionKey
63+
value:
64+
expr: "`agent:qa:qa-channel:group:group:${config.channelId}`"
65+
- sendInbound:
66+
conversation:
67+
id:
68+
ref: config.channelId
69+
kind: group
70+
senderId: qa-driver
71+
senderName: QA Driver
72+
text: "@openclaw Failed tool terminal recovery QA check: read the missing workspace file, then respond with exact marker: `QA-FAILED-TOOL-FINALIZED-OK`."
73+
- waitForOutbound:
74+
conversation:
75+
id:
76+
ref: config.channelId
77+
kind: group
78+
sinceIndex:
79+
ref: outboundStartIndex
80+
textIncludes:
81+
ref: config.expectedMarker
82+
timeoutMs: 60000
83+
saveAs: reply
84+
- set: scenarioRequests
85+
value:
86+
expr: "(await fetchJson(`${env.mock.baseUrl}/debug/requests?after=${requestCursorBefore}`)).filter((request) => String(request.allInputText ?? '').includes(config.promptSnippet))"
87+
- set: readPlans
88+
value:
89+
expr: "scenarioRequests.filter((request) => request.plannedToolName === 'read')"
90+
- set: finalizations
91+
value:
92+
expr: "scenarioRequests.filter((request) => String(request.allInputText ?? '').includes(config.retryNeedle))"
93+
- assert:
94+
expr: "readPlans.length === 1 && readPlans[0].plannedWireToolName === 'exec'"
95+
message:
96+
expr: "`expected one Code Mode read plan, got ${JSON.stringify(readPlans)}`"
97+
- assert:
98+
expr: "finalizations.length === 1 && String(finalizations[0].allInputText ?? '').includes(config.failureHonestyNeedle)"
99+
message:
100+
expr: "`expected one failure-honest finalization, got ${JSON.stringify(finalizations)}`"
101+
- set: replayedExecCalls
102+
value:
103+
expr: "(Array.isArray(finalizations[0].body?.input) ? finalizations[0].body.input : []).filter((item) => item?.type === 'function_call' && item.name === 'exec' && String(item.arguments ?? '').includes('qa-failed-terminal-missing-file.txt'))"
104+
- set: failedExecOutputs
105+
value:
106+
expr: "(Array.isArray(finalizations[0].body?.input) ? finalizations[0].body.input : []).filter((item) => item?.type === 'function_call_output' && item.call_id === replayedExecCalls[0]?.call_id && /ENOENT|no such file/i.test(typeof item.output === 'string' ? item.output : JSON.stringify(item.output ?? '')))"
107+
- assert:
108+
expr: "replayedExecCalls.length === 1 && failedExecOutputs.length === 1 && finalizations[0].toolOutputCallId === replayedExecCalls[0].call_id"
109+
message:
110+
expr: "`finalization did not preserve the normalized parent exec/result pairing: calls=${JSON.stringify(replayedExecCalls.map((item) => item.call_id))} outputs=${JSON.stringify(failedExecOutputs.map((item) => item.call_id))}`"
111+
- assert:
112+
expr: "!Array.isArray(finalizations[0].body?.tools) || finalizations[0].body.tools.length === 0"
113+
message: failed-tool finalization exposed a replayable model tool surface
114+
- call: readSessionTranscriptSummary
115+
saveAs: transcript
116+
args:
117+
- ref: env
118+
- ref: sessionKey
119+
- assert:
120+
expr: "transcript.assistantToolCallCounts.exec === 1 && transcript.completedToolCallCounts.exec === 1 && !transcript.successfulToolCallCounts.exec"
121+
message:
122+
expr: "`expected exactly one settled failed exec result, got ${JSON.stringify(transcript)}`"
123+
- set: deliveries
124+
value:
125+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && message.conversation.id === config.channelId)"
126+
- assert:
127+
expr: "deliveries.length === 1 && reply.text.trim() === config.expectedReply"
128+
message:
129+
expr: "`expected exactly one failure-honest reply, got ${JSON.stringify(deliveries)}`"
130+
detailsExpr: "`${reply.text}; calls=${String(transcript.assistantToolCallCounts.exec)} failed=${String(transcript.completedToolCallCounts.exec)} finalizations=${String(finalizations.length)}`"

0 commit comments

Comments
 (0)