From b0708d2f5f9869820a91531e9dcde46b91a359ae Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:25:24 +0000 Subject: [PATCH 1/2] fix(agent): enforce tool timeouts and abort signals across background grace, approval resume, and MCP wrappers --- packages/agent/src/lib/model-result.ts | 331 +++++++++++++----- packages/agent/src/mcp/tool-wrapper.ts | 29 +- .../tests/unit/async-tool-background.test.ts | 191 ++++++++++ .../tests/unit/mcp/call-tool-shape.test.ts | 124 ++++++- .../tests/unit/tool-cancellation.test.ts | 314 +++++++++++++++++ 5 files changed, 896 insertions(+), 93 deletions(-) diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index bf39a6f6..c424cd5a 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -2978,10 +2978,41 @@ export class ModelResult< private async settleAsyncInvocationAsUnsent( tc: ParsedToolCall, invocation: AsyncToolInvocation, + deadline?: { + timeoutMs: number | undefined; + controller: AbortController; + }, ): Promise> { if (invocation.asyncMode === 'background') { try { - const result = await invocation.run(); + const work = invocation.run(); + if (deadline) { + work.catch(() => undefined); + const raced = await this.raceToolDeadline( + work, + String(tc.name), + deadline.timeoutMs, + deadline.controller, + ); + if (raced === 'timeout') { + const message = `Tool "${tc.name}" timed out after ${deadline.timeoutMs}ms`; + this.broadcastToolResult( + tc.id, + String(tc.name), + this.toolSourceByName(String(tc.name)), + { + error: message, + } as InferToolOutputsUnion, + ); + return createRejectedResult(tc.id, String(tc.name), message); + } + return createUnsentResult( + tc.id, + String(tc.name), + await this.unsentModelOutput(tc as ParsedToolCall, raced), + ); + } + const result = await work; return createUnsentResult( tc.id, String(tc.name), @@ -3063,42 +3094,76 @@ export class ModelResult< // Route through runToolWithHooks so PreToolUse/PostToolUse fire even on // the auto-approve path. `runToolWithHooks` also fails closed on raw // JSON-parse failures so hooks never see a malformed payload. - const hookOutcome = await this.runToolWithHooks( - tool, - tc as ParsedToolCall, - turnContext, - ); + const { controller, signal, timeoutMs } = this.composeToolSignal(String(tc.name), tc.id); + const runBinding = this.createRunBinding(tc.id); + try { + const executionPromise = this.runToolWithHooks( + tool, + tc as ParsedToolCall, + turnContext, + undefined, + { + signal, + callId: tc.id, + ...(this.currentState?.id !== undefined && { + conversationId: this.currentState.id, + }), + client: this.options.client, + runExtras: buildRunExtras(tool, runBinding), + }, + ); - if (hookOutcome.type === 'parse_error') { - this.broadcastToolResult(tc.id, String(tc.name), isMcpTool(tool) ? 'mcp' : 'client', { - error: hookOutcome.errorMessage, - } as InferToolOutputsUnion); - return createRejectedResult(tc.id, String(tc.name), hookOutcome.errorMessage); - } + const hookOutcome = await this.raceToolDeadline( + executionPromise, + String(tc.name), + timeoutMs, + controller, + ); - if (hookOutcome.type === 'hook_blocked') { - return createRejectedResult(tc.id, String(tc.name), hookOutcome.reason); - } + if (hookOutcome === 'timeout') { + const message = `Tool "${tc.name}" timed out after ${timeoutMs}ms`; + this.broadcastToolResult(tc.id, String(tc.name), isMcpTool(tool) ? 'mcp' : 'client', { + error: message, + } as InferToolOutputsUnion); + return createRejectedResult(tc.id, String(tc.name), message); + } - const result = hookOutcome.result; + if (hookOutcome.type === 'parse_error') { + this.broadcastToolResult(tc.id, String(tc.name), isMcpTool(tool) ? 'mcp' : 'client', { + error: hookOutcome.errorMessage, + } as InferToolOutputsUnion); + return createRejectedResult(tc.id, String(tc.name), hookOutcome.errorMessage); + } - if (result === null) { - // HITL tool paused — no unsent result for this call in this round - return null; - } + if (hookOutcome.type === 'hook_blocked') { + return createRejectedResult(tc.id, String(tc.name), hookOutcome.reason); + } - if (isAsyncToolInvocation(result)) { - return this.settleAsyncInvocationAsUnsent(tc, result); - } + const result = hookOutcome.result; - if (result.error) { - return createRejectedResult(tc.id, String(tc.name), result.error.message); + if (result === null) { + // HITL tool paused — no unsent result for this call in this round + return null; + } + + if (isAsyncToolInvocation(result)) { + return await this.settleAsyncInvocationAsUnsent(tc, result, { + timeoutMs, + controller, + }); + } + + if (result.error) { + return createRejectedResult(tc.id, String(tc.name), result.error.message); + } + return createUnsentResult( + tc.id, + String(tc.name), + await this.unsentModelOutput(tc as ParsedToolCall, result.result), + ); + } finally { + this.inflightToolControllers.delete(tc.id); } - return createUnsentResult( - tc.id, - String(tc.name), - await this.unsentModelOutput(tc as ParsedToolCall, result.result), - ); }); const settledResults = await Promise.allSettled(toolCallPromises); @@ -4259,13 +4324,30 @@ export class ModelResult< work.catch(() => undefined); // Grace window: work settling in time yields a plain synchronous output. + // Arm the per-tool timeoutMs deadline immediately when the background work + // starts — independent of graceMs — so timeoutMs < graceMs (including the + // default 250ms graceMs) still aborts ctx.signal and settles on time. const graceMs = invocation.graceMs; + const timeoutMs = value.timeoutMs; if (graceMs > 0) { - // The timer is cleared when the work settles first (same discipline - // as raceToolDeadline) — it's unref'd, but a leaked timer is still a - // leaked timer. + // Both timers are cleared as soon as the race settles (same discipline + // as raceToolDeadline) — they are unref'd, but leaked timers are still + // leaked timers. let graceTimer: ReturnType | undefined; - const settled = await Promise.race([ + let timeoutTimer: ReturnType | undefined; + const raceParticipants: Array< + Promise< + | { + outcome: 'ok'; + result: unknown; + } + | { + outcome: 'error'; + error: unknown; + } + | 'pending' + > + > = [ work.then( (result) => ({ outcome: 'ok' as const, @@ -4286,10 +4368,43 @@ export class ModelResult< graceTimer.unref(); } }), - ]); + ]; + if (timeoutMs !== undefined && timeoutMs > 0) { + raceParticipants.push( + new Promise<{ + outcome: 'error'; + error: Error; + }>((resolve) => { + timeoutTimer = setTimeout(() => { + const timeoutError = Object.assign( + new Error(`Tool "${toolCall.name}" timed out after ${timeoutMs}ms`), + { + code: 'tool_timeout', + }, + ); + controller.abort(timeoutError); + resolve({ + outcome: 'error' as const, + error: timeoutError, + }); + }, timeoutMs); + if ( + typeof timeoutTimer === 'object' && + 'unref' in timeoutTimer && + typeof timeoutTimer.unref === 'function' + ) { + timeoutTimer.unref(); + } + }), + ); + } + const settled = await Promise.race(raceParticipants); if (graceTimer !== undefined) { clearTimeout(graceTimer); } + if (timeoutTimer !== undefined) { + clearTimeout(timeoutTimer); + } if (settled !== 'pending') { // Settled in-window: behave exactly like a regular tool. The call @@ -6144,66 +6259,110 @@ export class ModelResult< } } - const hookOutcome = await this.runToolWithHooks( - tool, - toolCall as ParsedToolCall, - turnContext, - undefined, - undefined, - false, + const { controller, signal, timeoutMs } = this.composeToolSignal( + String(toolCall.name), + callId, ); - - if (hookOutcome.type === 'parse_error') { - this.broadcastToolResult( - callId, - String(toolCall.name), - this.toolSourceByName(String(toolCall.name)), + const runBinding = this.createRunBinding(callId); + try { + const executionPromise = this.runToolWithHooks( + tool, + toolCall as ParsedToolCall, + turnContext, + undefined, { - error: hookOutcome.errorMessage, - } as InferToolOutputsUnion, + signal, + callId, + ...(this.currentState?.id !== undefined && { + conversationId: this.currentState.id, + }), + client: this.options.client, + runExtras: buildRunExtras(tool, runBinding), + }, + false, ); - unsentResults.push( - createRejectedResult(callId, String(toolCall.name), hookOutcome.errorMessage), + + const hookOutcome = await this.raceToolDeadline( + executionPromise, + String(toolCall.name), + timeoutMs, + controller, ); - continue; - } - if (hookOutcome.type === 'hook_blocked') { - unsentResults.push(createRejectedResult(callId, String(toolCall.name), hookOutcome.reason)); - continue; - } + if (hookOutcome === 'timeout') { + const message = `Tool "${toolCall.name}" timed out after ${timeoutMs}ms`; + this.broadcastToolResult( + callId, + String(toolCall.name), + this.toolSourceByName(String(toolCall.name)), + { + error: message, + } as InferToolOutputsUnion, + ); + unsentResults.push(createRejectedResult(callId, String(toolCall.name), message)); + continue; + } - const result = hookOutcome.result; + if (hookOutcome.type === 'parse_error') { + this.broadcastToolResult( + callId, + String(toolCall.name), + this.toolSourceByName(String(toolCall.name)), + { + error: hookOutcome.errorMessage, + } as InferToolOutputsUnion, + ); + unsentResults.push( + createRejectedResult(callId, String(toolCall.name), hookOutcome.errorMessage), + ); + continue; + } - if (result === null) { - // HITL tool paused on approval — keep the call visible to the caller - // via pendingToolCalls (status becomes 'awaiting_hitl' below). - hitlPausedIds.add(callId); - continue; - } + if (hookOutcome.type === 'hook_blocked') { + unsentResults.push( + createRejectedResult(callId, String(toolCall.name), hookOutcome.reason), + ); + continue; + } - if (isAsyncToolInvocation(result)) { - unsentResults.push( - await this.settleAsyncInvocationAsUnsent( - toolCall as ParsedToolCall, - result, - ), - ); - continue; - } + const result = hookOutcome.result; - if (result.error) { - unsentResults.push( - createRejectedResult(callId, String(toolCall.name), result.error.message), - ); - } else { - unsentResults.push( - createUnsentResult( - callId, - String(toolCall.name), - await this.unsentModelOutput(toolCall as ParsedToolCall, result.result), - ), - ); + if (result === null) { + // HITL tool paused on approval — keep the call visible to the caller + // via pendingToolCalls (status becomes 'awaiting_hitl' below). + hitlPausedIds.add(callId); + continue; + } + + if (isAsyncToolInvocation(result)) { + unsentResults.push( + await this.settleAsyncInvocationAsUnsent( + toolCall as ParsedToolCall, + result, + { + timeoutMs, + controller, + }, + ), + ); + continue; + } + + if (result.error) { + unsentResults.push( + createRejectedResult(callId, String(toolCall.name), result.error.message), + ); + } else { + unsentResults.push( + createUnsentResult( + callId, + String(toolCall.name), + await this.unsentModelOutput(toolCall as ParsedToolCall, result.result), + ), + ); + } + } finally { + this.inflightToolControllers.delete(callId); } } diff --git a/packages/agent/src/mcp/tool-wrapper.ts b/packages/agent/src/mcp/tool-wrapper.ts index 8c989ee9..9a22bacf 100644 --- a/packages/agent/src/mcp/tool-wrapper.ts +++ b/packages/agent/src/mcp/tool-wrapper.ts @@ -58,11 +58,28 @@ interface InvokeToolArgs { options: WrapToolOptions; mcpName: string; args: Record; + signal?: AbortSignal | undefined; onprogress?: (progress: Progress) => void; } +function composeToolSignal( + wrapperSignal: AbortSignal | undefined, + executionSignal: AbortSignal | undefined, +): AbortSignal | undefined { + if (wrapperSignal !== undefined && executionSignal !== undefined) { + return wrapperSignal === executionSignal + ? wrapperSignal + : AbortSignal.any([ + wrapperSignal, + executionSignal, + ]); + } + return executionSignal ?? wrapperSignal; +} + async function invokeTool(invokeArgs: InvokeToolArgs): Promise { - const { options, mcpName, args, onprogress } = invokeArgs; + const { options, mcpName, args, signal: executionSignal, onprogress } = invokeArgs; + const signal = composeToolSignal(options.signal, executionSignal); // SDK v2 signature is `callTool(params, options)` — v1's middle result-schema // argument is gone. Passing three args here would silently drop `signal` and // `onprogress` into an unread slot, killing cancellation and progress. @@ -72,8 +89,8 @@ async function invokeTool(invokeArgs: InvokeToolArgs): Promise { arguments: args, }, { - ...(options.signal !== undefined && { - signal: options.signal, + ...(signal !== undefined && { + signal, }), ...(onprogress !== undefined && { onprogress, @@ -138,7 +155,7 @@ export function wrapMcpTool(def: McpToolDef, options: WrapToolOptions): McpBrand inputSchema, eventSchema: progressEventSchema, outputSchema: outputSchema ?? z.unknown(), - execute: async function* (args: Record) { + execute: async function* (args: Record, ctx) { const queue: Array> = []; let notify: (() => void) | undefined; const onprogress = (p: Progress): void => { @@ -159,6 +176,7 @@ export function wrapMcpTool(def: McpToolDef, options: WrapToolOptions): McpBrand options, mcpName: def.name, args, + signal: ctx?.signal, onprogress, }); let done = false; @@ -200,11 +218,12 @@ export function wrapMcpTool(def: McpToolDef, options: WrapToolOptions): McpBrand ...(outputSchema !== undefined && { outputSchema, }), - execute: (args: Record) => + execute: (args: Record, ctx) => invokeTool({ options, mcpName: def.name, args, + signal: ctx?.signal, }), }), markOptions, diff --git a/packages/agent/tests/unit/async-tool-background.test.ts b/packages/agent/tests/unit/async-tool-background.test.ts index 8a95b4e4..6e6f70f7 100644 --- a/packages/agent/tests/unit/async-tool-background.test.ts +++ b/packages/agent/tests/unit/async-tool-background.test.ts @@ -609,4 +609,195 @@ describe('tool.background — placeholder & delivery', () => { }, ]); }); + + it('enforces timeoutMs < graceMs immediately during the grace window for signal-aware callbacks', async () => { + let observedAbort = false; + let completedPastTimeout = false; + const shortTimeout = tool({ + name: 'short_timeout_bg', + lifecycle: 'background', + inputSchema: z.object({}), + outputSchema: z.object({ + ok: z.boolean(), + }), + // Default graceMs is 250ms; timeoutMs is shorter than graceMs. + timeoutMs: 30, + run: async (_params, ctx) => { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + completedPastTimeout = true; + resolve(); + }, 150); + ctx.signal.addEventListener( + 'abort', + () => { + clearTimeout(timer); + observedAbort = true; + reject(ctx.signal.reason ?? new Error('aborted')); + }, + { + once: true, + }, + ); + }); + return { + ok: true, + }; + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_t1', 'short_timeout_bg', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'handled timeout'), + ]), + }); + + const text = await callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + shortTimeout, + ] as const, + }).getText(); + + expect(text).toBe('handled timeout'); + expect(observedAbort).toBe(true); + expect(completedPastTimeout).toBe(false); + + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const outputItem = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_t1', + ); + expect(outputItem?.output).toContain('timed out after 30ms'); + }); + + it('enforces timeoutMs < graceMs even when the background callback ignores ctx.signal', async () => { + let seenSignal: AbortSignal | undefined; + const unresponsive = tool({ + name: 'unresponsive_bg', + lifecycle: 'background', + inputSchema: z.object({}), + outputSchema: z.object({ + ok: z.boolean(), + }), + graceMs: 500, + timeoutMs: 30, + run: async (_params, ctx) => { + seenSignal = ctx.signal; + return new Promise<{ + ok: boolean; + }>(() => { + // Intentionally ignores ctx.signal and never settles. + }); + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_t2', 'unresponsive_bg', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'recovered'), + ]), + }); + + const text = await callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + unresponsive, + ] as const, + }).getText(); + + expect(text).toBe('recovered'); + expect(seenSignal?.aborted).toBe(true); + + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const outputItem = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_t2', + ); + expect(outputItem?.output).toContain('timed out after 30ms'); + }); + + it('allows background tool with timeoutMs > graceMs to transition to pending and complete', async () => { + const slow = tool({ + name: 'slow_within_timeout', + lifecycle: 'background', + inputSchema: z.object({}), + outputSchema: z.object({ + ok: z.boolean(), + }), + graceMs: 15, + timeoutMs: 500, + run: async () => { + await new Promise((resolve) => setTimeout(resolve, 40)); + return { + ok: true, + }; + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_t3', 'slow_within_timeout', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'waiting'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_3', [ + messageItem('msg_2', 'finished'), + ]), + }); + + const text = await callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + slow, + ] as const, + asyncTools: { + drainTimeoutMs: 2_000, + }, + }).getText(); + + expect(text).toBe('finished'); + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const placeholder = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_t3', + ); + expect(placeholder?.output).toContain('"status":"pending"'); + }); }); diff --git a/packages/agent/tests/unit/mcp/call-tool-shape.test.ts b/packages/agent/tests/unit/mcp/call-tool-shape.test.ts index 54ddfcbf..dae46029 100644 --- a/packages/agent/tests/unit/mcp/call-tool-shape.test.ts +++ b/packages/agent/tests/unit/mcp/call-tool-shape.test.ts @@ -37,11 +37,21 @@ function fakeClient(recorded: RecordedCall[]): Client { * The wrapped tool is an OpenRouter tool envelope — the callable lives at * `.function.execute`, not on the object itself. */ -function asExecute(t: unknown): (args: Record) => never { +function asExecute(t: unknown): ( + args: Record, + ctx?: { + signal?: AbortSignal; + }, +) => never { return ( t as { function: { - execute: (args: Record) => never; + execute: ( + args: Record, + ctx?: { + signal?: AbortSignal; + }, + ) => never; }; } ).function.execute; @@ -112,4 +122,114 @@ describe('callTool argument shape', () => { | undefined; expect(typeof options?.onprogress).toBe('function'); }); + + it('forwards per-execution ctx.signal when wrapper signal is not set', async () => { + const recorded: RecordedCall[] = []; + const execController = new AbortController(); + const t = wrapMcpTool(DEF, { + client: fakeClient(recorded), + emitProgress: false, + }); + + await asExecute(t)( + {}, + { + signal: execController.signal, + }, + ); + + const options = recorded[0]?.args[1] as + | { + signal?: AbortSignal; + } + | undefined; + expect(options?.signal).toBe(execController.signal); + }); + + it('composes wrapper options.signal and per-execution ctx.signal so either abort propagates', async () => { + const recorded: RecordedCall[] = []; + const wrapperController = new AbortController(); + const execController = new AbortController(); + const t = wrapMcpTool(DEF, { + client: fakeClient(recorded), + emitProgress: false, + signal: wrapperController.signal, + }); + + await asExecute(t)( + {}, + { + signal: execController.signal, + }, + ); + + const options = recorded[0]?.args[1] as + | { + signal?: AbortSignal; + } + | undefined; + expect(options?.signal).toBeInstanceOf(AbortSignal); + expect(options?.signal?.aborted).toBe(false); + + execController.abort(new Error('tool timeout')); + expect(options?.signal?.aborted).toBe(true); + + // Also verify aborting the wrapper signal propagates on a fresh call + const recorded2: RecordedCall[] = []; + const wrapperController2 = new AbortController(); + const execController2 = new AbortController(); + const t2 = wrapMcpTool(DEF, { + client: fakeClient(recorded2), + emitProgress: false, + signal: wrapperController2.signal, + }); + + await asExecute(t2)( + {}, + { + signal: execController2.signal, + }, + ); + + const options2 = recorded2[0]?.args[1] as + | { + signal?: AbortSignal; + } + | undefined; + expect(options2?.signal?.aborted).toBe(false); + wrapperController2.abort(new Error('wrapper closed')); + expect(options2?.signal?.aborted).toBe(true); + }); + + it('composes wrapper options.signal and per-execution ctx.signal for generator tools', async () => { + const recorded: RecordedCall[] = []; + const wrapperController = new AbortController(); + const execController = new AbortController(); + const t = wrapMcpTool(DEF, { + client: fakeClient(recorded), + emitProgress: true, + signal: wrapperController.signal, + }); + + const gen = asExecute(t)( + {}, + { + signal: execController.signal, + }, + ) as AsyncGenerator; + while (!(await gen.next()).done) { + // discard progress events + } + + const options = recorded[0]?.args[1] as + | { + signal?: AbortSignal; + } + | undefined; + expect(options?.signal).toBeInstanceOf(AbortSignal); + expect(options?.signal?.aborted).toBe(false); + + execController.abort(new Error('tool timeout')); + expect(options?.signal?.aborted).toBe(true); + }); }); diff --git a/packages/agent/tests/unit/tool-cancellation.test.ts b/packages/agent/tests/unit/tool-cancellation.test.ts index 1394b7c6..726e524c 100644 --- a/packages/agent/tests/unit/tool-cancellation.test.ts +++ b/packages/agent/tests/unit/tool-cancellation.test.ts @@ -1,9 +1,12 @@ +import type { Client } from '@modelcontextprotocol/client'; import type { OpenRouterCore } from '@openrouter/sdk/core'; import type * as models from '@openrouter/sdk/models'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod/v4'; import { callModel } from '../../src/inner-loop/call-model.js'; +import type { ConversationState, StateAccessor } from '../../src/lib/conversation-state.js'; import { tool } from '../../src/lib/tool.js'; +import { wrapMcpTool } from '../../src/mcp/tool-wrapper.js'; const mockBetaResponsesSend = vi.hoisted(() => vi.fn()); @@ -593,4 +596,315 @@ describe('tool concurrency controls', () => { expect(secondRan).toBe(true); }); + + it('enforces per-tool timeoutMs and aborts ctx.signal when resuming an approved tool', async () => { + let savedState: ConversationState | null = null; + const state: StateAccessor = { + load: async () => savedState, + save: async (next) => { + savedState = next; + }, + }; + + let seenSignal: AbortSignal | undefined; + const slowApproved = tool({ + name: 'slow_approved', + inputSchema: z.object({}), + requireApproval: true, + timeoutMs: 30, + execute: async (_params, ctx) => { + seenSignal = ctx?.signal; + return new Promise<{ + ok: boolean; + }>((_resolve, reject) => { + ctx?.signal?.addEventListener( + 'abort', + () => reject(ctx.signal.reason ?? new Error('aborted')), + { + once: true, + }, + ); + }); + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_appr_1', 'slow_approved', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'timed out on resume'), + ]), + }); + + // Turn 1: pauses for approval + const first = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + slowApproved, + ] as const, + state, + }); + const pending = await first.getPendingToolCalls(); + expect(pending.map((p) => p.id)).toEqual([ + 'call_appr_1', + ]); + + // Turn 2: approve and resume — per-tool timeoutMs must fire and abort ctx.signal + const resumed = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + slowApproved, + ] as const, + state, + approveToolCalls: [ + 'call_appr_1', + ], + }); + const text = await resumed.getText(); + expect(text).toBe('timed out on resume'); + expect(seenSignal).toBeInstanceOf(AbortSignal); + expect(seenSignal?.aborted).toBe(true); + + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const outputItem = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_appr_1', + ); + expect(outputItem?.output).toContain('timed out after 30ms'); + }); + + it('enforces run-level toolTimeoutMs when resuming an approved tool without per-tool timeoutMs', async () => { + let savedState: ConversationState | null = null; + const state: StateAccessor = { + load: async () => savedState, + save: async (next) => { + savedState = next; + }, + }; + + let seenSignal: AbortSignal | undefined; + const hangingApproved = tool({ + name: 'hanging_approved', + inputSchema: z.object({}), + requireApproval: true, + execute: async (_params, ctx) => { + seenSignal = ctx?.signal; + return new Promise<{ + ok: boolean; + }>(() => { + // Ignores ctx.signal and never settles + }); + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_appr_2', 'hanging_approved', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'run timeout fired'), + ]), + }); + + const first = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + hangingApproved, + ] as const, + state, + toolTimeoutMs: 30, + }); + expect((await first.getPendingToolCalls()).map((p) => p.id)).toEqual([ + 'call_appr_2', + ]); + + const resumed = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + hangingApproved, + ] as const, + state, + toolTimeoutMs: 30, + approveToolCalls: [ + 'call_appr_2', + ], + }); + const text = await resumed.getText(); + expect(text).toBe('run timeout fired'); + expect(seenSignal).toBeInstanceOf(AbortSignal); + expect(seenSignal?.aborted).toBe(true); + + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const outputItem = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_appr_2', + ); + expect(outputItem?.output).toContain('timed out after 30ms'); + }); + + it('enforces per-tool timeoutMs when resuming an approved background tool', async () => { + let savedState: ConversationState | null = null; + const state: StateAccessor = { + load: async () => savedState, + save: async (next) => { + savedState = next; + }, + }; + + let seenSignal: AbortSignal | undefined; + const bgApproved = tool({ + name: 'bg_approved', + lifecycle: 'background', + inputSchema: z.object({}), + outputSchema: z.object({ + ok: z.boolean(), + }), + requireApproval: true, + timeoutMs: 30, + run: async (_params, ctx) => { + seenSignal = ctx.signal; + return new Promise<{ + ok: boolean; + }>(() => { + // Never settles + }); + }, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_appr_bg', 'bg_approved', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'bg approved timed out'), + ]), + }); + + const first = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + bgApproved, + ] as const, + state, + }); + expect((await first.getPendingToolCalls()).map((p) => p.id)).toEqual([ + 'call_appr_bg', + ]); + + const resumed = callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + bgApproved, + ] as const, + state, + approveToolCalls: [ + 'call_appr_bg', + ], + }); + const text = await resumed.getText(); + expect(text).toBe('bg approved timed out'); + expect(seenSignal).toBeInstanceOf(AbortSignal); + expect(seenSignal?.aborted).toBe(true); + + const secondInput = mockBetaResponsesSend.mock.calls[1]?.[1]?.responsesRequest?.input as Array<{ + type?: string; + callId?: string; + output?: string; + }>; + const outputItem = secondInput.find( + (item) => item.type === 'function_call_output' && item.callId === 'call_appr_bg', + ); + expect(outputItem?.output).toContain('timed out after 30ms'); + }); + + it('aborts the signal passed to MCP client.callTool when toolTimeoutMs fires', async () => { + let callToolSignal: AbortSignal | undefined; + const fakeMcpClient = { + callTool: ( + _params: unknown, + opts?: { + signal?: AbortSignal; + }, + ) => { + callToolSignal = opts?.signal; + return new Promise((_resolve, reject) => { + opts?.signal?.addEventListener( + 'abort', + () => reject(opts.signal?.reason ?? new Error('aborted')), + { + once: true, + }, + ); + }); + }, + } as unknown as Client; + + const wrapped = wrapMcpTool( + { + name: 'slow_mcp', + inputSchema: { + type: 'object', + properties: {}, + }, + }, + { + client: fakeMcpClient, + }, + ); + + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_1', [ + functionCallItem('call_mcp_1', 'slow_mcp', '{}'), + ]), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_2', [ + messageItem('msg_1', 'mcp timed out'), + ]), + }); + + const text = await callModel(client, { + model: 'test-model', + input: 'go', + tools: [ + wrapped, + ] as const, + toolTimeoutMs: 30, + }).getText(); + + expect(text).toBe('mcp timed out'); + expect(callToolSignal).toBeInstanceOf(AbortSignal); + expect(callToolSignal?.aborted).toBe(true); + }); }); From 1808a34549f18ce01a60e0d677cbca40214f4008 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:28:05 +0000 Subject: [PATCH 2/2] refactor(agent): extract grace-window and unsent-tool deadline helpers --- packages/agent/src/lib/model-result.ts | 446 +++++++++++-------------- 1 file changed, 196 insertions(+), 250 deletions(-) diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index c424cd5a..1fc0f51a 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -3074,6 +3074,90 @@ export class ModelResult< ); } + /** + * Execute a single tool call with its per-call abort signal and deadline, + * returning an `UnsentToolResult` (or `null` when a HITL tool pauses). + * Shared by the auto-approve and approval-resume paths. + */ + private async executeToolForUnsentResult( + tool: Tool, + toolCall: ParsedToolCall, + turnContext: TurnContext, + runPreToolUse: boolean, + ): Promise | null> { + const callId = toolCall.id; + const toolName = String(toolCall.name); + const { controller, signal, timeoutMs } = this.composeToolSignal(toolName, callId); + const runBinding = this.createRunBinding(callId); + try { + const executionPromise = this.runToolWithHooks( + tool, + toolCall as ParsedToolCall, + turnContext, + undefined, + { + signal, + callId, + ...(this.currentState?.id !== undefined && { + conversationId: this.currentState.id, + }), + client: this.options.client, + runExtras: buildRunExtras(tool, runBinding), + }, + runPreToolUse, + ); + + const hookOutcome = await this.raceToolDeadline( + executionPromise, + toolName, + timeoutMs, + controller, + ); + + if (hookOutcome === 'timeout') { + const message = `Tool "${toolCall.name}" timed out after ${timeoutMs}ms`; + this.broadcastToolResult(callId, toolName, isMcpTool(tool) ? 'mcp' : 'client', { + error: message, + } as InferToolOutputsUnion); + return createRejectedResult(callId, toolName, message); + } + + if (hookOutcome.type === 'parse_error') { + this.broadcastToolResult(callId, toolName, isMcpTool(tool) ? 'mcp' : 'client', { + error: hookOutcome.errorMessage, + } as InferToolOutputsUnion); + return createRejectedResult(callId, toolName, hookOutcome.errorMessage); + } + + if (hookOutcome.type === 'hook_blocked') { + return createRejectedResult(callId, toolName, hookOutcome.reason); + } + + const result = hookOutcome.result; + if (result === null) { + return null; + } + + if (isAsyncToolInvocation(result)) { + return await this.settleAsyncInvocationAsUnsent(toolCall, result, { + timeoutMs, + controller, + }); + } + + if (result.error) { + return createRejectedResult(callId, toolName, result.error.message); + } + return createUnsentResult( + callId, + toolName, + await this.unsentModelOutput(toolCall as ParsedToolCall, result.result), + ); + } finally { + this.inflightToolControllers.delete(callId); + } + } + /** * Execute tools that can auto-execute (don't require approval) in parallel. * @@ -3090,80 +3174,10 @@ export class ModelResult< if (!tool || !isAutoResolvableTool(tool)) { return null; } - // Route through runToolWithHooks so PreToolUse/PostToolUse fire even on // the auto-approve path. `runToolWithHooks` also fails closed on raw // JSON-parse failures so hooks never see a malformed payload. - const { controller, signal, timeoutMs } = this.composeToolSignal(String(tc.name), tc.id); - const runBinding = this.createRunBinding(tc.id); - try { - const executionPromise = this.runToolWithHooks( - tool, - tc as ParsedToolCall, - turnContext, - undefined, - { - signal, - callId: tc.id, - ...(this.currentState?.id !== undefined && { - conversationId: this.currentState.id, - }), - client: this.options.client, - runExtras: buildRunExtras(tool, runBinding), - }, - ); - - const hookOutcome = await this.raceToolDeadline( - executionPromise, - String(tc.name), - timeoutMs, - controller, - ); - - if (hookOutcome === 'timeout') { - const message = `Tool "${tc.name}" timed out after ${timeoutMs}ms`; - this.broadcastToolResult(tc.id, String(tc.name), isMcpTool(tool) ? 'mcp' : 'client', { - error: message, - } as InferToolOutputsUnion); - return createRejectedResult(tc.id, String(tc.name), message); - } - - if (hookOutcome.type === 'parse_error') { - this.broadcastToolResult(tc.id, String(tc.name), isMcpTool(tool) ? 'mcp' : 'client', { - error: hookOutcome.errorMessage, - } as InferToolOutputsUnion); - return createRejectedResult(tc.id, String(tc.name), hookOutcome.errorMessage); - } - - if (hookOutcome.type === 'hook_blocked') { - return createRejectedResult(tc.id, String(tc.name), hookOutcome.reason); - } - - const result = hookOutcome.result; - - if (result === null) { - // HITL tool paused — no unsent result for this call in this round - return null; - } - - if (isAsyncToolInvocation(result)) { - return await this.settleAsyncInvocationAsUnsent(tc, result, { - timeoutMs, - controller, - }); - } - - if (result.error) { - return createRejectedResult(tc.id, String(tc.name), result.error.message); - } - return createUnsentResult( - tc.id, - String(tc.name), - await this.unsentModelOutput(tc as ParsedToolCall, result.result), - ); - } finally { - this.inflightToolControllers.delete(tc.id); - } + return this.executeToolForUnsentResult(tool, tc, turnContext, true); }); const settledResults = await Promise.allSettled(toolCallPromises); @@ -4328,83 +4342,14 @@ export class ModelResult< // starts — independent of graceMs — so timeoutMs < graceMs (including the // default 250ms graceMs) still aborts ctx.signal and settles on time. const graceMs = invocation.graceMs; - const timeoutMs = value.timeoutMs; if (graceMs > 0) { - // Both timers are cleared as soon as the race settles (same discipline - // as raceToolDeadline) — they are unref'd, but leaked timers are still - // leaked timers. - let graceTimer: ReturnType | undefined; - let timeoutTimer: ReturnType | undefined; - const raceParticipants: Array< - Promise< - | { - outcome: 'ok'; - result: unknown; - } - | { - outcome: 'error'; - error: unknown; - } - | 'pending' - > - > = [ - work.then( - (result) => ({ - outcome: 'ok' as const, - result, - }), - (error: unknown) => ({ - outcome: 'error' as const, - error, - }), - ), - new Promise<'pending'>((resolve) => { - graceTimer = setTimeout(() => resolve('pending'), graceMs); - if ( - typeof graceTimer === 'object' && - 'unref' in graceTimer && - typeof graceTimer.unref === 'function' - ) { - graceTimer.unref(); - } - }), - ]; - if (timeoutMs !== undefined && timeoutMs > 0) { - raceParticipants.push( - new Promise<{ - outcome: 'error'; - error: Error; - }>((resolve) => { - timeoutTimer = setTimeout(() => { - const timeoutError = Object.assign( - new Error(`Tool "${toolCall.name}" timed out after ${timeoutMs}ms`), - { - code: 'tool_timeout', - }, - ); - controller.abort(timeoutError); - resolve({ - outcome: 'error' as const, - error: timeoutError, - }); - }, timeoutMs); - if ( - typeof timeoutTimer === 'object' && - 'unref' in timeoutTimer && - typeof timeoutTimer.unref === 'function' - ) { - timeoutTimer.unref(); - } - }), - ); - } - const settled = await Promise.race(raceParticipants); - if (graceTimer !== undefined) { - clearTimeout(graceTimer); - } - if (timeoutTimer !== undefined) { - clearTimeout(timeoutTimer); - } + const settled = await this.raceBackgroundGraceWindow( + work, + String(toolCall.name), + graceMs, + value.timeoutMs, + controller, + ); if (settled !== 'pending') { // Settled in-window: behave exactly like a regular tool. The call @@ -4562,6 +4507,99 @@ export class ModelResult< }; } + /** + * Race background work against both the grace window and (when configured) + * the per-tool timeout deadline. Clears both timers as soon as any branch + * settles so handoff to `AsyncToolRegistry.trackBackground` leaves no + * duplicate or leaked timer. + */ + private async raceBackgroundGraceWindow( + work: Promise, + toolName: string, + graceMs: number, + timeoutMs: number | undefined, + controller: AbortController, + ): Promise< + | { + outcome: 'ok'; + result: unknown; + } + | { + outcome: 'error'; + error: unknown; + } + | 'pending' + > { + let graceTimer: ReturnType | undefined; + let timeoutTimer: ReturnType | undefined; + const unrefTimer = (timer: ReturnType): void => { + if (typeof timer === 'object' && 'unref' in timer && typeof timer.unref === 'function') { + timer.unref(); + } + }; + const participants: Array< + Promise< + | { + outcome: 'ok'; + result: unknown; + } + | { + outcome: 'error'; + error: unknown; + } + | 'pending' + > + > = [ + work.then( + (result) => ({ + outcome: 'ok' as const, + result, + }), + (error: unknown) => ({ + outcome: 'error' as const, + error, + }), + ), + new Promise<'pending'>((resolve) => { + graceTimer = setTimeout(() => resolve('pending'), graceMs); + unrefTimer(graceTimer); + }), + ]; + if (timeoutMs !== undefined && timeoutMs > 0) { + participants.push( + new Promise<{ + outcome: 'error'; + error: Error; + }>((resolve) => { + timeoutTimer = setTimeout(() => { + const timeoutError = Object.assign( + new Error(`Tool "${toolName}" timed out after ${timeoutMs}ms`), + { + code: 'tool_timeout', + }, + ); + controller.abort(timeoutError); + resolve({ + outcome: 'error' as const, + error: timeoutError, + }); + }, timeoutMs); + unrefTimer(timeoutTimer); + }), + ); + } + try { + return await Promise.race(participants); + } finally { + if (graceTimer !== undefined) { + clearTimeout(graceTimer); + } + if (timeoutTimer !== undefined) { + clearTimeout(timeoutTimer); + } + } + } + /** * Run a background tool's work under the tool's own concurrency gate AND * the background pool. The round path does not touch the per-tool gate @@ -6259,111 +6297,19 @@ export class ModelResult< } } - const { controller, signal, timeoutMs } = this.composeToolSignal( - String(toolCall.name), - callId, + const unsent = await this.executeToolForUnsentResult( + tool, + toolCall as ParsedToolCall, + turnContext, + false, ); - const runBinding = this.createRunBinding(callId); - try { - const executionPromise = this.runToolWithHooks( - tool, - toolCall as ParsedToolCall, - turnContext, - undefined, - { - signal, - callId, - ...(this.currentState?.id !== undefined && { - conversationId: this.currentState.id, - }), - client: this.options.client, - runExtras: buildRunExtras(tool, runBinding), - }, - false, - ); - - const hookOutcome = await this.raceToolDeadline( - executionPromise, - String(toolCall.name), - timeoutMs, - controller, - ); - - if (hookOutcome === 'timeout') { - const message = `Tool "${toolCall.name}" timed out after ${timeoutMs}ms`; - this.broadcastToolResult( - callId, - String(toolCall.name), - this.toolSourceByName(String(toolCall.name)), - { - error: message, - } as InferToolOutputsUnion, - ); - unsentResults.push(createRejectedResult(callId, String(toolCall.name), message)); - continue; - } - - if (hookOutcome.type === 'parse_error') { - this.broadcastToolResult( - callId, - String(toolCall.name), - this.toolSourceByName(String(toolCall.name)), - { - error: hookOutcome.errorMessage, - } as InferToolOutputsUnion, - ); - unsentResults.push( - createRejectedResult(callId, String(toolCall.name), hookOutcome.errorMessage), - ); - continue; - } - - if (hookOutcome.type === 'hook_blocked') { - unsentResults.push( - createRejectedResult(callId, String(toolCall.name), hookOutcome.reason), - ); - continue; - } - - const result = hookOutcome.result; - - if (result === null) { - // HITL tool paused on approval — keep the call visible to the caller - // via pendingToolCalls (status becomes 'awaiting_hitl' below). - hitlPausedIds.add(callId); - continue; - } - - if (isAsyncToolInvocation(result)) { - unsentResults.push( - await this.settleAsyncInvocationAsUnsent( - toolCall as ParsedToolCall, - result, - { - timeoutMs, - controller, - }, - ), - ); - continue; - } - - if (result.error) { - unsentResults.push( - createRejectedResult(callId, String(toolCall.name), result.error.message), - ); - } else { - unsentResults.push( - createUnsentResult( - callId, - String(toolCall.name), - await this.unsentModelOutput(toolCall as ParsedToolCall, result.result), - ), - ); - } - } finally { - this.inflightToolControllers.delete(callId); + if (unsent === null) { + // HITL tool paused on approval — keep the call visible to the caller + // via pendingToolCalls (status becomes 'awaiting_hitl' below). + hitlPausedIds.add(callId); + continue; } + unsentResults.push(unsent); } // Process rejections