From 5b42957e77180e8597e40d1ea674fe2438fbe373 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:57:14 +0000 Subject: [PATCH] fix(agent): send the json value returned by toModelOutput instead of the raw tool result --- .changeset/to-model-output-json.md | 5 + packages/agent/src/lib/model-result.ts | 11 +- packages/agent/src/lib/tool-types.ts | 14 +- .../tests/unit/to-model-output-json.test.ts | 369 ++++++++++++++++++ 4 files changed, 393 insertions(+), 6 deletions(-) create mode 100644 .changeset/to-model-output-json.md create mode 100644 packages/agent/tests/unit/to-model-output-json.test.ts diff --git a/.changeset/to-model-output-json.md b/.changeset/to-model-output-json.md new file mode 100644 index 00000000..574e3c9c --- /dev/null +++ b/.changeset/to-model-output-json.md @@ -0,0 +1,5 @@ +--- +'@openrouter/agent': patch +--- + +`toModelOutput` can now return `{ type: 'json', value }`, and that value is what the model receives on every tool result path (direct round, background grace settle, approval resume, and auto-approved calls persisted while a batch waits for approval). Previously a `json` result was ignored and the raw `execute` result was sent instead. A `toModelOutput` that returns any other type now fails the call instead of sending the raw result. diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index bf39a6f6..6e91e8b8 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -3633,7 +3633,9 @@ export class ModelResult< result: output, }, }); - return Array.isArray(modelOutput) ? modelOutput : output; + // A string here is the serialized `json` mapper value; parse it back so + // `unsentResultsToAPIFormat` serializes it once. + return Array.isArray(modelOutput) ? modelOutput : JSON.parse(modelOutput); } private async computeToolOutputForModel(value: { @@ -3673,7 +3675,12 @@ export class ModelResult< if (modelOutputResult.type === 'content') { return modelOutputResult.value; } - return JSON.stringify(value.result.result); + if (modelOutputResult.type === 'json') { + return JSON.stringify(modelOutputResult.value) ?? 'null'; + } + throw new Error( + `toModelOutput for "${value.toolCall.name}" must return type 'content' or 'json'`, + ); } /** diff --git a/packages/agent/src/lib/tool-types.ts b/packages/agent/src/lib/tool-types.ts index 48501abd..43b3bb6e 100644 --- a/packages/agent/src/lib/tool-types.ts +++ b/packages/agent/src/lib/tool-types.ts @@ -404,11 +404,17 @@ export type ToolOutputContentItem = /** * Result of toModelOutput function. * The 'content' type passes value array directly as tool output. + * The 'json' type sends `JSON.stringify(value)` as tool output. */ -export type ToModelOutputResult = { - type: 'content'; - value: ToolOutputContentItem[]; -}; +export type ToModelOutputResult = + | { + type: 'content'; + value: ToolOutputContentItem[]; + } + | { + type: 'json'; + value: unknown; + }; /** * Function to convert tool execution output to model-facing output. diff --git a/packages/agent/tests/unit/to-model-output-json.test.ts b/packages/agent/tests/unit/to-model-output-json.test.ts new file mode 100644 index 00000000..003eff26 --- /dev/null +++ b/packages/agent/tests/unit/to-model-output-json.test.ts @@ -0,0 +1,369 @@ +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 { tool } from '../../src/lib/tool.js'; +import type { ConversationState, StateAccessor, Tool } from '../../src/lib/tool-types.js'; + +const mockBetaResponsesSend = vi.hoisted(() => vi.fn()); + +vi.mock('@openrouter/sdk/funcs/betaResponsesSend', () => ({ + betaResponsesSend: mockBetaResponsesSend, +})); + +const { ModelResult } = await import('../../src/lib/model-result.js'); + +const SECRET = 'SENTINEL-PRIVATE-VALUE'; + +function makeResponse( + id: string, + output: models.OpenResponsesResult['output'], +): models.OpenResponsesResult { + return { + id, + object: 'response', + createdAt: 0, + model: 'test-model', + status: 'completed', + completedAt: 0, + output, + error: null, + incompleteDetails: null, + temperature: null, + topP: null, + presencePenalty: null, + frequencyPenalty: null, + metadata: null, + instructions: null, + tools: [], + toolChoice: 'auto', + parallelToolCalls: false, + }; +} + +function toolCallResponse(id: string, callId: string, args: string) { + return { + ok: true, + value: makeResponse(id, [ + { + type: 'function_call', + id: `fc_${callId}`, + callId, + name: 'lookup', + arguments: args, + status: 'completed', + }, + ]), + }; +} + +function textResponse(id: string) { + return { + ok: true, + value: makeResponse(id, [ + { + type: 'message', + id: `msg_${id}`, + role: 'assistant', + status: 'completed', + content: [ + { + type: 'output_text', + text: 'done', + annotations: [], + }, + ], + }, + ]), + }; +} + +function createMemoryAccessor(): { + accessor: StateAccessor; + get: () => ConversationState | null; +} { + let state: ConversationState | null = null; + return { + accessor: { + load: async () => state, + save: async (next) => { + state = next; + }, + }, + get: () => state, + }; +} + +/** Every function_call_output the SDK sent to the model, across all requests. */ +function sentToolOutputs(): unknown[] { + return mockBetaResponsesSend.mock.calls.flatMap((call) => { + const input = call[1]?.responsesRequest?.input; + return Array.isArray(input) + ? input + .filter((item: { type?: string }) => item?.type === 'function_call_output') + .map((item: { output: unknown }) => item.output) + : []; + }); +} + +const request = { + model: 'test-model', + input: 'look it up', +}; + +const PUBLIC = { + status: 'ok', +}; + +function redactToJson() { + return { + type: 'json' as const, + value: PUBLIC, + }; +} + +function multiCallResponse( + id: string, + calls: Array< + [ + string, + string, + ] + >, +) { + return { + ok: true, + value: makeResponse( + id, + calls.map(([callId, name]) => ({ + type: 'function_call' as const, + id: `fc_${callId}`, + callId, + name, + arguments: '{"access":"x"}', + status: 'completed' as const, + })), + ), + }; +} + +const inputSchema = z.object({ + access: z.string(), +}); + +function expectOnlyPublicOutput(outputs: unknown[]) { + expect(JSON.stringify(outputs)).not.toContain(SECRET); + expect(outputs).toContainEqual(JSON.stringify(PUBLIC)); +} + +beforeEach(() => { + mockBetaResponsesSend.mockReset(); +}); + +describe('toModelOutput json results reach the model', () => { + it('sends the json value on the direct tool round', async () => { + const lookup = tool({ + name: 'lookup', + inputSchema, + execute: async () => ({ + secret: SECRET, + }), + toModelOutput: redactToJson, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce(toolCallResponse('resp_1', 'call_1', '{"access":"x"}')) + .mockResolvedValueOnce(textResponse('resp_2')); + + await new ModelResult({ + request, + client: {} as OpenRouterCore, + tools: [ + lookup, + ] as const, + }).getResponse(); + + expectOnlyPublicOutput(sentToolOutputs()); + }); + + it('sends the json value for a background tool that settles in its grace window', async () => { + const render = tool({ + name: 'lookup', + lifecycle: 'background', + inputSchema, + outputSchema: z.object({ + secret: z.string(), + }), + graceMs: 1_000, + run: async () => ({ + secret: SECRET, + }), + toModelOutput: redactToJson, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce(toolCallResponse('resp_1', 'call_1', '{"access":"x"}')) + .mockResolvedValueOnce(textResponse('resp_2')); + + await new ModelResult({ + request, + client: {} as OpenRouterCore, + tools: [ + render, + ] as const, + }).getResponse(); + + expectOnlyPublicOutput(sentToolOutputs()); + }); + + it('sends the json value for an approved call on resume', async () => { + const lookup = tool({ + name: 'lookup', + inputSchema, + requireApproval: true, + execute: async () => ({ + secret: SECRET, + }), + toModelOutput: redactToJson, + }); + const tools = [ + lookup, + ] as const; + const { accessor, get } = createMemoryAccessor(); + + mockBetaResponsesSend.mockResolvedValueOnce( + toolCallResponse('resp_1', 'call_1', '{"access":"x"}'), + ); + await new ModelResult({ + request, + client: {} as OpenRouterCore, + tools, + state: accessor, + }).getResponse(); + expect(get()?.status).toBe('awaiting_approval'); + + mockBetaResponsesSend.mockResolvedValueOnce(textResponse('resp_2')); + await new ModelResult({ + request: { + ...request, + input: [], + }, + client: {} as OpenRouterCore, + tools, + state: accessor, + approveToolCalls: [ + 'call_1', + ], + }).getResponse(); + + expectOnlyPublicOutput(sentToolOutputs()); + }); + + it.each([ + 'sync', + 'background', + ] as const)('sends the json value for a %s call auto-approved alongside a paused one', async (lifecycle) => { + const lookup = + lifecycle === 'sync' + ? tool({ + name: 'lookup', + inputSchema, + execute: async () => ({ + secret: SECRET, + }), + toModelOutput: redactToJson, + }) + : tool({ + name: 'lookup', + lifecycle: 'background', + inputSchema, + outputSchema: z.object({ + secret: z.string(), + }), + run: async () => ({ + secret: SECRET, + }), + toModelOutput: redactToJson, + }); + const gated = tool({ + name: 'gated', + inputSchema, + requireApproval: true, + execute: async () => ({ + ok: true, + }), + }); + const tools = [ + lookup, + gated, + ] as const; + const { accessor, get } = createMemoryAccessor(); + + mockBetaResponsesSend.mockResolvedValueOnce( + multiCallResponse('resp_1', [ + [ + 'call_1', + 'lookup', + ], + [ + 'call_2', + 'gated', + ], + ]), + ); + await new ModelResult({ + request, + client: {} as OpenRouterCore, + tools, + state: accessor, + }).getResponse(); + expect(get()?.status).toBe('awaiting_approval'); + + mockBetaResponsesSend.mockResolvedValueOnce(textResponse('resp_2')); + await new ModelResult({ + request: { + ...request, + input: [], + }, + client: {} as OpenRouterCore, + tools, + state: accessor, + approveToolCalls: [ + 'call_2', + ], + }).getResponse(); + + expectOnlyPublicOutput(sentToolOutputs()); + }); + + it('refuses an unsupported toModelOutput type instead of sending the raw result', async () => { + const lookup = tool({ + name: 'lookup', + inputSchema, + execute: async () => ({ + secret: SECRET, + }), + toModelOutput: () => + ({ + type: 'text', + value: 'nope', + }) as never, + }); + + mockBetaResponsesSend + .mockResolvedValueOnce(toolCallResponse('resp_1', 'call_1', '{"access":"x"}')) + .mockResolvedValue(textResponse('resp_2')); + + await new ModelResult({ + request, + client: {} as OpenRouterCore, + tools: [ + lookup, + ] as const, + }) + .getResponse() + .catch(() => undefined); + + expect(JSON.stringify(sentToolOutputs())).not.toContain(SECRET); + }); +});