From 6654f5d933d5aa164ac9a5350fb9a41aed9ef13c Mon Sep 17 00:00:00 2001 From: Alex Bujduveanu Date: Mon, 30 Nov 2026 16:03:02 +0000 Subject: [PATCH] fix(agent): apply toModelOutput to late background tool results Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .changeset/to-model-output-late-background.md | 5 + packages/agent/src/lib/model-result.ts | 108 ++++-- .../to-model-output-late-background.test.ts | 322 ++++++++++++++++++ 3 files changed, 403 insertions(+), 32 deletions(-) create mode 100644 .changeset/to-model-output-late-background.md create mode 100644 packages/agent/tests/unit/to-model-output-late-background.test.ts diff --git a/.changeset/to-model-output-late-background.md b/.changeset/to-model-output-late-background.md new file mode 100644 index 00000000..cff9815f --- /dev/null +++ b/.changeset/to-model-output-late-background.md @@ -0,0 +1,5 @@ +--- +'@openrouter/agent': patch +--- + +A background tool result that arrives after `graceMs` is now passed through the tool's `toModelOutput` before it is embedded in the `tool_task_result` message, both when it is delivered during the run and when it is persisted after the run ends. The mapper gets the schema-parsed input (the raw arguments when parsing fails), and both `content` and `json` mapper values are delivered. Previously the raw `execute` result 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/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index bf39a6f6..5ec09df2 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -286,6 +286,23 @@ const DUPLICATE_CALL_ID = Symbol('duplicate-call-id'); * Human-readable label for a value that failed the `isRecord` check. Used * exclusively to make `toModelOutput` misuse errors specific. */ +/** Serialize one settled task as a `tool_task_result` envelope line. */ +function lateTaskEnvelope(task: SettledToolTask): string { + return JSON.stringify({ + type: 'tool_task_result', + tool: task.name, + taskId: task.taskId, + callId: task.callId, + status: task.status, + ...(task.result !== undefined && { + result: task.result, + }), + ...(task.error !== undefined && { + error: task.error, + }), + }); +} + function describeNonRecord(value: unknown): string { if (value === null) { return 'null'; @@ -3550,28 +3567,17 @@ export class ModelResult< // must cover long-running results, which are exactly the ones that // arrive from external processes. await this.emitAsyncSettledHooks(task); - envelopes.push( - JSON.stringify({ - type: 'tool_task_result', - tool: task.name, - taskId: task.taskId, - callId: task.callId, - status: task.status, - ...(task.result !== undefined && { - result: task.result, - }), - ...(task.error !== undefined && { - error: task.error, - }), - }), - ); + const delivered = await this.lateTaskForModel(task); + envelopes.push(lateTaskEnvelope(delivered)); // Record settlement for the at-most-once guard. The pending entry is // KEPT with its terminal status (not removed) — same policy as // resumeToolResults — so a late external resolution by taskId OR // callId resolves to ToolTaskAlreadySettledError, never "not found". if (this.currentState) { const terminalStatus = - task.status === 'completed' || task.status === 'cancelled' ? task.status : 'failed'; + delivered.status === 'completed' || delivered.status === 'cancelled' + ? delivered.status + : 'failed'; this.currentState = updateState(this.currentState, { settledAsyncCallIds: [ ...(this.currentState.settledAsyncCallIds ?? []), @@ -3604,6 +3610,54 @@ export class ModelResult< return true; } + /** + * Map a settled background task's result through the tool's + * `toModelOutput` before it is embedded in a `tool_task_result` envelope, + * so late deliveries hide the same fields as in-round results. The mapper + * gets the schema-parsed input (raw arguments when parsing fails, as in + * `computeToolOutputForModel`). A mapper that throws or returns an + * unknown type fails the delivery instead of sending the raw result. + */ + private async lateTaskForModel(task: SettledToolTask): Promise { + if (task.status !== 'completed') { + return task; + } + const tool = this.options.tools?.find((t) => isClientTool(t) && t.function.name === task.name); + if (!tool || !isAutoResolvableTool(tool) || !tool.function.toModelOutput) { + return task; + } + const { result: _raw, ...rest } = task; + 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 { + ...rest, + result: mapped.value ?? null, + }; + } catch (error) { + return { + ...rest, + status: 'failed', + error: error instanceof Error ? error.message : String(error), + }; + } + } + /** * Compute the `output` payload sent to the model for a successfully * settled tool execution. Routes through `toModelOutput` when the tool @@ -5095,27 +5149,17 @@ export class ModelResult< if (settled.length === 0 || !this.stateAccessor || !this.currentState) { return; } + const delivered: SettledToolTask[] = []; + for (const task of settled) { + delivered.push(await this.lateTaskForModel(task)); + } const terminalByCallId = new Map( - settled.map((t) => [ + delivered.map((t) => [ t.callId, t.status === 'completed' || t.status === 'cancelled' ? t.status : ('failed' as const), ]), ); - const envelopes = settled.map((t) => - JSON.stringify({ - type: 'tool_task_result', - tool: t.name, - taskId: t.taskId, - callId: t.callId, - status: t.status, - ...(t.result !== undefined && { - result: t.result, - }), - ...(t.error !== undefined && { - error: t.error, - }), - }), - ); + const envelopes = delivered.map(lateTaskEnvelope); await this.saveStateSafely({ messages: appendToMessages(this.currentState.messages, [ { diff --git a/packages/agent/tests/unit/to-model-output-late-background.test.ts b/packages/agent/tests/unit/to-model-output-late-background.test.ts new file mode 100644 index 00000000..0857fc6e --- /dev/null +++ b/packages/agent/tests/unit/to-model-output-late-background.test.ts @@ -0,0 +1,322 @@ +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 { 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(id: string) { + return { + ok: true, + value: makeResponse(id, [ + { + type: 'function_call', + id: 'fc_call_bg', + callId: 'call_bg', + 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: [], + }, + ], + }, + ]), + }; +} + +/** + * Background tool that always outlives `graceMs`, so its result arrives as a + * late `tool_task_result` envelope. The input schema coerces `id` to a + * number, so the mapper can tell parsed input from raw wire arguments. + */ +function makeLateTool( + mapper: (args: { + output: { + secret: string; + id: number; + }; + input: { + id: number; + }; + }) => unknown, +) { + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const seenInputs: unknown[] = []; + const built = tool({ + name: 'lookup', + lifecycle: 'background', + inputSchema: z.object({ + id: z.coerce.number(), + }), + outputSchema: z.object({ + secret: z.string(), + id: z.number(), + }), + graceMs: 0, + run: async ({ id }) => { + await gate; + return { + secret: SECRET, + id, + }; + }, + toModelOutput: (async (args: { + output: { + secret: string; + id: number; + }; + input: { + id: number; + }; + }) => { + seenInputs.push(args.input); + return mapper(args); + }) as never, + }); + return { + tool: built, + release: () => release?.(), + seenInputs, + }; +} + +function userEnvelopes(callIndex: number): string[] { + const input = mockBetaResponsesSend.mock.calls[callIndex]?.[1]?.responsesRequest?.input as Array<{ + role?: string; + content?: unknown; + }>; + return input + .filter((m) => m.role === 'user' && typeof m.content === 'string') + .map((m) => m.content as string) + .filter((c) => c.includes('tool_task_result')); +} + +function allRequestText(): string { + return JSON.stringify(mockBetaResponsesSend.mock.calls.map((c) => c[1]?.responsesRequest?.input)); +} + +async function runInRun(late: ReturnType) { + mockBetaResponsesSend + .mockResolvedValueOnce(callResponse('resp_1')) + .mockImplementationOnce(async () => { + late.release(); + return textResponse('resp_2'); + }) + .mockResolvedValueOnce(textResponse('resp_3')); + + await callModel(client, { + model: 'test-model', + input: 'look it up', + tools: [ + late.tool, + ] as const, + asyncTools: { + onRunEnd: 'drain', + drainTimeoutMs: 5_000, + }, + }).getText(); + + expect(mockBetaResponsesSend).toHaveBeenCalledTimes(3); + const envelopes = userEnvelopes(2); + expect(envelopes).toHaveLength(1); + return envelopes[0] ?? ''; +} + +describe('toModelOutput on late background deliveries', () => { + beforeEach(() => { + mockBetaResponsesSend.mockReset(); + }); + + it('applies a content mapper to the delivered envelope, with schema-parsed input', async () => { + const late = makeLateTool(({ output }) => ({ + type: 'content', + value: [ + { + type: 'input_text', + text: `id=${output.id} secret=${MASK}`, + }, + ], + })); + + const envelope = await runInRun(late); + + expect(envelope).toContain(`id=7 secret=${MASK}`); + expect(envelope).toContain('"status":"completed"'); + expect(allRequestText()).not.toContain(SECRET); + expect(late.seenInputs).toEqual([ + { + id: 7, + }, + ]); + }); + + it('applies a json mapper to the delivered envelope', async () => { + const late = makeLateTool(({ output }) => ({ + type: 'json', + value: { + id: output.id, + secret: MASK, + }, + })); + + const envelope = await runInRun(late); + + expect(envelope).toContain(`"result":{"id":7,"secret":"${MASK}"}`); + expect(allRequestText()).not.toContain(SECRET); + }); + + it('fails the delivery closed when the mapper returns an unknown type', async () => { + const late = makeLateTool(({ output }) => ({ + type: 'text', + value: output.secret, + })); + + const envelope = await runInRun(late); + + expect(envelope).toContain('"status":"failed"'); + expect(envelope).toContain("must return type 'content' or 'json'"); + expect(allRequestText()).not.toContain(SECRET); + }); + + it('fails the delivery closed when the mapper throws', async () => { + const late = makeLateTool(() => { + throw new Error('mapper refused'); + }); + + const envelope = await runInRun(late); + + expect(envelope).toContain('"status":"failed"'); + expect(envelope).toContain('mapper refused'); + expect(allRequestText()).not.toContain(SECRET); + }); + + it('falls back to the raw arguments when they do not parse against the input schema', async () => { + const late = makeLateTool(({ output }) => ({ + type: 'json', + value: { + id: output.id, + }, + })); + // The mapper runs after `execute`; make the parse fail only at mapping + // time by refining the schema after the tool was built. + const fn = late.tool.function as { + inputSchema: z.ZodType; + }; + const original = fn.inputSchema; + let calls = 0; + fn.inputSchema = original.refine(() => { + calls++; + return calls === 1; + }); + + const envelope = await runInRun(late); + + expect(envelope).toContain('"result":{"id":7}'); + expect(late.seenInputs).toEqual([ + { + id: '7', + }, + ]); + }); + + it('applies the mapper to an envelope persisted after the run ends', async () => { + let stored: ConversationState | null = null; + const accessor: StateAccessor = { + load: async () => stored, + save: async (s) => { + stored = s; + }, + }; + const late = makeLateTool(({ output }) => ({ + type: 'json', + value: { + id: output.id, + secret: MASK, + }, + })); + + mockBetaResponsesSend + .mockResolvedValueOnce(callResponse('resp_1')) + .mockImplementationOnce(async () => { + late.release(); + return textResponse('resp_2'); + }); + + await callModel(client, { + model: 'test-model', + input: 'look it up', + tools: [ + late.tool, + ] as const, + state: accessor, + asyncTools: { + onRunEnd: 'cancel', + }, + }).getText(); + + const persisted = JSON.stringify((stored as ConversationState | null)?.messages ?? []); + expect(persisted).toContain('tool_task_result'); + expect(persisted).not.toContain(SECRET); + }); +});