diff --git a/.changeset/deferred-tool-identity-and-hitl-stripping.md b/.changeset/deferred-tool-identity-and-hitl-stripping.md new file mode 100644 index 00000000..870334f9 --- /dev/null +++ b/.changeset/deferred-tool-identity-and-hitl-stripping.md @@ -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. diff --git a/packages/agent/src/inner-loop/resume-tool-results.ts b/packages/agent/src/inner-loop/resume-tool-results.ts index 60b8555f..3f47afef 100644 --- a/packages/agent/src/inner-loop/resume-tool-results.ts +++ b/packages/agent/src/inner-loop/resume-tool-results.ts @@ -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'; @@ -209,6 +209,14 @@ export async function resumeToolResults( * 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 | null> { @@ -235,18 +243,9 @@ export async function resumeToolResults( 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' @@ -327,38 +326,101 @@ export async function resumeToolResults( ); } +async function assertToolFingerprintMatch( + task: PendingAsyncTool, + tool: Tool, + reason: string, +): Promise { + 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 { + 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 { + 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 { 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 { diff --git a/packages/agent/src/lib/async-tool-registry.ts b/packages/agent/src/lib/async-tool-registry.ts index 27f49146..5458854c 100644 --- a/packages/agent/src/lib/async-tool-registry.ts +++ b/packages/agent/src/lib/async-tool-registry.ts @@ -147,6 +147,7 @@ export class AsyncToolRegistry { callId: string; taskId: string; name: string; + toolFingerprint?: string; expiresAt?: number; pollAfterMs?: number; }): ToolTask { @@ -154,6 +155,9 @@ export class AsyncToolRegistry { taskId: entry.taskId, callId: entry.callId, toolName: entry.name, + ...(entry.toolFingerprint !== undefined && { + toolFingerprint: entry.toolFingerprint, + }), mode: 'defer', ...(entry.expiresAt !== undefined && { expiresAt: entry.expiresAt, @@ -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, @@ -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, diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index 8a2c0ab9..a1f5fd91 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -99,6 +99,7 @@ import type { AsyncToolInvocation } from './tool-executor.js'; import { applyOnResponseReceivedHooks, assertUniqueClientToolNames, + computeToolFingerprint, executeTool, isAsyncToolInvocation, validateToolInput, @@ -3099,6 +3100,7 @@ export class ModelResult< */ private async settleAsyncInvocationAsUnsent( tc: ParsedToolCall, + tool: Tool, invocation: AsyncToolInvocation, deadline?: { timeoutMs: number | undefined; @@ -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: [ @@ -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, }); @@ -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; @@ -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( @@ -4427,7 +4430,7 @@ export class ModelResult< invocation.ack, invocation.pollAfterMs, ), - deferredTask: task, + deferredTask: pendingTask, }; } @@ -4435,10 +4438,14 @@ export class ModelResult< // 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 && { diff --git a/packages/agent/src/lib/tool-executor.ts b/packages/agent/src/lib/tool-executor.ts index c34bab16..57bc4bcf 100644 --- a/packages/agent/src/lib/tool-executor.ts +++ b/packages/agent/src/lib/tool-executor.ts @@ -2,6 +2,7 @@ import type * as models from '@openrouter/sdk/models'; import * as z4 from 'zod/v4'; import type { $ZodObject, $ZodShape, $ZodType } from 'zod/v4/core'; import { isContentArray } from './conversation-state.js'; +import { fingerprintKeyMaterial } from './doom-loop.js'; import { isFunctionCallItem, isFunctionCallOutputItem } from './stream-type-guards.js'; import type { ToolContextStore, ToolExecutionExtras } from './tool-context.js'; import { buildToolExecuteContext, buildToolRunContext } from './tool-context.js'; @@ -20,6 +21,7 @@ import type { import { findDuplicateClientToolName, hasExecuteFunction, + isClientTool, isDeferredHandle, isGeneratorTool, isHITLTool, @@ -108,6 +110,159 @@ export function convertZodToJsonSchema(zodSchema: $ZodType): Record | undefined { + if (typeof schema !== 'object' || schema === null) { + return undefined; + } + const def = ( + schema as { + _zod?: { + def?: Record; + }; + } + )._zod?.def; + return def && typeof def === 'object' ? def : undefined; +} + +function summarizeZodChecks(checks: unknown): unknown[] | undefined { + if (!Array.isArray(checks) || checks.length === 0) { + return undefined; + } + return checks.map((c) => { + const cDef = getZodDef(c); + return { + check: typeof cDef?.['check'] === 'string' ? cDef['check'] : 'unknown', + ...(typeof cDef?.['fn'] === 'function' && { + fn: cDef['fn'].toString(), + }), + }; + }); +} + +function summarizeZodShape(shape: unknown, seen: Set): Record | undefined { + if (!shape || typeof shape !== 'object') { + return undefined; + } + const record = shape as Record; + const sorted: Record = {}; + for (const key of Object.keys(record).sort()) { + sorted[key] = summarizeZodDef(record[key], seen); + } + return sorted; +} + +const ZOD_CHILD_KEYS = [ + 'catchall', + 'innerType', + 'element', + 'keyType', + 'valueType', + 'left', + 'right', + 'in', + 'out', +] as const; + +const ZOD_LIST_KEYS = [ + 'items', + 'options', +] as const; + +function attachZodChildren( + summary: Record, + def: Record, + seen: Set, +): void { + for (const key of ZOD_CHILD_KEYS) { + if (def[key] !== undefined) { + summary[key] = summarizeZodDef(def[key], seen); + } + } + for (const key of ZOD_LIST_KEYS) { + const list = def[key]; + if (Array.isArray(list)) { + summary[key] = list.map((item) => summarizeZodDef(item, seen)); + } + } +} + +/** + * Extract a deterministic structural summary of a Zod v4 schema's internal + * definition so constraints that JSON Schema cannot represent (refinements, + * transforms, `strict`/`passthrough` catchalls, and unrepresentable types + * such as `date`, `bigint`, `any` vs `unknown`) participate in tool + * fingerprinting. + */ +function summarizeZodDef(schema: unknown, seen = new Set()): unknown { + const def = getZodDef(schema); + if (!def || typeof schema !== 'object' || schema === null) { + return null; + } + if (seen.has(schema)) { + return '[circular]'; + } + seen.add(schema); + try { + const summary: Record = { + type: typeof def['type'] === 'string' ? def['type'] : 'unknown', + }; + const checks = summarizeZodChecks(def['checks']); + if (checks !== undefined) { + summary['checks'] = checks; + } + if (typeof def['transform'] === 'function') { + summary['transform'] = def['transform'].toString(); + } + const shape = summarizeZodShape(def['shape'], seen); + if (shape !== undefined) { + summary['shape'] = shape; + } + attachZodChildren(summary, def, seen); + return summary; + } finally { + seen.delete(schema); + } +} + +function describeSchemaForFingerprint(schema: $ZodType): Record { + let jsonSchema: Record | null = null; + try { + jsonSchema = sanitizeJsonSchema( + z4.toJSONSchema(schema, { + target: 'draft-7', + unrepresentable: 'any', + }), + ); + } catch { + jsonSchema = null; + } + return { + jsonSchema, + zod: summarizeZodDef(schema), + }; +} + +/** + * Compute a deterministic SHA-256 fingerprint for a client tool from its name, + * `inputSchema`, and `outputSchema`. Persisted on `PendingAsyncTool` so + * `resumeToolResults` and deferred `.resolve()`/`.fail()`/`.cancel()` reject + * a different tool definition sharing the same public name. + */ +export async function computeToolFingerprint(tool: Tool): Promise { + if (!isClientTool(tool)) { + return undefined; + } + const outputSchema = + isUnifiedTool(tool) && tool.function.outputSchema !== undefined + ? tool.function.outputSchema + : undefined; + return fingerprintKeyMaterial({ + name: tool.function.name, + input: describeSchemaForFingerprint(tool.function.inputSchema), + output: outputSchema !== undefined ? describeSchemaForFingerprint(outputSchema) : null, + }); +} + /** * Convert tools to OpenRouter API format. Server tools pass their SDK-shaped * config through untouched; client tools are packaged into the function-call @@ -936,9 +1091,19 @@ function buildCallIdToNameMap( type HookOutput = string | models.FunctionCallOutputItemOutputUnion1[]; +function isSameHookOutput(a: HookOutput, b: HookOutput): boolean { + if (typeof a === 'string' && typeof b === 'string') { + return a === b; + } + if (Array.isArray(a) && Array.isArray(b)) { + return JSON.stringify(a) === JSON.stringify(b); + } + return false; +} + /** * Invoke `onResponseReceived`, validate the return against the tool's - * `outputSchema`, and convert the result (or any error) to a + * `outputSchema`, and convert the validated result (or any error) to a * `FunctionCallOutputItem.output` payload. */ // biome-ignore lint: parameters match the internal API shape @@ -965,7 +1130,7 @@ async function invokeOnResponseReceived( if (!validation.success) { return formatHookError(validation.error.message, parsed); } - return toFunctionCallOutputValue(hookResult); + return toFunctionCallOutputValue(validation.data); } catch (err) { // Preserve the caller's original output alongside the hook error so // the model can distinguish a hook failure from a tool-reported error. @@ -976,7 +1141,7 @@ async function invokeOnResponseReceived( /** * Compute the (optional) replacement output for a single HITL * `function_call_output` item. Returns `null` when the caller-supplied output - * is schema-conformant and should be left untouched. + * is already identical to the `outputSchema`-validated payload. */ // biome-ignore lint: parameters match the internal API shape async function computeHitlItemOutput( @@ -992,11 +1157,14 @@ async function computeHitlItemOutput( return invokeOnResponseReceived(tool, parsed, context, contextStore, sharedSchema); } - // No hook — validate the parsed raw output against outputSchema. On - // success, leave the item untouched; on failure, surface an error wrapper. + // No hook — validate the parsed raw output against outputSchema. Serialize + // `validation.data` so extra fields stripped by `outputSchema` (or defaults / + // transforms) are never forwarded to the model, while leaving already- + // identical items untouched to preserve array references. const validation = z4.safeParse(tool.function.outputSchema, parsed); if (validation.success) { - return null; + const serialized = toFunctionCallOutputValue(validation.data); + return isSameHookOutput(item.output, serialized) ? null : serialized; } return formatHookError(validation.error.message, parsed); } diff --git a/packages/agent/src/lib/tool-task.ts b/packages/agent/src/lib/tool-task.ts index 94b07c1f..aab74869 100644 --- a/packages/agent/src/lib/tool-task.ts +++ b/packages/agent/src/lib/tool-task.ts @@ -133,6 +133,7 @@ export class ToolTask { readonly taskId: string; readonly callId: string; readonly toolName: string; + readonly toolFingerprint?: string; readonly mode: ToolTaskMode; readonly startedAt: number; status: ToolTaskStatus; @@ -163,6 +164,7 @@ export class ToolTask { taskId: string; callId: string; toolName: string; + toolFingerprint?: string; mode: ToolTaskMode; expiresAt?: number; pollAfterMs?: number; @@ -173,6 +175,9 @@ export class ToolTask { this.taskId = entry.taskId; this.callId = entry.callId; this.toolName = entry.toolName; + if (entry.toolFingerprint !== undefined) { + this.toolFingerprint = entry.toolFingerprint; + } this.mode = entry.mode; this.status = 'working'; this.startedAt = Date.now(); diff --git a/packages/agent/src/lib/tool-types.ts b/packages/agent/src/lib/tool-types.ts index 48501abd..f68b80b6 100644 --- a/packages/agent/src/lib/tool-types.ts +++ b/packages/agent/src/lib/tool-types.ts @@ -1909,6 +1909,14 @@ export interface PendingAsyncTool { * `onRunEnd: 'detach'` — its result will never be delivered. */ orphaned?: boolean; + /** + * Deterministic SHA-256 fingerprint of the owning tool's name and schemas + * (`inputSchema` + `outputSchema`). Persisted so `resumeToolResults` and + * deferred completion methods can verify that a settling tool carries the + * same contract as the tool that started the task — even across processes. + * Additive within ConversationState version 1. + */ + toolFingerprint?: string; /** * The most recent log entry, truncated (~200 chars) — the one piece of * progress that survives a process restart. Additive within diff --git a/packages/agent/src/lib/tool.ts b/packages/agent/src/lib/tool.ts index ac9a4afe..8ecc4b70 100644 --- a/packages/agent/src/lib/tool.ts +++ b/packages/agent/src/lib/tool.ts @@ -938,7 +938,9 @@ function bindDeferredCompletion( toolValue, ], // Ownership guard: a taskId handed to an external system must not - // settle a DIFFERENT tool's task through this tool's methods. + // settle a DIFFERENT tool's task through this tool's methods — bind + // both the tool name and its schema fingerprint. + expectTool: toolValue, ...(isClientTool(toolValue) && { expectToolName: toolValue.function.name, }), diff --git a/packages/agent/tests/unit/async-tool-deferred.test.ts b/packages/agent/tests/unit/async-tool-deferred.test.ts index 2a115bf8..fa4bd078 100644 --- a/packages/agent/tests/unit/async-tool-deferred.test.ts +++ b/packages/agent/tests/unit/async-tool-deferred.test.ts @@ -804,4 +804,207 @@ describe('tool.deferred — cross-process resume', () => { /* Nothing was persisted: the task is still working, no envelope appended. */ expect(get()?.pendingAsyncTools?.[0]?.status).toBe('working'); }); + + it('.resolve(), .fail(), and .cancel() reject a different tool with the same name and looser outputSchema', async () => { + const { accessor, get } = await pauseConversation(); + + const spoofLegalReview = tool({ + name: 'request_legal_review', + lifecycle: 'deferred', + inputSchema: z.object({ + contractId: z.string(), + }), + outputSchema: z.any(), + run: async ({ contractId }, ctx) => { + if (!ctx) { + throw new Error('run context missing'); + } + return ctx.defer(`spoof_${contractId}`); + }, + }); + + await expect( + spoofLegalReview.resolve(client, { + state: accessor, + taskId: 'ticket_c-9', + output: { + approved: 'bypassed', + injected: true, + }, + }), + ).rejects.toThrow('schema mismatch'); + + await expect( + spoofLegalReview.fail(client, { + state: accessor, + taskId: 'ticket_c-9', + error: 'spoofed failure', + }), + ).rejects.toThrow('schema mismatch'); + + await expect( + spoofLegalReview.cancel(client, { + state: accessor, + taskId: 'ticket_c-9', + reason: 'spoofed cancel', + }), + ).rejects.toThrow('schema mismatch'); + + // Nothing was persisted; the owning tool can still resolve normally. + expect(get()?.pendingAsyncTools?.[0]?.status).toBe('working'); + expect(get()?.settledAsyncCallIds ?? []).not.toContain('call_d1'); + }); + + it('.resolve() rejects a same-name tool that drops a Zod refinement from outputSchema', async () => { + const strictTool = tool({ + name: 'request_legal_review', + lifecycle: 'deferred', + inputSchema: z.object({ + contractId: z.string(), + }), + outputSchema: z + .object({ + approved: z.boolean(), + }) + .refine((v) => v.approved === true, { + message: 'must be approved', + }), + run: async ({ contractId }, ctx) => { + if (!ctx) { + throw new Error('run context missing'); + } + return ctx.defer(`strict_${contractId}`); + }, + }); + + const relaxedTool = tool({ + name: 'request_legal_review', + lifecycle: 'deferred', + inputSchema: z.object({ + contractId: z.string(), + }), + outputSchema: z.object({ + approved: z.boolean(), + }), + run: async ({ contractId }, ctx) => { + if (!ctx) { + throw new Error('run context missing'); + } + return ctx.defer(`relaxed_${contractId}`); + }, + }); + + const { accessor, get } = createMemoryAccessor(); + mockBetaResponsesSend.mockResolvedValueOnce({ + ok: true, + value: makeResponse('resp_strict', [ + functionCallItem( + 'call_strict', + 'request_legal_review', + JSON.stringify({ + contractId: 'c-1', + }), + ), + ]), + }); + await callModel(client, { + model: 'test-model', + input: 'review', + tools: [ + strictTool, + ] as const, + state: accessor, + }).getResponse(); + + await expect( + relaxedTool.resolve(client, { + state: accessor, + taskId: 'strict_c-1', + output: { + approved: false, + }, + }), + ).rejects.toThrow('schema mismatch'); + expect(get()?.pendingAsyncTools?.[0]?.status).toBe('working'); + }); + + it('resumeToolResults rejects a substitute tool with the same name and looser outputSchema', async () => { + const { accessor, get } = await pauseConversation(); + + const spoofTool = tool({ + name: 'request_legal_review', + lifecycle: 'deferred', + inputSchema: z.object({ + contractId: z.string(), + }), + outputSchema: z.record(z.string(), z.unknown()), + run: async ({ contractId }, ctx) => { + if (!ctx) { + throw new Error('run context missing'); + } + return ctx.defer(`spoof_${contractId}`); + }, + }); + + await expect( + resumeToolResults(client, { + state: accessor, + tools: [ + spoofTool, + ] as const, + results: [ + { + taskId: 'ticket_c-9', + output: { + approved: 'bypassed', + }, + }, + ], + }), + ).rejects.toThrow('schema mismatch'); + + expect(get()?.pendingAsyncTools?.[0]?.status).toBe('working'); + }); + + it('allows an equivalent tool definition in another process after JSON state round-trip', async () => { + const { get } = await pauseConversation(); + const roundTripped = JSON.parse(JSON.stringify(get())) as ConversationState; + + let stored: ConversationState | null = roundTripped; + const remoteAccessor: StateAccessor = { + load: async () => stored, + save: async (state) => { + stored = state; + }, + }; + + const recreatedLegalReview = tool({ + name: 'request_legal_review', + lifecycle: 'deferred', + inputSchema: z.object({ + contractId: z.string(), + }), + outputSchema: z.object({ + approved: z.boolean(), + notes: z.string().optional(), + }), + run: async ({ contractId }, ctx) => { + if (!ctx) { + throw new Error('run context missing'); + } + return ctx.defer(`ticket_${contractId}`); + }, + }); + + await recreatedLegalReview.resolve(client, { + state: remoteAccessor, + taskId: 'ticket_c-9', + output: { + approved: true, + notes: 'ok', + }, + }); + + expect(stored?.pendingAsyncTools?.[0]?.status).toBe('completed'); + }); }); diff --git a/packages/agent/tests/unit/hitl-tool.test.ts b/packages/agent/tests/unit/hitl-tool.test.ts index 55500d2f..5458455f 100644 --- a/packages/agent/tests/unit/hitl-tool.test.ts +++ b/packages/agent/tests/unit/hitl-tool.test.ts @@ -1043,6 +1043,146 @@ describe('applyOnResponseReceivedHooks', () => { ); expect(result).toBe(input); }); + + it('strips extra fields from onResponseReceived return value per outputSchema', async () => { + const t = tool({ + name: 'approve', + inputSchema: z.object({ + amount: z.number(), + }), + outputSchema: z.object({ + ok: z.boolean(), + }), + onToolCalled: async () => null, + onResponseReceived: async (raw) => { + if (!isRawRecord(raw)) { + return { + ok: false, + }; + } + return { + ok: Boolean(raw['ok']), + secretToken: 'should-be-stripped', + } as { + ok: boolean; + }; + }, + }); + + const input: models.InputsUnion = [ + callItem('c1', 'approve'), + outputItem( + 'c1', + JSON.stringify({ + ok: true, + }), + ), + ]; + + const result = await applyOnResponseReceivedHooks( + input, + [ + t, + ], + turnContext, + ); + const arr = result as unknown[]; + const out = arr[1] as models.FunctionCallOutputItem; + expect(out.output).toBe( + JSON.stringify({ + ok: true, + }), + ); + }); + + it('strips extra fields from raw output per outputSchema when no onResponseReceived hook is defined', async () => { + const t = tool({ + name: 'approve', + inputSchema: z.object({ + amount: z.number(), + }), + outputSchema: z.object({ + ok: z.boolean(), + }), + onToolCalled: async () => null, + }); + + const input: models.InputsUnion = [ + callItem('c1', 'approve'), + outputItem( + 'c1', + JSON.stringify({ + ok: true, + internalSecret: 'must-not-reach-model', + }), + ), + ]; + + const result = await applyOnResponseReceivedHooks( + input, + [ + t, + ], + turnContext, + ); + expect(result).not.toBe(input); + const arr = result as unknown[]; + const out = arr[1] as models.FunctionCallOutputItem; + expect(out.output).toBe( + JSON.stringify({ + ok: true, + }), + ); + }); + + it('strips extra fields from content-array output when no onResponseReceived hook is defined', async () => { + const t = tool({ + name: 'describe', + inputSchema: z.object({ + id: z.string(), + }), + outputSchema: z.array( + z.object({ + type: z.literal('input_text'), + text: z.string(), + }), + ), + onToolCalled: async () => null, + }); + + const input: models.InputsUnion = [ + callItem('c1', 'describe'), + { + type: 'function_call_output', + id: 'output_c1', + callId: 'c1', + output: [ + { + type: 'input_text', + text: 'visible', + extraSecret: 'strip-me', + } as models.FunctionCallOutputItemOutputUnion1, + ], + }, + ]; + + const result = await applyOnResponseReceivedHooks( + input, + [ + t, + ], + turnContext, + ); + expect(result).not.toBe(input); + const arr = result as unknown[]; + const out = arr[1] as models.FunctionCallOutputItem; + expect(out.output).toEqual([ + { + type: 'input_text', + text: 'visible', + }, + ]); + }); }); // --------------------------------------------------------------------------- @@ -1953,6 +2093,7 @@ describe('initStream does not re-hook historical outputs (Fix #3)', () => { }), outputSchema: z.object({ ok: z.boolean(), + hooked: z.boolean().optional(), }), onToolCalled: async () => null, onResponseReceived,