Skip to content

Commit 112f37f

Browse files
committed
fix(agents): finish settled failed-tool turns instead of dropping replies
1 parent c43ba8e commit 112f37f

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
@@ -6777,6 +6777,79 @@ describe("qa mock openai server", () => {
67776777
});
67786778
expect(outputText(laterHeartbeatPayload)).toBe("HEARTBEAT_OK");
67796779
});
6780+
6781+
it("scripts one failure-honest Code Mode terminal-tool continuation (#118274)", async () => {
6782+
const server = await startMockServer();
6783+
const prompt =
6784+
"Failed tool terminal recovery QA check: read the missing file, then respond with exact marker: `QA-FAILED-TOOL-FINALIZED-OK`.";
6785+
const codeModeTools = [
6786+
{
6787+
type: "function",
6788+
name: "exec",
6789+
parameters: {
6790+
type: "object",
6791+
properties: { code: { type: "string" } },
6792+
required: ["code"],
6793+
},
6794+
},
6795+
{
6796+
type: "function",
6797+
name: "wait",
6798+
parameters: {
6799+
type: "object",
6800+
properties: { runId: { type: "string" } },
6801+
required: ["runId"],
6802+
},
6803+
},
6804+
];
6805+
6806+
const toolPlan = await postStreamingResponses(server, {
6807+
model: "gpt-5.6-luna",
6808+
tools: codeModeTools,
6809+
input: [makeUserInput(prompt)],
6810+
});
6811+
const plannedResponse = await toolPlan.text();
6812+
expect(plannedResponse).toContain('"name":"exec"');
6813+
expect(plannedResponse).toContain("qa-failed-terminal-missing-file.txt");
6814+
const plannedRequest = requireRecord(
6815+
await (await fetch(`${server.baseUrl}/debug/last-request`)).json(),
6816+
"failed terminal tool plan",
6817+
);
6818+
expect(plannedRequest.plannedToolName).toBe("read");
6819+
expect(plannedRequest.plannedWireToolName).toBe("exec");
6820+
6821+
const failedToolOutput = makeToolOutputWithCallId(
6822+
String(plannedRequest.plannedToolCallId),
6823+
JSON.stringify({ status: "failed", error: "ENOENT: qa-failed-terminal-missing-file.txt" }),
6824+
);
6825+
const dishonestFinalization = await expectNonStreamingResponsesJson<{
6826+
output?: Array<{ content?: Array<{ text?: string }> }>;
6827+
}>(server, {
6828+
model: "gpt-5.6-luna",
6829+
input: [
6830+
makeUserInput(prompt),
6831+
makeUserInput(QA_SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION),
6832+
failedToolOutput,
6833+
],
6834+
});
6835+
expect(outputText(dishonestFinalization)).toBe("FAILED-TOOL-HONESTY-INSTRUCTION-MISSING");
6836+
6837+
const recovered = await expectNonStreamingResponsesJson<{
6838+
output?: Array<{ content?: Array<{ text?: string }> }>;
6839+
}>(server, {
6840+
model: "gpt-5.6-luna",
6841+
input: [
6842+
makeUserInput(prompt),
6843+
makeUserInput(
6844+
`${QA_SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION} If any tool failed, state that failure plainly and do not claim it succeeded.`,
6845+
),
6846+
failedToolOutput,
6847+
],
6848+
});
6849+
expect(outputText(recovered)).toBe(
6850+
"The requested file could not be read: ENOENT. QA-FAILED-TOOL-FINALIZED-OK",
6851+
);
6852+
});
67806853
});
67816854

67826855
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)