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/deferred-tool-identity-and-hitl-stripping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@openrouter/agent": patch
---

Bind pending async tool tasks to the owning tool's schema fingerprint (`toolFingerprint`) so a different tool instance with the same public name and a looser `outputSchema` cannot settle another tool's pending task via `.resolve()`/`.fail()`/`.cancel()` or `resumeToolResults()`, and serialize Zod-validated `outputSchema` data (`validation.data`) in HITL `invokeOnResponseReceived` and `computeHitlItemOutput` so stripped fields are not forwarded to the model.
118 changes: 90 additions & 28 deletions packages/agent/src/inner-loop/resume-tool-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +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 { validateToolOutput } from '../lib/tool-executor.js';
import { computeToolFingerprint, 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';
import { isClientTool, isUnifiedTool } from '../lib/tool-types.js';
Expand Down Expand Up @@ -209,6 +209,14 @@ export async function resumeToolResults<TTools extends readonly Tool[]>(
* webhook cannot settle a different tool's task through them.
*/
expectToolName?: string;
/**
* Ownership guard: every resolved task must match this tool's identity
* (name AND schema fingerprint) or the call throws BEFORE anything is
* persisted. Set by the typed `.resolve()`/`.fail()`/`.cancel()` methods
* so a separate tool instance with the same public name and a looser
* `outputSchema` cannot settle another tool's pending task.
*/
expectTool?: Tool;
},
options?: RequestOptions,
): Promise<ModelResult<TTools> | null> {
Expand All @@ -235,18 +243,9 @@ export async function resumeToolResults<TTools extends readonly Tool[]>(
continue; // already settled and the caller asked to ignore it
}

// Ownership guard: a taskId is an external identifier handed to
// third-party systems — a lower-trust webhook must not be able to
// settle a DIFFERENT tool's task through a tool-bound completion
// method (confused deputy; it would also skip that tool's
// outputSchema validation).
if (request.expectToolName !== undefined && task.name !== request.expectToolName) {
throw new Error(
`resumeToolResults: task "${task.taskId}" belongs to tool "${task.name}", not "${request.expectToolName}" — use the owning tool's completion methods (or the untyped resumeToolResults entry point).`,
);
}
await assertTaskOwnership(task, request);

const envelope = buildResumeEnvelope(entry, task, request.tools);
const envelope = await buildResumeEnvelope(entry, task, request.tools);

envelopes.push(buildTaskResultMessage(envelope));
// Persist the entry's real terminal status. 'expired' / 'timed_out'
Expand Down Expand Up @@ -327,38 +326,101 @@ export async function resumeToolResults<TTools extends readonly Tool[]>(
);
}

async function assertToolFingerprintMatch(
task: PendingAsyncTool,
tool: Tool,
reason: string,
): Promise<void> {
if (task.toolFingerprint === undefined) {
return;
}
const candidateFingerprint = await computeToolFingerprint(tool);
if (candidateFingerprint !== task.toolFingerprint) {
throw new Error(
`resumeToolResults: task "${task.taskId}" belongs to a different "${task.name}" tool definition (schema mismatch) — ${reason}.`,
);
}
}

/**
* Ownership guard: verify both tool name and schema fingerprint so a separate
* tool definition with the same public name and a looser `outputSchema` cannot
* settle another tool's pending task.
*/
async function assertTaskOwnership(
task: PendingAsyncTool,
request: {
expectTool?: Tool;
expectToolName?: string;
tools?: readonly Tool[];
},
): Promise<void> {
const { expectTool, expectToolName, tools } = request;
const expectedName =
expectTool && isClientTool(expectTool) ? expectTool.function.name : expectToolName;
if (expectedName !== undefined && task.name !== expectedName) {
throw new Error(
`resumeToolResults: task "${task.taskId}" belongs to tool "${task.name}", not "${expectedName}" — use the owning tool's completion methods (or the untyped resumeToolResults entry point).`,
);
}
const boundTool =
expectTool ??
(expectedName !== undefined
? tools?.find((t) => isClientTool(t) && t.function.name === expectedName)
: undefined);
if (boundTool !== undefined) {
await assertToolFingerprintMatch(task, boundTool, "use the owning tool's completion methods");
}
}

