@@ -191,6 +191,7 @@ export function resolveReasoningOnlyRetryInstruction(params: {
191191}
192192
193193type SettledToolCall = { id : string | null ; name : string | null } ;
194+ type SettledToolResult = { toolCallId ?: unknown ; toolName ?: unknown ; isError ?: unknown } ;
194195
195196function 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}
0 commit comments