Skip to content

Commit 41ee506

Browse files
committed
fix(agents): preserve terminal tool completion
1 parent a29d8c8 commit 41ee506

19 files changed

Lines changed: 353 additions & 135 deletions

‎src/agents/embedded-agent-runner/result-fallback-classifier.test.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -393,18 +393,22 @@ describe("classifyEmbeddedAgentRunResultForModelFallback", () => {
393393
});
394394
});
395395

396-
it("does not fallback after a yielded empty result records potential side effects", () => {
396+
it.each([
397+
{
398+
label: "a yielded empty result records potential side effects",
399+
meta: { replayInvalid: true, yielded: true, stopReason: "end_turn" },
400+
},
401+
{
402+
label: "an exact terminal tool batch intentionally completes the turn",
403+
meta: { intentionalTerminalCompletion: "tool-batch" as const },
404+
},
405+
])("does not fallback after $label", ({ meta }) => {
397406
const result = classifyEmbeddedAgentRunResultForModelFallback({
398407
provider: "openai",
399408
model: "gpt-5.5",
400409
result: {
401410
payloads: [],
402-
meta: {
403-
durationMs: 42,
404-
replayInvalid: true,
405-
yielded: true,
406-
stopReason: "end_turn",
407-
},
411+
meta: { durationMs: 42, ...meta },
408412
},
409413
});
410414

‎src/agents/embedded-agent-runner/result-fallback-classifier.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ export function hasDeliberateSilentTerminalReply(result: EmbeddedAgentRunResult)
7878
);
7979
}
8080

81+
export function hasIntentionalTerminalCompletion(result: EmbeddedAgentRunResult): boolean {
82+
return result.meta.intentionalTerminalCompletion === "tool-batch";
83+
}
84+
8185
function hasDeliverableAssistantPayload(result: {
8286
payloads?: unknown;
8387
meta?: { finalAssistantVisibleText?: unknown };
@@ -201,6 +205,7 @@ export function classifyEmbeddedAgentRunResultForModelFallback(params: {
201205
return null;
202206
}
203207
if (
208+
hasIntentionalTerminalCompletion(params.result) ||
204209
params.result.meta.aborted ||
205210
params.hasDirectlySentBlockReply === true ||
206211
params.hasBlockReplyPipelineOutput === true

‎src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts‎

Lines changed: 80 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ export function resolveReasoningOnlyRetryInstruction(params: {
191191
}
192192

193193
type SettledToolCall = { id: string | null; name: string | null };
194+
type SettledToolResult = { toolCallId?: unknown; toolName?: unknown; isError?: unknown };
194195

195196
function readSettledToolCalls(
196197
message: EmbeddedRunAttemptResult["currentAttemptAssistant"] | null | undefined,
@@ -211,23 +212,11 @@ function readSettledToolCalls(
211212
});
212213
}
213214

214-
/** Builds one fresh continuation after settled tools ended without a visible final answer. */
215-
export function resolveSettledToolTerminalContinuationInstruction(params: {
216-
provider?: string;
217-
modelId?: string;
218-
modelApi?: string;
219-
executionContract?: string;
220-
allowEmptyStopContinuation?: boolean;
221-
payloadCount: number;
222-
hasTerminalToolPresentation?: boolean;
223-
aborted: boolean;
224-
timedOut: boolean;
225-
attempt: IncompleteTurnAttempt;
226-
}): string | null {
227-
const currentAttemptAssistant = params.attempt.currentAttemptAssistant;
228-
const snapshot = params.attempt.messagesSnapshot ?? [];
215+
/** Proves settlement and intentional termination for the exact current-turn tool-call batch. */
216+
export function resolveSettledToolBatchEvidence(attempt: IncompleteTurnAttempt) {
217+
const snapshot = attempt.messagesSnapshot ?? [];
229218
const latestUserIndex = snapshot.findLastIndex((message) => message.role === "user");
230-
let assistant: EmbeddedRunAttemptResult["currentAttemptAssistant"] = currentAttemptAssistant;
219+
let assistant = attempt.currentAttemptAssistant;
231220
let assistantIndex = assistant ? snapshot.indexOf(assistant) : -1;
232221
if (assistantIndex <= latestUserIndex || readSettledToolCalls(assistant).length === 0) {
233222
assistantIndex = snapshot.findLastIndex(
@@ -236,106 +225,112 @@ export function resolveSettledToolTerminalContinuationInstruction(params: {
236225
message.role === "assistant" &&
237226
readSettledToolCalls(message).length > 0,
238227
);
239-
const assistantCandidate = assistantIndex >= 0 ? snapshot[assistantIndex] : undefined;
240-
assistant = assistantCandidate?.role === "assistant" ? assistantCandidate : undefined;
228+
const candidate = assistantIndex >= 0 ? snapshot[assistantIndex] : undefined;
229+
assistant = candidate?.role === "assistant" ? candidate : undefined;
241230
}
242-
const terminal = params.attempt.terminal;
243-
const idlePromptTimeout =
244-
terminal.kind === "timeout" &&
245-
terminal.phase === "prompt" &&
246-
terminal.source === "idle" &&
247-
params.attempt.currentAttemptReplayMetadata?.hadPotentialSideEffects === true;
248-
const emptyStopAfterSettledTools = Boolean(
249-
params.allowEmptyStopContinuation &&
250-
currentAttemptAssistant?.stopReason === "stop" &&
251-
params.attempt.toolMetas.length > 0 &&
252-
params.attempt.toolMetas.every((tool) => tool.isError !== true && tool.asyncStarted !== true) &&
253-
params.attempt.itemLifecycle.startedCount > 0 &&
254-
params.attempt.itemLifecycle.completedCount === params.attempt.itemLifecycle.startedCount &&
255-
params.attempt.itemLifecycle.activeCount === 0 &&
256-
!hasAcceptedSessionSpawn(params.attempt.acceptedSessionSpawns) &&
257-
isEmptyResponseAssistantTurn({
258-
payloadCount: params.payloadCount,
259-
attempt: params.attempt,
260-
}),
261-
);
262-
// Idle is not proof of settlement: skipped or partially dispatched tools must
263-
// never be described as completed. Match each terminal call's id and owner to
264-
// its own current-batch result; a reported failure is settled, not successful.
265231
const requestedToolCalls = readSettledToolCalls(assistant);
266-
// Scan only results AFTER the terminal assistant: the snapshot spans the whole
267-
// session, and a prior turn's toolResult with a model-reused id would otherwise
268-
// prove "completion" for a batch that never dispatched. Assistant not found in
269-
// the snapshot fails closed to the existing incomplete-turn error.
232+
// Results must follow their owning assistant; session-wide reused ids cannot settle a new turn.
270233
const settledToolResults = new Map(
271234
(assistantIndex >= 0 ? snapshot.slice(assistantIndex + 1) : []).flatMap((message) => {
272-
const result = message as {
273-
role?: unknown;
274-
toolCallId?: unknown;
275-
toolName?: unknown;
276-
isError?: unknown;
277-
};
278-
return result.role === "toolResult" &&
279-
typeof result.toolCallId === "string" &&
280-
typeof result.toolName === "string"
281-
? [
282-
[
283-
result.toolCallId,
284-
{ toolName: result.toolName, isError: result.isError === true },
285-
] as const,
286-
]
235+
const { toolCallId, toolName, isError } = message as SettledToolResult;
236+
return message.role === "toolResult" &&
237+
typeof toolCallId === "string" &&
238+
typeof toolName === "string"
239+
? [[toolCallId, { toolName, isError: isError === true }] as const]
287240
: [];
288241
}),
289242
);
290243
const allToolsProvenSettled =
291-
params.attempt.itemLifecycle.startedCount > 0 &&
292-
params.attempt.itemLifecycle.completedCount === params.attempt.itemLifecycle.startedCount &&
293-
params.attempt.itemLifecycle.activeCount === 0 &&
244+
attempt.itemLifecycle.startedCount > 0 &&
245+
attempt.itemLifecycle.completedCount === attempt.itemLifecycle.startedCount &&
246+
attempt.itemLifecycle.activeCount === 0 &&
294247
requestedToolCalls.length > 0 &&
295248
requestedToolCalls.every(
296249
({ id, name }) =>
297250
id !== null && name !== null && settledToolResults.get(id)?.toolName === name,
298251
);
299-
const failedTerminalToolNames = new Set(
252+
const failedToolNames = new Set(
300253
requestedToolCalls.flatMap(({ id, name }) =>
301254
id !== null && name !== null && settledToolResults.get(id)?.isError === true ? [name] : [],
302255
),
303256
);
304-
const hasSettledTerminalToolFailure = allToolsProvenSettled && failedTerminalToolNames.size > 0;
305-
const hasIntentionalTerminalToolBatch =
257+
const intentionalTermination =
306258
allToolsProvenSettled &&
307-
requestedToolCalls.every(
308-
({ id, name }) =>
309-
params.attempt.toolMetas.findLast(
310-
(meta) => meta.toolCallId === id && meta.toolName === name,
311-
)?.terminate === true,
312-
);
259+
assistant?.stopReason === "toolUse" &&
260+
failedToolNames.size === 0 &&
261+
!attempt.lastToolError &&
262+
!hasAsyncActivity(attempt.toolMetas) &&
263+
requestedToolCalls.every(({ id, name }) => {
264+
const metadata = attempt.toolMetas.findLast(
265+
(entry) => entry.toolCallId === id && entry.toolName === name,
266+
);
267+
return metadata?.terminate === true && metadata.isError !== true;
268+
});
269+
return { assistant, allToolsProvenSettled, failedToolNames, intentionalTermination };
270+
}
271+
272+
/** Builds one fresh continuation after settled tools ended without a visible final answer. */
273+
export function resolveSettledToolTerminalContinuationInstruction(params: {
274+
provider?: string;
275+
modelId?: string;
276+
modelApi?: string;
277+
executionContract?: string;
278+
allowEmptyStopContinuation?: boolean;
279+
payloadCount: number;
280+
hasTerminalToolPresentation?: boolean;
281+
aborted: boolean;
282+
timedOut: boolean;
283+
attempt: IncompleteTurnAttempt;
284+
}): string | null {
285+
const { attempt } = params;
286+
const { assistant, allToolsProvenSettled, failedToolNames, intentionalTermination } =
287+
resolveSettledToolBatchEvidence(attempt);
288+
const terminal = attempt.terminal;
289+
const idlePromptTimeout =
290+
terminal.kind === "timeout" &&
291+
terminal.phase === "prompt" &&
292+
terminal.source === "idle" &&
293+
attempt.currentAttemptReplayMetadata?.hadPotentialSideEffects === true;
294+
const emptyStopAfterSettledTools = Boolean(
295+
params.allowEmptyStopContinuation &&
296+
attempt.currentAttemptAssistant?.stopReason === "stop" &&
297+
attempt.toolMetas.length > 0 &&
298+
attempt.toolMetas.every((tool) => tool.isError !== true && tool.asyncStarted !== true) &&
299+
attempt.itemLifecycle.startedCount > 0 &&
300+
attempt.itemLifecycle.completedCount === attempt.itemLifecycle.startedCount &&
301+
attempt.itemLifecycle.activeCount === 0 &&
302+
!hasAcceptedSessionSpawn(attempt.acceptedSessionSpawns) &&
303+
isEmptyResponseAssistantTurn({
304+
payloadCount: params.payloadCount,
305+
attempt,
306+
}),
307+
);
313308
// ToolErrorSummary has no call id: its owner must match a failed result in the
314309
// proven terminal batch, or a stale/unrelated error could authorize finalization.
315310
const hasUnsettledToolError = Boolean(
316-
params.attempt.lastToolError &&
311+
attempt.lastToolError &&
317312
(assistant?.stopReason !== "toolUse" ||
318-
!hasSettledTerminalToolFailure ||
319-
!failedTerminalToolNames.has(params.attempt.lastToolError.toolName)),
313+
!allToolsProvenSettled ||
314+
!failedToolNames.has(attempt.lastToolError.toolName)),
320315
);
321316
if (
322317
params.payloadCount !== 0 ||
323318
params.hasTerminalToolPresentation ||
324319
params.aborted ||
325-
((params.timedOut || params.attempt.terminal.kind === "timeout") && !idlePromptTimeout) ||
326-
(terminal.kind === "failed" && !params.attempt.settledTurnFinalizationContext) ||
320+
((params.timedOut || terminal.kind === "timeout") && !idlePromptTimeout) ||
321+
(terminal.kind === "failed" && !attempt.settledTurnFinalizationContext) ||
327322
(assistant?.stopReason === "toolUse" ? !allToolsProvenSettled : !emptyStopAfterSettledTools) ||
328-
hasIntentionalTerminalToolBatch ||
323+
intentionalTermination ||
329324
hasUnsettledToolError ||
330-
hasAsyncActivity(params.attempt.toolMetas) ||
331-
hasAcceptedSessionSpawn(params.attempt.acceptedSessionSpawns) ||
332-
params.attempt.clientToolCalls ||
333-
params.attempt.yieldDetected ||
334-
params.attempt.didSendDeterministicApprovalPrompt
325+
hasAsyncActivity(attempt.toolMetas) ||
326+
hasAcceptedSessionSpawn(attempt.acceptedSessionSpawns) ||
327+
attempt.clientToolCalls ||
328+
attempt.yieldDetected ||
329+
attempt.didSendDeterministicApprovalPrompt
335330
) {
336331
return null;
337332
}
338-
if (hasCompletedMessagingToolDeliveryEvidence(params.attempt)) {
333+
if (hasCompletedMessagingToolDeliveryEvidence(attempt)) {
339334
return null;
340335
}
341336
if (
@@ -348,7 +343,7 @@ export function resolveSettledToolTerminalContinuationInstruction(params: {
348343
) {
349344
return null;
350345
}
351-
return hasSettledTerminalToolFailure
346+
return allToolsProvenSettled && failedToolNames.size > 0
352347
? `${SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION} ${TOOL_FAILURE_INSTRUCTION}`
353348
: SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION;
354349
}

‎src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export function resolveIncompleteTurnPayloadText(params: {
4747
externalAbort: boolean;
4848
timedOut: boolean;
4949
hadPotentialSideEffects?: boolean;
50+
hasIntentionalTerminalCompletion?: boolean;
5051
attempt: IncompleteTurnAttempt;
5152
}): string | null {
5253
// Prefer the current attempt's terminal message. The session fallback can
@@ -78,7 +79,8 @@ export function resolveIncompleteTurnPayloadText(params: {
7879
params.attempt.clientToolCalls ||
7980
params.attempt.yieldDetected ||
8081
params.attempt.didSendDeterministicApprovalPrompt ||
81-
params.attempt.lastToolError
82+
params.attempt.lastToolError ||
83+
params.hasIntentionalTerminalCompletion
8284
) {
8385
return null;
8486
}

‎src/agents/embedded-agent-runner/run/settled-tool-evidence.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -348,9 +348,14 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
348348
lastToolError: { toolName: "exec", error: "post-processing error" },
349349
},
350350
{ label: "no remaining failure summary", lastToolError: undefined },
351+
{
352+
label: "a terminal-marked failed tool",
353+
lastToolError: { toolName: "exec", error: "post-processing error" },
354+
failedToolTerminate: true,
355+
},
351356
])(
352357
"recognizes successful and failed current-batch tools with $label (#118274)",
353-
({ lastToolError }) => {
358+
({ lastToolError, failedToolTerminate }) => {
354359
const toolUseAssistant = makeLastAssistant({
355360
stopReason: "toolUse",
356361
content: [
@@ -361,7 +366,15 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
361366
const instruction = resolveSettledToolTerminalContinuationInstruction(
362367
makeSettledContinuationParams({
363368
assistantTexts: [],
364-
toolMetas: [{ toolName: "read" }, { toolName: "exec", isError: true }],
369+
toolMetas: [
370+
{ toolName: "read" },
371+
{
372+
toolName: "exec",
373+
toolCallId: "tool_failed",
374+
isError: true,
375+
...(failedToolTerminate ? { terminate: true } : {}),
376+
},
377+
],
365378
itemLifecycle: { startedCount: 2, completedCount: 2, activeCount: 0 },
366379
messagesSnapshot: [
367380
toolUseAssistant,

0 commit comments

Comments
 (0)