Skip to content
Merged
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/lifecycle-hook-input-enforcement.md
Original file line number Diff line number Diff line change
@@ -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`.
172 changes: 147 additions & 25 deletions packages/agent/src/lib/model-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand All @@ -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 {
Expand All @@ -409,21 +492,26 @@ 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,
};
}

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;
}
Expand All @@ -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;
},
Expand Down Expand Up @@ -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<string, unknown>;
// 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',
{
Expand Down Expand Up @@ -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<string, unknown>,
toolInput: postToolInput,
error: result.error,
},
this.hookEmitContext(effectiveToolCall.name),
Expand All @@ -1665,7 +1760,7 @@ export class ModelResult<
'PostToolUse',
{
toolName: effectiveToolCall.name,
toolInput: (effectiveToolCall.arguments ?? {}) as Record<string, unknown>,
toolInput: postToolInput,
toolOutput: result.result,
durationMs,
},
Expand Down Expand Up @@ -2678,7 +2773,7 @@ export class ModelResult<
'PermissionRequest',
{
toolName: toolCall.name,
toolInput: (toolCall.arguments ?? {}) as Record<string, unknown>,
toolInput: this.resolveHookToolInput(tool, toolCall.arguments),
riskLevel,
},
this.hookEmitContext(toolCall.name),
Expand All @@ -2704,18 +2799,42 @@ 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<string, unknown> {
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<string, unknown>;
}

private async prepareToolCallForApproval(
toolCall: ParsedToolCall<Tool>,
): Promise<ParsedToolCall<Tool>> {
if (!this.hooksManager || typeof toolCall.arguments === 'string') {
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<string, unknown>,
toolInput: this.resolveHookToolInput(tool, toolCall.arguments),
},
this.hookEmitContext(toolCall.name),
);
Expand Down Expand Up @@ -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<string, unknown>,
toolInput: this.resolveHookToolInput(tool, toolCall.arguments),
error: new Error(reason),
},
this.hookEmitContext(toolCall.name),
Expand Down
Loading
Loading