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-late-background.md
Original file line number Diff line number Diff line change
@@ -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.
108 changes: 76 additions & 32 deletions packages/agent/src/lib/model-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 ?? []),
Expand Down Expand Up @@ -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<SettledToolTask> {
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
Expand Down Expand Up @@ -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, [
{
Expand Down
Loading
Loading