Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/to-model-output-resume.md
Original file line number Diff line number Diff line change
@@ -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.
75 changes: 66 additions & 9 deletions packages/agent/src/inner-loop/resume-tool-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -246,7 +247,12 @@ export async function resumeToolResults<TTools extends readonly Tool[]>(
);
}

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'
Expand Down Expand Up @@ -327,17 +333,53 @@ export async function resumeToolResults<TTools extends readonly Tool[]>(
);
}

/**
* 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<ToolTaskResultEnvelope> {
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
Expand All @@ -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 {
Expand Down
80 changes: 80 additions & 0 deletions packages/agent/src/lib/task-result-for-model.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
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<TaskResultForModel> {
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),
};
}
}
Loading