From 6879a85b0c94799bdbbe200bc3ea5f63718caa18 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:23:00 +0000 Subject: [PATCH] fix(agent): apply toModelOutput to deferred results delivered by resumeToolResults --- .changeset/to-model-output-resume.md | 5 + .../src/inner-loop/resume-tool-results.ts | 75 +++- .../agent/src/lib/task-result-for-model.ts | 80 ++++ .../tests/unit/to-model-output-resume.test.ts | 373 ++++++++++++++++++ 4 files changed, 524 insertions(+), 9 deletions(-) create mode 100644 .changeset/to-model-output-resume.md create mode 100644 packages/agent/src/lib/task-result-for-model.ts create mode 100644 packages/agent/tests/unit/to-model-output-resume.test.ts diff --git a/.changeset/to-model-output-resume.md b/.changeset/to-model-output-resume.md new file mode 100644 index 00000000..a0c145b9 --- /dev/null +++ b/.changeset/to-model-output-resume.md @@ -0,0 +1,5 @@ +--- +'@openrouter/agent': patch +--- + +A deferred tool result delivered through `resumeToolResults` (or the tool's `.resolve()` method) is now passed through the tool's `toModelOutput` before it is embedded in the `tool_task_result` message. The mapper gets the schema-parsed input of the original call (the raw arguments when parsing fails), and both `content` and `json` mapper values are delivered. Previously the raw output was sent, so a mapper that hid fields was bypassed. A mapper that throws or returns any other type now delivers the task as failed instead of sending the raw result. diff --git a/packages/agent/src/inner-loop/resume-tool-results.ts b/packages/agent/src/inner-loop/resume-tool-results.ts index 60b8555f..b43b9f97 100644 --- a/packages/agent/src/inner-loop/resume-tool-results.ts +++ b/packages/agent/src/inner-loop/resume-tool-results.ts @@ -4,6 +4,7 @@ import type * as models from '@openrouter/sdk/models'; import type { CallModelInput } from '../lib/async-params.js'; import { appendToMessages, updateState } from '../lib/conversation-state.js'; import type { ModelResult } from '../lib/model-result.js'; +import { mapTaskResultForModel } from '../lib/task-result-for-model.js'; import { validateToolOutput } from '../lib/tool-executor.js'; import { TASK_RESULT_BOUNDARY } from '../lib/tool-task.js'; import type { PendingAsyncTool, StateAccessor, Tool, ToolTaskStatus } from '../lib/tool-types.js'; @@ -246,7 +247,12 @@ export async function resumeToolResults( ); } - const envelope = buildResumeEnvelope(entry, task, request.tools); + const envelope = await buildResumeEnvelope({ + entry, + task, + tools: request.tools, + messages: state.messages, + }); envelopes.push(buildTaskResultMessage(envelope)); // Persist the entry's real terminal status. 'expired' / 'timed_out' @@ -327,17 +333,53 @@ export async function resumeToolResults( ); } +/** + * The JSON-parsed arguments of the `function_call` that started `callId`, + * or `{}` when that item is no longer in history or does not parse. + */ +function findCallArguments(messages: unknown, callId: string): unknown { + if (!Array.isArray(messages)) { + return {}; + } + for (const item of messages) { + if ( + typeof item === 'object' && + item !== null && + item.type === 'function_call' && + item.callId === callId + ) { + const args: unknown = item.arguments; + if (typeof args !== 'string') { + return args ?? {}; + } + try { + return JSON.parse(args); + } catch { + return {}; + } + } + } + return {}; +} + /** * Build the `tool_task_result` envelope for one resume entry. Successful * outputs are validated against the owning tool's `outputSchema` when the - * tool is available; error entries carry the caller's refined status - * (default `'failed'`). + * tool is available, then mapped through its `toModelOutput` (a mapper + * failure delivers the task as failed); error entries carry the caller's + * refined status (default `'failed'`). */ -function buildResumeEnvelope( - entry: ResumeToolResultEntry, - task: PendingAsyncTool, - tools: readonly Tool[] | undefined, -): ToolTaskResultEnvelope { +async function buildResumeEnvelope({ + entry, + task, + tools, + messages, +}: { + entry: ResumeToolResultEntry; + task: PendingAsyncTool; + tools: readonly Tool[] | undefined; + messages: unknown; +}): Promise { if ('output' in entry && entry.error === undefined) { const tool = tools?.find((t) => isClientTool(t) && t.function.name === task.name); // Fail closed: when a tools list was supplied but the owning tool is @@ -352,13 +394,28 @@ function buildResumeEnvelope( if (tool && isUnifiedTool(tool) && tool.function.outputSchema !== undefined) { output = validateToolOutput(tool.function.outputSchema, output); } + const mapped = await mapTaskResultForModel(tool, { + name: task.name, + input: findCallArguments(messages, task.callId), + result: output, + }); + if (!mapped.ok) { + return { + type: 'tool_task_result', + tool: task.name, + taskId: task.taskId, + callId: task.callId, + status: 'failed', + error: mapped.error, + }; + } return { type: 'tool_task_result', tool: task.name, taskId: task.taskId, callId: task.callId, status: 'completed', - result: output, + result: mapped.result, }; } return { diff --git a/packages/agent/src/lib/task-result-for-model.ts b/packages/agent/src/lib/task-result-for-model.ts new file mode 100644 index 00000000..2543e4f3 --- /dev/null +++ b/packages/agent/src/lib/task-result-for-model.ts @@ -0,0 +1,80 @@ +import * as z4 from 'zod/v4'; +import type { Tool } from './tool-types.js'; +import { isAutoResolvableTool } from './tool-types.js'; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function describeNonRecord(value: unknown): string { + if (value === null) { + return 'null'; + } + if (Array.isArray(value)) { + return 'array'; + } + return typeof value; +} + +/** Outcome of mapping a completed async task's result for the model. */ +export type TaskResultForModel = + | { + ok: true; + result: unknown; + } + | { + ok: false; + error: string; + }; + +/** + * Map a completed async task's result through the tool's `toModelOutput` + * before it is embedded in a `tool_task_result` envelope, so async + * deliveries hide the same fields as in-round results. The mapper gets the + * schema-parsed input (raw arguments when parsing fails). A mapper that + * throws or returns an unknown type yields `ok: false` so the caller + * delivers the task as failed instead of sending the raw result. + */ +export async function mapTaskResultForModel( + tool: Tool | undefined, + task: { + name: string; + input: unknown; + result: unknown; + }, +): Promise { + if (!tool || !isAutoResolvableTool(tool) || !tool.function.toModelOutput) { + return { + ok: true, + result: task.result, + }; + } + try { + const parsed = z4.safeParse(tool.function.inputSchema, task.input); + const input: unknown = parsed.success ? parsed.data : task.input; + if (!isRecord(input)) { + throw new Error( + `toolCall.arguments for "${task.name}" must be an object after Zod validation, got ${describeNonRecord(input)}`, + ); + } + const mapped: { + type: string; + value?: unknown; + } = await tool.function.toModelOutput({ + output: task.result, + input, + }); + if (mapped.type !== 'content' && mapped.type !== 'json') { + throw new Error(`toModelOutput for "${task.name}" must return type 'content' or 'json'`); + } + return { + ok: true, + result: mapped.value ?? null, + }; + } catch (error) { + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } +} diff --git a/packages/agent/tests/unit/to-model-output-resume.test.ts b/packages/agent/tests/unit/to-model-output-resume.test.ts new file mode 100644 index 00000000..f84c8a18 --- /dev/null +++ b/packages/agent/tests/unit/to-model-output-resume.test.ts @@ -0,0 +1,373 @@ +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 { resumeToolResults } from '../../src/inner-loop/resume-tool-results.js'; +import { tool } from '../../src/lib/tool.js'; +import type { ConversationState, StateAccessor } from '../../src/lib/tool-types.js'; + +const mockBetaResponsesSend = vi.hoisted(() => vi.fn()); + +vi.mock('@openrouter/sdk/funcs/betaResponsesSend', () => ({ + betaResponsesSend: mockBetaResponsesSend, +})); + +const SECRET = 'SENTINEL-PRIVATE-VALUE'; +const MASK = '[masked]'; + +const client = { + _options: {}, +} as OpenRouterCore; + +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, + } as models.OpenResponsesResult; +} + +function callResponse() { + return { + ok: true, + value: makeResponse('resp_1', [ + { + type: 'function_call', + id: 'fc_call_d', + callId: 'call_d', + name: 'lookup', + arguments: '{"id":"7"}', + 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: [], + }, + ], + }, + ]), + }; +} + +type Output = { + secret: string; + id: number; +}; + +/** + * Deferred tool whose input schema coerces `id` to a number, so the mapper + * can tell schema-parsed input from the raw wire arguments. + */ +function makeDeferredTool( + mapper?: (args: { + output: Output; + input: { + id: number; + }; + }) => unknown, +) { + const seenInputs: unknown[] = []; + const built = tool({ + name: 'lookup', + lifecycle: 'deferred', + inputSchema: z.object({ + id: z.coerce.number(), + }), + outputSchema: z.object({ + secret: z.string(), + id: z.number(), + }), + run: async ({ id }, ctx) => { + if (!ctx) { + throw new Error('no ctx'); + } + return ctx.defer(`task_${id}`); + }, + ...(mapper && { + toModelOutput: (args: { + output: Output; + input: { + id: number; + }; + }) => { + seenInputs.push(args.input); + return mapper(args) as never; + }, + }), + }); + return { + built, + seenInputs, + }; +} + +function lastUserContent(state: ConversationState | null): string { + const messages = state?.messages; + if (!Array.isArray(messages)) { + throw new Error('no messages'); + } + const last = messages[messages.length - 1] as { + role?: string; + content?: unknown; + }; + expect(last.role).toBe('user'); + return String(last.content); +} + +function envelopeOf(content: string): Record { + const line = content.split('\n').find((l) => l.includes('"tool_task_result"')); + return JSON.parse(line ?? 'null') as Record; +} + +describe('toModelOutput on resumeToolResults deliveries', () => { + let stored: ConversationState | null; + let accessor: StateAccessor; + + beforeEach(() => { + mockBetaResponsesSend.mockReset(); + stored = null; + accessor = { + load: async () => stored, + save: async (state) => { + stored = state; + }, + }; + }); + + async function startDeferred(built: ReturnType['built']) { + mockBetaResponsesSend.mockResolvedValueOnce(callResponse()); + await callModel(client, { + model: 'test-model', + input: 'look it up', + tools: [ + built, + ] as const, + state: accessor, + }).getState(); + mockBetaResponsesSend.mockReset(); + } + + it('maps a content mapper result with schema-parsed input before the model sees it', async () => { + const { built, seenInputs } = makeDeferredTool(({ input }) => ({ + type: 'content', + value: [ + { + type: 'input_text', + text: `${MASK} id=${input.id}`, + }, + ], + })); + await startDeferred(built); + + mockBetaResponsesSend.mockResolvedValueOnce(textResponse('resp_2')); + const result = await built.resolve(client, { + state: accessor, + taskId: 'task_7', + output: { + secret: SECRET, + id: 7, + }, + run: { + model: 'test-model', + }, + }); + await result?.getText(); + + const sent = JSON.stringify(mockBetaResponsesSend.mock.calls[0]?.[1]?.responsesRequest?.input); + expect(sent).not.toContain(SECRET); + expect(sent).toContain(MASK); + expect(JSON.stringify(stored?.messages)).not.toContain(SECRET); + expect(seenInputs).toEqual([ + { + id: 7, + }, + ]); + }); + + it('delivers the json mapper value in place of the raw result', async () => { + const { built } = makeDeferredTool(({ output }) => ({ + type: 'json', + value: { + id: output.id, + secret: MASK, + }, + })); + await startDeferred(built); + + await built.resolve(client, { + state: accessor, + taskId: 'task_7', + output: { + secret: SECRET, + id: 7, + }, + }); + + const content = lastUserContent(stored); + expect(content).not.toContain(SECRET); + const envelope = envelopeOf(content); + expect(envelope['status']).toBe('completed'); + expect(envelope['result']).toEqual({ + id: 7, + secret: MASK, + }); + expect(stored?.pendingAsyncTools?.[0]?.status).toBe('completed'); + }); + + it('delivers a throwing mapper as failed, never the raw result', async () => { + const { built } = makeDeferredTool(() => { + throw new Error('mapper exploded'); + }); + await startDeferred(built); + + await built.resolve(client, { + state: accessor, + taskId: 'task_7', + output: { + secret: SECRET, + id: 7, + }, + }); + + const content = lastUserContent(stored); + expect(content).not.toContain(SECRET); + const envelope = envelopeOf(content); + expect(envelope['status']).toBe('failed'); + expect(envelope['error']).toContain('mapper exploded'); + expect(envelope).not.toHaveProperty('result'); + expect(stored?.pendingAsyncTools?.[0]?.status).toBe('failed'); + }); + + it('delivers an unknown mapper result type as failed', async () => { + const { built } = makeDeferredTool(({ output }) => ({ + type: 'text', + value: output, + })); + await startDeferred(built); + + await built.resolve(client, { + state: accessor, + taskId: 'task_7', + output: { + secret: SECRET, + id: 7, + }, + }); + + const content = lastUserContent(stored); + expect(content).not.toContain(SECRET); + const envelope = envelopeOf(content); + expect(envelope['status']).toBe('failed'); + expect(envelope['error']).toContain("must return type 'content' or 'json'"); + }); + + it('passes the raw arguments when they fail the input schema', async () => { + const { built, seenInputs } = makeDeferredTool(() => ({ + type: 'json', + value: MASK, + })); + stored = { + id: 'conv_1', + version: 1, + createdAt: 0, + updatedAt: 0, + status: 'awaiting_async_tools', + messages: [ + { + type: 'function_call', + id: 'fc_call_d', + callId: 'call_d', + name: 'lookup', + arguments: '{"id":"not-a-number"}', + status: 'completed', + }, + ], + pendingAsyncTools: [ + { + callId: 'call_d', + taskId: 'task_x', + name: 'lookup', + mode: 'defer', + status: 'working', + startedAt: 0, + }, + ], + } as unknown as ConversationState; + + await resumeToolResults(client, { + state: accessor, + tools: [ + built, + ], + results: [ + { + taskId: 'task_x', + output: { + secret: SECRET, + id: 1, + }, + }, + ], + }); + + expect(seenInputs).toEqual([ + { + id: 'not-a-number', + }, + ]); + expect(envelopeOf(lastUserContent(stored))['result']).toBe(MASK); + }); + + it('keeps the raw result when the tool has no mapper', async () => { + const { built } = makeDeferredTool(); + await startDeferred(built); + + await built.resolve(client, { + state: accessor, + taskId: 'task_7', + output: { + secret: SECRET, + id: 7, + }, + }); + + expect(envelopeOf(lastUserContent(stored))['result']).toEqual({ + secret: SECRET, + id: 7, + }); + }); +});