async function validateResumedOutput(
output: unknown,
task: PendingAsyncTool,
tools: readonly Tool[] | undefined,
): Promise<unknown> {
if (tools === undefined) {
return output;
}
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
// not in it, the caller expected validation — appending the output
// unvalidated would silently void that expectation.
if (tool === undefined) {
throw new Error(
`resumeToolResults: task "${task.taskId}" belongs to tool "${task.name}", which is not in the supplied tools list — its output cannot be validated. Include the tool, or omit \`tools\` to skip validation explicitly.`,
);
}
await assertToolFingerprintMatch(
task,
tool,
'its output cannot be validated against a substitute tool',
);
if (isUnifiedTool(tool) && tool.function.outputSchema !== undefined) {
return validateToolOutput(tool.function.outputSchema, output);
}
return output;
}

/**
* 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'`).
*/
function buildResumeEnvelope(
async function buildResumeEnvelope(
entry: ResumeToolResultEntry,
task: PendingAsyncTool,
tools: readonly Tool[] | undefined,
): ToolTaskResultEnvelope {
): 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
// not in it, the caller expected validation — appending the output
// unvalidated would silently void that expectation.
if (tools !== undefined && tool === undefined) {
throw new Error(
`resumeToolResults: task "${task.taskId}" belongs to tool "${task.name}", which is not in the supplied tools list — its output cannot be validated. Include the tool, or omit \`tools\` to skip validation explicitly.`,
);
}
let output = entry.output;
if (tool && isUnifiedTool(tool) && tool.function.outputSchema !== undefined) {
output = validateToolOutput(tool.function.outputSchema, output);
}
const result = await validateResumedOutput(entry.output, task, tools);
return {
type: 'tool_task_result',
tool: task.name,
taskId: task.taskId,
callId: task.callId,
status: 'completed',
result: output,
result,
};
}
return {
Expand Down
10 changes: 10 additions & 0 deletions packages/agent/src/lib/async-tool-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,17 @@ export class AsyncToolRegistry {
callId: string;
taskId: string;
name: string;
toolFingerprint?: string;
expiresAt?: number;
pollAfterMs?: number;
}): ToolTask {
const task = new ToolTask({
taskId: entry.taskId,
callId: entry.callId,
toolName: entry.name,
...(entry.toolFingerprint !== undefined && {
toolFingerprint: entry.toolFingerprint,
}),
mode: 'defer',
...(entry.expiresAt !== undefined && {
expiresAt: entry.expiresAt,
Expand Down Expand Up @@ -276,6 +280,9 @@ export class AsyncToolRegistry {
callId: task.callId,
taskId: task.taskId,
name: task.toolName,
...(task.toolFingerprint !== undefined && {
toolFingerprint: task.toolFingerprint,
}),
mode: task.mode,
status: task.status,
startedAt: task.startedAt,
Expand All @@ -298,6 +305,9 @@ export class AsyncToolRegistry {
callId: t.callId,
taskId: t.taskId,
name: t.toolName,
...(t.toolFingerprint !== undefined && {
toolFingerprint: t.toolFingerprint,
}),
mode: t.mode,
status: t.status,
startedAt: t.startedAt,
Expand Down
113 changes: 60 additions & 53 deletions packages/agent/src/lib/model-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ import type { AsyncToolInvocation } from './tool-executor.js';
import {
applyOnResponseReceivedHooks,
assertUniqueClientToolNames,
computeToolFingerprint,
executeTool,
isAsyncToolInvocation,
validateToolInput,
Expand Down Expand Up @@ -3099,6 +3100,7 @@ export class ModelResult<
*/
private async settleAsyncInvocationAsUnsent(
tc: ParsedToolCall<TTools[number]>,
tool: Tool,
invocation: AsyncToolInvocation,
deadline?: {
timeoutMs: number | undefined;
Expand Down Expand Up @@ -3149,32 +3151,7 @@ export class ModelResult<
}
}

const registry = this.ensureAsyncToolRegistry();
const liveTask = registry.trackDeferred({
callId: tc.id,
taskId: invocation.taskId,
name: String(tc.name),
...(invocation.pollAfterMs !== undefined && {
pollAfterMs: invocation.pollAfterMs,
}),
...(invocation.expiresAt !== undefined && {
expiresAt: invocation.expiresAt,
}),
});
const task: PendingAsyncTool = {
callId: tc.id,
taskId: invocation.taskId,
name: String(tc.name),
mode: 'defer',
status: 'working',
startedAt: liveTask.startedAt,
...(invocation.pollAfterMs !== undefined && {
pollAfterMs: invocation.pollAfterMs,
}),
...(invocation.expiresAt !== undefined && {
expiresAt: invocation.expiresAt,
}),
};
const { pendingTask: task } = await this.registerDeferredTask(tc, tool, invocation);
if (this.currentState) {
this.currentState = updateState(this.currentState, {
pendingAsyncTools: [
Expand Down Expand Up @@ -3261,7 +3238,7 @@ export class ModelResult<
}

if (isAsyncToolInvocation(result)) {
return await this.settleAsyncInvocationAsUnsent(toolCall, result, {
return await this.settleAsyncInvocationAsUnsent(toolCall, tool, result, {
timeoutMs,
controller,
});
Expand Down Expand Up @@ -4372,6 +4349,56 @@ export class ModelResult<
*
* Deferred: emit the placeholder and report the task for the pause path.
*/
private async registerDeferredTask(
toolCall: {
id: string;
name: PropertyKey;
},
tool: Tool,
invocation: Extract<
AsyncToolInvocation,
{
asyncMode: 'defer';
}
>,
): Promise<{
liveTask: ToolTask;
pendingTask: PendingAsyncTool;
}> {
const registry = this.ensureAsyncToolRegistry();
const toolFingerprint = await computeToolFingerprint(tool);
const optionalFields = {
...(toolFingerprint !== undefined && {
toolFingerprint,
}),
...(invocation.pollAfterMs !== undefined && {
pollAfterMs: invocation.pollAfterMs,
}),
...(invocation.expiresAt !== undefined && {
expiresAt: invocation.expiresAt,
}),
};
const liveTask = registry.trackDeferred({
callId: toolCall.id,
taskId: invocation.taskId,
name: String(toolCall.name),
...optionalFields,
});
const pendingTask: PendingAsyncTool = {
callId: toolCall.id,
taskId: invocation.taskId,
name: String(toolCall.name),
mode: 'defer',
status: 'working',
startedAt: liveTask.startedAt,
...optionalFields,
};
return {
liveTask,
pendingTask,
};
}

private async handleAsyncInvocation(value: {
toolCall: ParsedToolCall<Tool>;
tool: Tool;
Expand All @@ -4393,32 +4420,8 @@ export class ModelResult<
if (collision) {
return collision;
}
const liveTask = registry.trackDeferred({
callId: toolCall.id,
taskId: invocation.taskId,
name: String(toolCall.name),
...(invocation.expiresAt !== undefined && {
expiresAt: invocation.expiresAt,
}),
...(invocation.pollAfterMs !== undefined && {
pollAfterMs: invocation.pollAfterMs,
}),
});
const { liveTask, pendingTask } = await this.registerDeferredTask(toolCall, tool, invocation);
runBinding.bind(liveTask);
const task: PendingAsyncTool = {
callId: toolCall.id,
taskId: invocation.taskId,
name: String(toolCall.name),
mode: 'defer',
status: 'working',
startedAt: liveTask.startedAt,
...(invocation.pollAfterMs !== undefined && {
pollAfterMs: invocation.pollAfterMs,
}),
...(invocation.expiresAt !== undefined && {
expiresAt: invocation.expiresAt,
}),
};
this.broadcastAsyncStarted(toolCall, 'defer', invocation.taskId, invocation.ack);
return {
output: this.buildPendingPlaceholder(
Expand All @@ -4427,18 +4430,22 @@ export class ModelResult<
invocation.ack,
invocation.pollAfterMs,
),
deferredTask: task,
deferredTask: pendingTask,
};
}

// Background: start the work under the background pool. The pool slot is
// held for the duration of the work (queue wait counts against the
// task's own timeout tracked by the registry).
const taskId = registry.generateTaskId();
const toolFingerprint = await computeToolFingerprint(tool);
const liveTask = new ToolTask({
taskId,
callId: toolCall.id,
toolName: String(toolCall.name),
...(toolFingerprint !== undefined && {
toolFingerprint,
}),
mode: isAgentTool(tool) ? 'agent' : 'background',
controller,
...(logLimits !== undefined && {
Expand Down
Loading
Loading