diff --git a/.changeset/lifecycle-hook-input-enforcement.md b/.changeset/lifecycle-hook-input-enforcement.md new file mode 100644 index 00000000..d6765e0a --- /dev/null +++ b/.changeset/lifecycle-hook-input-enforcement.md @@ -0,0 +1,5 @@ +--- +"@openrouter/agent": patch +--- + +Parse tool arguments through `inputSchema` before emitting `PreToolUse` (as well as `PermissionRequest`, `PostToolUse`, and `PostToolUseFailure`) so hooks inspect the same defaulted, coerced, and transformed values that `execute` receives, and support structured content-array user messages (`input_text` / `text` blocks and multimodal arrays) in `UserPromptSubmit`. diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index bf39a6f6..3e1625a6 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -344,9 +344,28 @@ function extractModelCallUsage(usage: models.Usage | null | undefined): ModelCal }; } +type UserTextContentPart = { + type: 'input_text' | 'text'; + text: string; +}; + +/** + * Type guard for a text content block inside a structured user message + * (`{ type: 'input_text', text: string }` or `{ type: 'text', text: string }`). + */ +function isUserTextContentPart(value: unknown): value is UserTextContentPart { + if (typeof value !== 'object' || value === null) { + return false; + } + const obj = value as { + type?: unknown; + text?: unknown; + }; + return (obj.type === 'input_text' || obj.type === 'text') && typeof obj.text === 'string'; +} + /** * Type guard for an input message with a user role and a string `content`. - * These are the messages we can safely surface to UserPromptSubmit hooks. */ function isUserStringMessage(value: unknown): value is { role: 'user'; @@ -363,29 +382,93 @@ function isUserStringMessage(value: unknown): value is { } /** - * Find the index of the last user-role, string-content message in an input - * array. Returns -1 when no such message exists. + * Type guard for an input message with a user role and an array `content` + * (e.g. `[{ type: 'input_text', text: '...' }, ...]`). + */ +function isUserStructuredMessage(value: unknown): value is { + role: 'user'; + content: unknown[]; +} { + if (typeof value !== 'object' || value === null) { + return false; + } + const obj = value as { + role?: unknown; + content?: unknown; + }; + return obj.role === 'user' && Array.isArray(obj.content); +} + +/** + * Find the index of the last user-role message (string or structured content + * array) in an input array. Returns -1 when no such message exists. */ -function findLatestUserStringIndex(arr: readonly unknown[]): number { +function findLatestUserMessageIndex(arr: readonly unknown[]): number { for (let i = arr.length - 1; i >= 0; i--) { - if (isUserStringMessage(arr[i])) { + if (isUserStringMessage(arr[i]) || isUserStructuredMessage(arr[i])) { return i; } } return -1; } +/** + * Extract the text content from a structured user message's content array. + * Multiple text blocks are joined with a newline so inspection hooks see all + * user-supplied text in the message. + */ +function extractTextFromContentArray(parts: readonly unknown[]): string { + const texts: string[] = []; + for (const part of parts) { + if (isUserTextContentPart(part)) { + texts.push(part.text); + } + } + return texts.join('\n'); +} + +/** + * Apply a mutated prompt string back into a structured user message's content + * array. Replaces the first text block with `mutated`, drops subsequent text + * blocks so unmutated text does not remain, and preserves non-text blocks + * (images, files, audio, video). When no text block existed, appends an + * `input_text` block carrying `mutated`. + */ +function applyMutatedToContentArray(parts: readonly unknown[], mutated: string): unknown[] { + let replaced = false; + const updated: unknown[] = []; + for (const part of parts) { + if (isUserTextContentPart(part)) { + if (!replaced) { + updated.push({ + ...part, + text: mutated, + }); + replaced = true; + } + } else { + updated.push(part); + } + } + if (!replaced) { + updated.push({ + type: 'input_text', + text: mutated, + }); + } + return updated; +} + /** * Extract a user-facing prompt string from an input (string or message array), * and return an applier that writes a mutated prompt back into the same shape. * - * For structured inputs we look at the LAST user message with a string - * content — this is the most common shape emitted by the SDK's own helpers - * (`normalizeInputToArray`) and matches what a handler would reasonably - * expect to mutate. + * For array inputs we look at the LAST user message, supporting both plain + * string `content` and structured content arrays (e.g. `input_text` blocks + * alongside multimodal parts). * - * Returns `{ prompt: undefined }` when no usable prompt can be extracted; the - * caller should skip the hook in that case. + * Returns `{ prompt: undefined }` when no user message is present; the caller + * should skip the hook in that case. */ function extractPromptAndApplier(input: models.InputsUnion): { prompt: string | undefined; @@ -399,7 +482,7 @@ function extractPromptAndApplier(input: models.InputsUnion): { } if (Array.isArray(input)) { - const targetIndex = findLatestUserStringIndex(input); + const targetIndex = findLatestUserMessageIndex(input); if (targetIndex === -1) { return { @@ -409,7 +492,12 @@ function extractPromptAndApplier(input: models.InputsUnion): { } const target = input[targetIndex]; - if (!isUserStringMessage(target)) { + let prompt: string | undefined; + if (isUserStringMessage(target)) { + prompt = target.content; + } else if (isUserStructuredMessage(target)) { + prompt = extractTextFromContentArray(target.content); + } else { return { prompt: undefined, applyMutated: (_mutated, original) => original ?? input, @@ -417,13 +505,13 @@ function extractPromptAndApplier(input: models.InputsUnion): { } return { - prompt: target.content, + prompt, applyMutated: (mutated, original) => { // Re-derive the target index from the effective base array so an // arbitrary `original` shape lands the mutation in the correct slot // rather than the closed-over index from the initial extraction. const base = Array.isArray(original) ? original : input; - const idx = findLatestUserStringIndex(base); + const idx = findLatestUserMessageIndex(base); if (idx === -1) { return base; } @@ -436,6 +524,11 @@ function extractPromptAndApplier(input: models.InputsUnion): { ...existing, content: mutated, }; + } else if (isUserStructuredMessage(existing)) { + out[idx] = { + ...existing, + content: applyMutatedToContentArray(existing.content, mutated), + } as models.InputsUnion1; } return out; }, @@ -1580,11 +1673,12 @@ export class ModelResult< // Emit PreToolUse here only when the approval gate has not already done // so (for example, an approved call resumed from older persisted state). if (this.hooksManager && !prepared && runPreToolUse) { - // The hook payload coerces null/undefined arguments to {} for schema - // validation, but `effectiveToolCall.arguments` only changes when the - // chain reports an actual mutation (`emit.mutated`), so tools that - // legitimately distinguish "no args" from "empty args" are unaffected. - const originalToolInput = (toolCall.arguments ?? {}) as Record; + // Parse through `inputSchema` so PreToolUse inspects the same defaulted, + // coerced, or transformed values that `executeTool` will receive. + // `effectiveToolCall.arguments` only changes when the chain reports an + // actual mutation (`emit.mutated`), preserving raw/null arguments on + // pass-through and letting `executeTool` re-parse mutated inputs. + const originalToolInput = this.resolveHookToolInput(tool, toolCall.arguments); const preResult = await this.hooksManager.emit( 'PreToolUse', { @@ -1650,12 +1744,13 @@ export class ModelResult< // that path stays uncovered and is documented on resumeToolResults. // Emit PostToolUse or PostToolUseFailure. if (this.hooksManager && result !== null && !isAsyncToolInvocation(result)) { + const postToolInput = this.resolveHookToolInput(tool, effectiveToolCall.arguments); if (result.error) { await this.hooksManager.emit( 'PostToolUseFailure', { toolName: effectiveToolCall.name, - toolInput: (effectiveToolCall.arguments ?? {}) as Record, + toolInput: postToolInput, error: result.error, }, this.hookEmitContext(effectiveToolCall.name), @@ -1665,7 +1760,7 @@ export class ModelResult< 'PostToolUse', { toolName: effectiveToolCall.name, - toolInput: (effectiveToolCall.arguments ?? {}) as Record, + toolInput: postToolInput, toolOutput: result.result, durationMs, }, @@ -2678,7 +2773,7 @@ export class ModelResult< 'PermissionRequest', { toolName: toolCall.name, - toolInput: (toolCall.arguments ?? {}) as Record, + toolInput: this.resolveHookToolInput(tool, toolCall.arguments), riskLevel, }, this.hookEmitContext(toolCall.name), @@ -2704,6 +2799,27 @@ export class ModelResult< }; } + /** + * Parse `rawArguments` through the client tool's `inputSchema` when + * available so lifecycle hooks (PreToolUse, PostToolUse, PostToolUseFailure, + * PermissionRequest) inspect the same defaulted/coerced/transformed values + * that `executeTool` will pass to `execute`. Falls back to the raw arguments + * (coerced to `{}` when null/undefined) if validation fails or returns a + * non-record, allowing PreToolUse hooks to inspect or repair invalid input. + */ + private resolveHookToolInput( + tool: Tool | undefined, + rawArguments: unknown, + ): Record { + if (tool && isClientTool(tool)) { + const parsed = z4.safeParse(tool.function.inputSchema, rawArguments); + if (parsed.success && isRecord(parsed.data)) { + return parsed.data; + } + } + return (rawArguments ?? {}) as Record; + } + private async prepareToolCallForApproval( toolCall: ParsedToolCall, ): Promise> { @@ -2711,11 +2827,14 @@ export class ModelResult< return toolCall; } + const tool = this.options.tools?.find( + (candidate) => isClientTool(candidate) && candidate.function.name === toolCall.name, + ); const preResult = await this.hooksManager.emit( 'PreToolUse', { toolName: toolCall.name, - toolInput: (toolCall.arguments ?? {}) as Record, + toolInput: this.resolveHookToolInput(tool, toolCall.arguments), }, this.hookEmitContext(toolCall.name), ); @@ -2821,11 +2940,14 @@ export class ModelResult< if (!this.hooksManager) { return; } + const tool = this.options.tools?.find( + (candidate) => isClientTool(candidate) && candidate.function.name === toolCall.name, + ); await this.hooksManager.emit( 'PostToolUseFailure', { toolName: toolCall.name, - toolInput: (toolCall.arguments ?? {}) as Record, + toolInput: this.resolveHookToolInput(tool, toolCall.arguments), error: new Error(reason), }, this.hookEmitContext(toolCall.name), diff --git a/packages/agent/tests/unit/model-result-hooks.test.ts b/packages/agent/tests/unit/model-result-hooks.test.ts index 751144b5..3ce66fa4 100644 --- a/packages/agent/tests/unit/model-result-hooks.test.ts +++ b/packages/agent/tests/unit/model-result-hooks.test.ts @@ -442,6 +442,241 @@ describe('ModelResult hooks integration', () => { }); }); + it('passes inputSchema-defaulted values to PreToolUse so deny hooks catch defaults', async () => { + const hooks = new HooksManager(); + const seenInputs: Record[] = []; + hooks.on('PreToolUse', { + handler: ({ toolInput }) => { + seenInputs.push(toolInput); + if (toolInput.dangerous === true) { + return { + block: 'dangerous default denied', + }; + } + return undefined; + }, + }); + + const execSpy = vi.fn(() => ({ + ok: true, + })); + const tool = { + type: ToolType.Function, + function: { + name: 'risky', + description: 'Tool with dangerous default', + inputSchema: z.object({ + dangerous: z.boolean().default(true), + }), + outputSchema: z.unknown(), + execute: async (args: unknown) => execSpy(args), + }, + } as unknown as Tool; + + const m = buildModelResult({ + tools: [ + tool, + ] as const, + hooks, + }); + + const result = await internal(m).runToolWithHooks( + tool, + { + id: 'call_default_deny', + name: 'risky', + arguments: {}, + }, + { + numberOfTurns: 1, + }, + ); + + expect(result.type).toBe('hook_blocked'); + expect(result.reason).toBe('dangerous default denied'); + expect(seenInputs).toEqual([ + { + dangerous: true, + }, + ]); + expect(execSpy).not.toHaveBeenCalled(); + }); + + it('passes inputSchema transforms to PreToolUse and PostToolUse and re-parses mutated input', async () => { + const hooks = new HooksManager(); + const preInputs: Record[] = []; + const postInputs: Record[] = []; + hooks.on('PreToolUse', { + handler: ({ toolInput }) => { + preInputs.push(toolInput); + return { + mutatedInput: { + path: ' /safe/file.txt ', + }, + }; + }, + }); + hooks.on('PostToolUse', { + handler: ({ toolInput }) => { + postInputs.push(toolInput); + }, + }); + + const execSpy = vi.fn((args: unknown) => ({ + received: args, + })); + const tool = { + type: ToolType.Function, + function: { + name: 'read_file', + description: 'Tool with transform and default', + inputSchema: z.object({ + path: z.string().transform((s) => s.trim()), + mode: z + .enum([ + 'ro', + 'rw', + ]) + .default('ro'), + }), + outputSchema: z.unknown(), + execute: async (args: unknown) => execSpy(args), + }, + } as unknown as Tool; + + const m = buildModelResult({ + tools: [ + tool, + ] as const, + hooks, + }); + + const result = await internal(m).runToolWithHooks( + tool, + { + id: 'call_transform', + name: 'read_file', + arguments: { + path: ' /initial.txt ', + }, + }, + { + numberOfTurns: 1, + }, + ); + + expect(result.type).toBe('execution'); + expect(preInputs).toEqual([ + { + path: '/initial.txt', + mode: 'ro', + }, + ]); + expect(execSpy).toHaveBeenCalledWith({ + path: '/safe/file.txt', + mode: 'ro', + }); + expect(postInputs).toEqual([ + { + path: '/safe/file.txt', + mode: 'ro', + }, + ]); + }); + + it('passes inputSchema-defaulted values to PreToolUse and PermissionRequest on approval-gate paths', async () => { + const hooks = new HooksManager(); + const permInputs: Record[] = []; + const preInputs: Record[] = []; + + hooks.on('PermissionRequest', { + handler: ({ toolInput }) => { + permInputs.push(toolInput); + return { + decision: 'allow' as const, + }; + }, + }); + hooks.on('PreToolUse', { + handler: ({ toolInput }) => { + preInputs.push(toolInput); + if (toolInput.dangerous === true) { + return { + block: 'blocked on approval gate', + }; + } + return undefined; + }, + }); + + const execSpy = vi.fn(() => ({ + ran: true, + })); + const tool = { + type: ToolType.Function, + function: { + name: 'gated_default', + description: 'Approval tool with dangerous default', + inputSchema: z.object({ + dangerous: z.boolean().default(true), + }), + outputSchema: z.unknown(), + execute: async (args: unknown) => execSpy(args), + requireApproval: true, + }, + } as unknown as Tool; + + const stateAccessor = makeStateAccessor({ + id: 'conv_gated_default', + messages: [], + status: 'in_progress', + createdAt: 0, + updatedAt: 0, + }); + const m = buildModelResult({ + tools: [ + tool, + ] as const, + hooks, + state: stateAccessor, + }); + const ent = internal(m); + ent.currentState = await stateAccessor.load(); + ent.stateAccessor = stateAccessor; + + const toolCall = { + id: 'c_gated_default', + name: 'gated_default', + arguments: {}, + } as ParsedToolCall; + + await ent.handleApprovalCheck( + [ + toolCall, + ], + 0, + makeResponse(), + ); + + expect(permInputs).toEqual([ + { + dangerous: true, + }, + ]); + expect(preInputs).toEqual([ + { + dangerous: true, + }, + ]); + + const runOutcome = await internal(m).runToolWithHooks(tool, toolCall, { + numberOfTurns: 1, + }); + expect(runOutcome.type).toBe('hook_blocked'); + expect(runOutcome.reason).toBe('blocked on approval gate'); + expect(execSpy).not.toHaveBeenCalled(); + }); + it('threads each run session id per emit when two runs share one HooksManager', async () => { // Devin finding: the manager-level setSessionId default is a single // mutable field, so two concurrent runs sharing one manager would @@ -834,6 +1069,239 @@ describe('ModelResult hooks integration', () => { await expect(ent.maybeRunUserPromptSubmit('hello')).rejects.toThrow('no good'); }); + + it('fires and rejects for structured content-array user messages', async () => { + const hooks = new HooksManager(); + const seen: string[] = []; + hooks.on('UserPromptSubmit', { + handler: ({ prompt }) => { + seen.push(prompt); + if (prompt.includes('forbidden')) { + return { + reject: 'blocked structured prompt', + }; + } + return undefined; + }, + }); + + const m = buildModelResult({ + hooks, + }); + const ent = internal(m); + ent.currentState = { + id: 'conv_struct_reject', + messages: [], + status: 'in_progress', + createdAt: 0, + updatedAt: 0, + } as ConversationState; + + const structured = [ + { + role: 'user', + content: [ + { + type: 'input_text', + text: 'this contains forbidden content', + }, + ], + }, + ]; + + await expect(ent.maybeRunUserPromptSubmit(structured)).rejects.toThrow( + 'blocked structured prompt', + ); + expect(seen).toEqual([ + 'this contains forbidden content', + ]); + }); + + it('targets the latest structured user message instead of an earlier string user message', async () => { + const hooks = new HooksManager(); + const seen: string[] = []; + hooks.on('UserPromptSubmit', { + handler: ({ prompt }) => { + seen.push(prompt); + if (prompt.includes('malicious')) { + return { + reject: 'caught latest structured message', + }; + } + return undefined; + }, + }); + + const m = buildModelResult({ + hooks, + }); + const ent = internal(m); + ent.currentState = { + id: 'conv_struct_latest', + messages: [], + status: 'in_progress', + createdAt: 0, + updatedAt: 0, + } as ConversationState; + + const mixedHistory = [ + { + role: 'user', + content: 'benign earlier turn', + }, + { + role: 'assistant', + content: 'ok', + }, + { + role: 'user', + content: [ + { + type: 'input_text', + text: 'malicious follow-up', + }, + ], + }, + ]; + + await expect(ent.maybeRunUserPromptSubmit(mixedHistory)).rejects.toThrow( + 'caught latest structured message', + ); + expect(seen).toEqual([ + 'malicious follow-up', + ]); + }); + + it('mutates structured content-array user messages while preserving non-text blocks and dropping extra text blocks', async () => { + const hooks = new HooksManager(); + const seen: string[] = []; + hooks.on('UserPromptSubmit', { + handler: ({ prompt }) => { + seen.push(prompt); + return { + mutatedPrompt: prompt.replace(/SECRET/g, '[REDACTED]'), + }; + }, + }); + + const m = buildModelResult({ + hooks, + }); + const ent = internal(m); + ent.currentState = { + id: 'conv_struct_mutate', + messages: [], + status: 'in_progress', + createdAt: 0, + updatedAt: 0, + } as ConversationState; + + const imageBlock = { + type: 'input_image', + detail: 'auto', + imageUrl: 'https://example.com/photo.png', + }; + const original = [ + { + role: 'user', + content: [ + { + type: 'input_text', + text: 'first SECRET', + promptCacheBreakpoint: { + type: 'ephemeral', + }, + }, + imageBlock, + { + type: 'input_text', + text: 'second SECRET', + }, + ], + }, + ]; + + const outcome = await ent.maybeRunUserPromptSubmit(original); + expect(seen).toEqual([ + 'first SECRET\nsecond SECRET', + ]); + expect(outcome).toBeDefined(); + const applied = outcome?.applyTo(original) as Array<{ + role: string; + content: unknown[]; + }>; + expect(applied).toEqual([ + { + role: 'user', + content: [ + { + type: 'input_text', + text: 'first [REDACTED]\nsecond [REDACTED]', + promptCacheBreakpoint: { + type: 'ephemeral', + }, + }, + imageBlock, + ], + }, + ]); + }); + + it('fires for non-text-only structured user messages and appends input_text on mutation', async () => { + const hooks = new HooksManager(); + const seen: string[] = []; + hooks.on('UserPromptSubmit', { + handler: ({ prompt }) => { + seen.push(prompt); + return { + mutatedPrompt: 'added policy context', + }; + }, + }); + + const m = buildModelResult({ + hooks, + }); + const ent = internal(m); + ent.currentState = { + id: 'conv_struct_image_only', + messages: [], + status: 'in_progress', + createdAt: 0, + updatedAt: 0, + } as ConversationState; + + const imageBlock = { + type: 'input_image', + detail: 'auto', + imageUrl: 'https://example.com/only-image.png', + }; + const original = [ + { + role: 'user', + content: [ + imageBlock, + ], + }, + ]; + + const outcome = await ent.maybeRunUserPromptSubmit(original); + expect(seen).toEqual([ + '', + ]); + expect(outcome?.applyTo(original)).toEqual([ + { + role: 'user', + content: [ + imageBlock, + { + type: 'input_text', + text: 'added policy context', + }, + ], + }, + ]); + }); }); describe('Stop hook', () => {