diff --git a/packages/agent/src/lib/conversation-state.ts b/packages/agent/src/lib/conversation-state.ts index d7e1be6c..30043e99 100644 --- a/packages/agent/src/lib/conversation-state.ts +++ b/packages/agent/src/lib/conversation-state.ts @@ -516,12 +516,13 @@ export function extractTextFromResponse(response: models.OpenResponsesResult): s } /** - * Extract tool calls from a response + * Extract tool calls from a completed response. + * Non-completed responses yield no tool calls. */ export function extractToolCallsFromResponse( response: models.OpenResponsesResult, ): ParsedToolCall[] { - if (!response.output) { + if (response.status !== 'completed' || !response.output) { return []; } diff --git a/packages/agent/src/lib/stream-transformers.ts b/packages/agent/src/lib/stream-transformers.ts index 66dac32c..942b9809 100644 --- a/packages/agent/src/lib/stream-transformers.ts +++ b/packages/agent/src/lib/stream-transformers.ts @@ -806,34 +806,33 @@ export function extractTextFromResponse(response: models.OpenResponsesResult): s } /** - * Whether the provider stopped this response at `max_output_tokens`. The - * `function_call` items on such a response are an unfinished batch: the model - * asked for the set together, and the last one carries whatever argument - * prefix fit in the budget. Executing the complete ones would hand the model a - * result set with a silent hole, and spend side effects on a turn that - * truncates the same way on the same budget, so none of them run. The caller - * sees every item and `incomplete_details`, and resumes once the budget is - * raised. + * Whether this response reached the `'completed'` terminal status and its + * `function_call` items are eligible for local tool execution. + * + * Non-completed responses (`incomplete` for `max_output_tokens`, + * `content_filter`, or any other reason; `failed`; `cancelled`; `in_progress`; + * `queued`; or any unknown status) must not trigger local tool execution: + * their output may be truncated, halted by a safety filter, errored, + * cancelled, or still in flight. The caller still receives the response with + * its output items, status, error, and `incompleteDetails` intact. */ -function isTruncatedAtMaxOutputTokens(response: models.OpenResponsesResult): boolean { - return ( - response.status === 'incomplete' && response.incompleteDetails?.reason === 'max_output_tokens' - ); +function isResponseCompleted(response: models.OpenResponsesResult): boolean { + return response.status === 'completed'; } /** * Extract all tool calls from a completed response * Returns parsed tool calls with arguments as objects (not JSON strings) * - * A response truncated at `max_output_tokens` yields no tool calls: see - * `isTruncatedAtMaxOutputTokens`. + * Any response whose status is not `'completed'` yields no tool calls: see + * `isResponseCompleted`. */ export function extractToolCallsFromResponse( response: models.OpenResponsesResult, ): ParsedToolCall[] { const toolCalls: ParsedToolCall[] = []; - if (isTruncatedAtMaxOutputTokens(response)) { + if (!isResponseCompleted(response)) { return toolCalls; } @@ -982,18 +981,19 @@ export async function* buildToolCallStream( } /** - * Check if a response contains any tool calls the loop should execute. A - * response truncated at `max_output_tokens` has none, even when its output - * carries a cut-off `function_call` item. + * Check if a response contains any tool calls the loop should execute. Only a + * response with `status === 'completed'` is eligible; any non-completed + * response (`incomplete`, `failed`, `cancelled`, `in_progress`, `queued`, etc.) + * returns `false`, even when its output carries `function_call` items. * * Scope: this and `extractToolCallsFromResponse` decide execution on the - * completed response. `buildToolCallStream` (`getToolCallsStream()`) is a + * materialized response. `buildToolCallStream` (`getToolCallsStream()`) is a * consumer view that yields each call as its `output_item.done` arrives, - * before the terminal event says whether the turn was cut off, so it still - * reports the model's emitted calls, truncated one included. + * before the terminal event reports the final response status, so it still + * reports the model's emitted calls. */ export function responseHasToolCalls(response: models.OpenResponsesResult): boolean { - if (isTruncatedAtMaxOutputTokens(response)) { + if (!isResponseCompleted(response)) { return false; } return response.output.some((item) => 'type' in item && item.type === 'function_call'); diff --git a/packages/agent/tests/unit/get-usage.test.ts b/packages/agent/tests/unit/get-usage.test.ts index c64be793..fc99dd67 100644 --- a/packages/agent/tests/unit/get-usage.test.ts +++ b/packages/agent/tests/unit/get-usage.test.ts @@ -60,6 +60,7 @@ function textResponse(id = 'resp_text', usage?: models.Usage | null): models.Ope return { id, model: 'test-model-v1', + status: 'completed', output: [ { type: 'message', @@ -94,6 +95,7 @@ function toolCallResponse( return { id, model: 'test-model-v1', + status: 'completed', output: [ { type: 'function_call', diff --git a/packages/agent/tests/unit/hooks-post-model-call.test.ts b/packages/agent/tests/unit/hooks-post-model-call.test.ts index 8f98d80f..1e041271 100644 --- a/packages/agent/tests/unit/hooks-post-model-call.test.ts +++ b/packages/agent/tests/unit/hooks-post-model-call.test.ts @@ -52,6 +52,7 @@ function textResponse(id = 'resp_text', usage?: models.Usage | null): models.Ope return { id, model: 'test-model-v1', + status: 'completed', output: [ { type: 'message', @@ -76,6 +77,7 @@ function toolCallResponse(id = 'resp_tool'): models.OpenResponsesResult { return { id, model: 'test-model-v1', + status: 'completed', output: [ { type: 'function_call', diff --git a/packages/agent/tests/unit/hooks-session-lifecycle.test.ts b/packages/agent/tests/unit/hooks-session-lifecycle.test.ts index 333aa528..6d7e9b3b 100644 --- a/packages/agent/tests/unit/hooks-session-lifecycle.test.ts +++ b/packages/agent/tests/unit/hooks-session-lifecycle.test.ts @@ -35,6 +35,7 @@ afterEach(() => { function textResponse(id = 'resp_text'): models.OpenResponsesResult { return { id, + status: 'completed', output: [ { type: 'message', @@ -55,6 +56,7 @@ function textResponse(id = 'resp_text'): models.OpenResponsesResult { function toolCallResponse(id = 'resp_tool'): models.OpenResponsesResult { return { id, + status: 'completed', output: [ { type: 'function_call', diff --git a/packages/agent/tests/unit/next-turn-tool-choice-loop.test.ts b/packages/agent/tests/unit/next-turn-tool-choice-loop.test.ts index f81b6db4..ca9084ef 100644 --- a/packages/agent/tests/unit/next-turn-tool-choice-loop.test.ts +++ b/packages/agent/tests/unit/next-turn-tool-choice-loop.test.ts @@ -43,6 +43,7 @@ function allowed(names: string[]): models.ResponsesRequest['toolChoice'] { function toolCallResponse(): models.OpenResponsesResult { return { id: 'resp_tool', + status: 'completed', output: [ { type: 'function_call', @@ -59,6 +60,7 @@ function toolCallResponse(): models.OpenResponsesResult { function textResponse(): models.OpenResponsesResult { return { id: 'resp_text', + status: 'completed', output: [ { type: 'message', diff --git a/packages/agent/tests/unit/non-completed-response-tool-calls.test.ts b/packages/agent/tests/unit/non-completed-response-tool-calls.test.ts new file mode 100644 index 00000000..377233c7 --- /dev/null +++ b/packages/agent/tests/unit/non-completed-response-tool-calls.test.ts @@ -0,0 +1,481 @@ +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'; + +const mockBetaResponsesSend = vi.hoisted(() => vi.fn()); + +vi.mock('@openrouter/sdk/funcs/betaResponsesSend', () => ({ + betaResponsesSend: mockBetaResponsesSend, +})); + +import { callModel } from '../../src/inner-loop/call-model.js'; +import { extractToolCallsFromResponse as extractStateToolCalls } from '../../src/lib/conversation-state.js'; +import { stepCountIs } from '../../src/lib/stop-conditions.js'; +import { + extractToolCallsFromResponse, + responseHasToolCalls, +} from '../../src/lib/stream-transformers.js'; +import { executeToolLoop } from '../../src/lib/tool-orchestrator.js'; +import { ToolType } from '../../src/lib/tool-types.js'; + +function makeToolCallResponse(overrides: { + id?: string; + status: models.OpenAIResponsesResponseStatus; + incompleteDetails?: models.IncompleteDetails | null; + error?: models.OpenResponsesErrorField | null; + toolName?: string; + callId?: string; + args?: string; +}): models.OpenResponsesResult { + const toolName = overrides.toolName ?? 'run_shell'; + const callId = overrides.callId ?? 'call_1'; + return { + id: overrides.id ?? `resp_${overrides.status}`, + object: 'response', + createdAt: 1_783_462_506, + completedAt: overrides.status === 'completed' ? 1_783_462_520 : null, + model: 'test-model', + status: overrides.status, + incompleteDetails: overrides.incompleteDetails ?? null, + error: overrides.error ?? null, + output: [ + { + type: 'function_call', + id: `fc_${callId}`, + callId, + name: toolName, + arguments: + overrides.args ?? + JSON.stringify({ + command: 'echo hi', + }), + status: 'completed', + }, + ], + usage: { + inputTokens: 100, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokens: 20, + totalTokens: 120, + outputTokensDetails: { + reasoningTokens: 0, + }, + }, + temperature: null, + topP: null, + presencePenalty: null, + frequencyPenalty: null, + metadata: null, + instructions: null, + tools: [], + toolChoice: 'auto', + parallelToolCalls: false, + } as models.OpenResponsesResult; +} + +function makeTextResponse(id = 'resp_done'): models.OpenResponsesResult { + return { + id, + object: 'response', + createdAt: 1_783_462_506, + completedAt: 1_783_462_520, + model: 'test-model', + status: 'completed', + incompleteDetails: null, + error: null, + output: [ + { + type: 'message', + id: `msg_${id}`, + role: 'assistant', + status: 'completed', + content: [ + { + type: 'output_text', + text: 'done', + annotations: [], + }, + ], + }, + ], + usage: { + inputTokens: 100, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokens: 10, + totalTokens: 110, + outputTokensDetails: { + reasoningTokens: 0, + }, + }, + temperature: null, + topP: null, + presencePenalty: null, + frequencyPenalty: null, + metadata: null, + instructions: null, + tools: [], + toolChoice: 'auto', + parallelToolCalls: false, + } as models.OpenResponsesResult; +} + +function makeEventStream(events: models.StreamEvents[]): ReadableStream { + return new ReadableStream({ + start(controller) { + for (const event of events) { + controller.enqueue(event); + } + controller.close(); + }, + }); +} + +const NON_COMPLETED_CASES: ReadonlyArray<{ + label: string; + status: models.OpenAIResponsesResponseStatus; + incompleteDetails?: models.IncompleteDetails | null; + error?: models.OpenResponsesErrorField | null; +}> = [ + { + label: 'failed', + status: 'failed', + error: { + code: 'server_error', + message: 'upstream failed', + }, + }, + { + label: 'cancelled', + status: 'cancelled', + }, + { + label: 'incomplete (content_filter)', + status: 'incomplete', + incompleteDetails: { + reason: 'content_filter', + }, + }, + { + label: 'incomplete (max_output_tokens)', + status: 'incomplete', + incompleteDetails: { + reason: 'max_output_tokens', + }, + }, + { + label: 'incomplete (no details)', + status: 'incomplete', + incompleteDetails: null, + }, + { + label: 'in_progress', + status: 'in_progress', + }, + { + label: 'queued', + status: 'queued', + }, +]; + +const client = {} as OpenRouterCore; + +function makeShellTool(executed: unknown[]) { + return { + type: ToolType.Function, + function: { + name: 'run_shell', + description: 'Run a shell command.', + inputSchema: z.object({ + command: z.string(), + }), + execute: async (params: { command: string }) => { + executed.push(params); + return { + ok: true, + }; + }, + }, + } as const; +} + +describe('non-completed response tool execution guard', () => { + beforeEach(() => { + mockBetaResponsesSend.mockReset(); + }); + + it.each(NON_COMPLETED_CASES)('extractors return no tool calls for $label response', ({ + status, + incompleteDetails, + error, + }) => { + const response = makeToolCallResponse({ + status, + incompleteDetails, + error, + }); + + expect(responseHasToolCalls(response)).toBe(false); + expect(extractToolCallsFromResponse(response)).toEqual([]); + expect(extractStateToolCalls(response)).toEqual([]); + }); + + it('extractors return tool calls for a completed response', () => { + const response = makeToolCallResponse({ + status: 'completed', + }); + + expect(responseHasToolCalls(response)).toBe(true); + expect(extractToolCallsFromResponse(response)).toEqual([ + { + id: 'call_1', + name: 'run_shell', + arguments: { + command: 'echo hi', + }, + }, + ]); + expect(extractStateToolCalls(response)).toEqual([ + { + id: 'call_1', + name: 'run_shell', + arguments: { + command: 'echo hi', + }, + }, + ]); + }); + + it.each( + NON_COMPLETED_CASES, + )('callModel refuses to execute tools on initial $label response', async ({ + status, + incompleteDetails, + error, + }) => { + const executed: unknown[] = []; + const nonCompleted = makeToolCallResponse({ + status, + incompleteDetails, + error, + }); + mockBetaResponsesSend.mockResolvedValue({ + ok: true, + value: nonCompleted, + }); + + const result = callModel(client, { + model: 'test-model', + input: 'Run echo hi.', + stopWhen: stepCountIs(3), + tools: [ + makeShellTool(executed), + ] as const, + }); + + const response = await result.getResponse(); + + expect(executed).toEqual([]); + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(1); + expect(response.status).toBe(status); + expect(await result.getToolCalls()).toEqual([]); + }); + + it('callModel refuses to execute tools from a streaming response.incomplete (content_filter) event', async () => { + const executed: unknown[] = []; + const incompleteResponse = makeToolCallResponse({ + status: 'incomplete', + incompleteDetails: { + reason: 'content_filter', + }, + }); + mockBetaResponsesSend.mockResolvedValue({ + ok: true, + value: makeEventStream([ + { + type: 'response.incomplete', + sequenceNumber: 1, + response: incompleteResponse, + } as unknown as models.StreamEvents, + ]), + }); + + const result = callModel(client, { + model: 'test-model', + input: 'Run echo hi.', + stopWhen: stepCountIs(3), + tools: [ + makeShellTool(executed), + ] as const, + }); + + const response = await result.getResponse(); + + expect(executed).toEqual([]); + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(1); + expect(response.status).toBe('incomplete'); + expect(response.incompleteDetails).toEqual({ + reason: 'content_filter', + }); + }); + + it('callModel refuses to execute tools when a streaming response.completed event carries a non-completed status', async () => { + const executed: unknown[] = []; + const cancelledResponse = makeToolCallResponse({ + status: 'cancelled', + }); + mockBetaResponsesSend.mockResolvedValue({ + ok: true, + value: makeEventStream([ + { + type: 'response.completed', + sequenceNumber: 1, + response: cancelledResponse, + } as unknown as models.StreamEvents, + ]), + }); + + const result = callModel(client, { + model: 'test-model', + input: 'Run echo hi.', + stopWhen: stepCountIs(3), + tools: [ + makeShellTool(executed), + ] as const, + }); + + const response = await result.getResponse(); + + expect(executed).toEqual([]); + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(1); + expect(response.status).toBe('cancelled'); + }); + + it('callModel refuses to execute tools on a follow-up turn with non-completed status (including when stopWhen fires)', async () => { + const executed: unknown[] = []; + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeToolCallResponse({ + id: 'resp_turn_0', + status: 'completed', + callId: 'call_turn_0', + args: JSON.stringify({ + command: 'first', + }), + }), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeToolCallResponse({ + id: 'resp_turn_1', + status: 'incomplete', + incompleteDetails: { + reason: 'content_filter', + }, + callId: 'call_turn_1', + args: JSON.stringify({ + command: 'second', + }), + }), + }); + + const result = callModel(client, { + model: 'test-model', + input: 'Run two commands.', + stopWhen: stepCountIs(1), + allowFinalResponse: true, + tools: [ + makeShellTool(executed), + ] as const, + }); + + const response = await result.getResponse(); + + expect(executed).toEqual([ + { + command: 'first', + }, + ]); + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(2); + expect(response.id).toBe('resp_turn_1'); + expect(response.status).toBe('incomplete'); + }); + + it('callModel still executes tools normally when response status is completed', async () => { + const executed: unknown[] = []; + mockBetaResponsesSend + .mockResolvedValueOnce({ + ok: true, + value: makeToolCallResponse({ + status: 'completed', + }), + }) + .mockResolvedValueOnce({ + ok: true, + value: makeTextResponse(), + }); + + const result = callModel(client, { + model: 'test-model', + input: 'Run echo hi.', + stopWhen: stepCountIs(3), + tools: [ + makeShellTool(executed), + ] as const, + }); + + const response = await result.getResponse(); + + expect(executed).toEqual([ + { + command: 'echo hi', + }, + ]); + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(2); + expect(response.status).toBe('completed'); + }); + + it.each( + NON_COMPLETED_CASES, + )('executeToolLoop refuses to execute tools on $label response', async ({ + status, + incompleteDetails, + error, + }) => { + const executed: unknown[] = []; + const nonCompleted = makeToolCallResponse({ + status, + incompleteDetails, + error, + }); + const sendRequest = vi.fn(async () => nonCompleted); + + const loopResult = await executeToolLoop( + sendRequest, + [ + { + role: 'user', + content: 'Run echo hi.', + }, + ], + { + model: 'test-model', + input: [], + } as unknown as models.ResponsesRequest, + [ + makeShellTool(executed), + ], + [], + ); + + expect(executed).toEqual([]); + expect(sendRequest).toHaveBeenCalledTimes(1); + expect(loopResult.toolExecutionResults).toEqual([]); + expect(loopResult.finalResponse.status).toBe(status); + }); +}); diff --git a/packages/agent/tests/unit/tool-orchestrator.test.ts b/packages/agent/tests/unit/tool-orchestrator.test.ts index bbaba413..3edd8982 100644 --- a/packages/agent/tests/unit/tool-orchestrator.test.ts +++ b/packages/agent/tests/unit/tool-orchestrator.test.ts @@ -32,6 +32,7 @@ function functionCallItem( function responseWith(...items: unknown[]): models.OpenResponsesResult { return { + status: 'completed', output: items, } as unknown as models.OpenResponsesResult; }