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/blocking-hooks-fail-closed-on-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@openrouter/agent": patch
---

Fail closed when a blocking hook fails. Outside strict mode, a `PreToolUse` or `UserPromptSubmit` emit used to report `blocked: false` when its payload failed validation, and a throwing handler, matcher or filter (or a handler returning an invalid result) was logged and skipped, so a crashing deny guard let the tool run. These cases now stop the chain and return `blocked: true` with a new `blockReason` field; the tool gets the usual blocked output and does not run. Non-blocking hooks keep logging and continuing, and `throwOnHandlerError: true` still re-throws.
9 changes: 9 additions & 0 deletions packages/agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,15 @@ Handlers for a hook run sequentially in registration order.
continues. Construct the manager with
`new HooksManager(custom, { throwOnHandlerError: true })` to propagate
errors instead (useful in tests).
- **Blocking hooks fail closed**: `PreToolUse` and `UserPromptSubmit` don't
skip failures, because the failing handler may be the guard that would
have blocked. If the payload fails validation, a handler, matcher or
filter throws, a handler returns an invalid result, or the chain is
aborted before every handler ran, the emit returns `blocked: true` with a
`blockReason` (the error itself is only logged). A blocked `PreToolUse`
gives the model the usual blocked tool output with that reason and the
tool does not run; a blocked `UserPromptSubmit` rejects the call. Other
hooks keep the log-and-continue policy above.

**Async fire-and-forget handlers**

Expand Down
178 changes: 130 additions & 48 deletions packages/agent/src/lib/hooks-emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ function isPlainMutableObject(value: unknown): value is Record<string, unknown>
* `abortInflight()` has a deterministic effect on the chain itself (not just
* on handlers that happen to consult the signal). For hooks with a block
* field, bailing out before every handler ran reports `blocked: true`.
* - Fail closed for blocking hooks: for a hook with a block field
* (PreToolUse, UserPromptSubmit), a throwing handler, matcher or filter,
* or a handler result that fails `options.resultSchema`, stops the chain
* with `blocked: true` and a `blockReason` instead of being logged and
* skipped, because the failing handler may be the guard that would have
* blocked. Other hooks keep log-and-continue. Strict mode
* (`throwOnHandlerError`) still re-throws.
*
* Payload isolation: the initial payload is shallow-cloned before entering the
* chain so mutation piping (via {@link HOOK_BEHAVIOR}) doesn't mutate the
Expand Down Expand Up @@ -98,12 +105,14 @@ export async function executeHandlerChain<P, R>(
} as P)
: initialPayload;
let blocked = false;
let blockReason: string | undefined;
let mutated = false;

// Per-hook mutation/block behavior. Hooks absent from the table (all
// observation-only hooks and every custom hook) collect results without
// altering the payload or short-circuiting.
const behavior = (HOOK_BEHAVIOR as Partial<Record<string, HookBehavior>>)[options.hookName];
const failsClosed = behavior?.blockField !== undefined;

for (let i = 0; i < entries.length; i++) {
// Cooperative abort: bail out of the chain when abortInflight() has fired.
Expand All @@ -113,8 +122,9 @@ export async function executeHandlerChain<P, R>(
// A hook that can block (PreToolUse, UserPromptSubmit) fails closed:
// the handlers left unrun may include the guard that would have
// blocked, so an aborted chain must not read as an approval.
if (behavior?.blockField) {
if (failsClosed) {
blocked = true;
blockReason = `Blocked: ${options.hookName} hook chain was aborted before every handler ran`;
}
break;
}
Expand All @@ -124,52 +134,39 @@ export async function executeHandlerChain<P, R>(
continue;
}

// Matcher and filter checks run under the same error policy as handlers:
// in non-strict mode a throwing user-supplied matcher function or filter
// is logged and the entry skipped, instead of crashing the whole chain.
const gate = evaluateEntryGate(entry, currentPayload, i, options);
if (gate === 'skip') {
continue;
const outcome = await runEntry<P, R>(entry, currentPayload, context, i, options, failsClosed);
if (outcome.kind === 'failed') {
blocked = true;
blockReason = outcome.reason;
break;
}

try {
const returnValue = await entry.handler(currentPayload, context);
const outcome = classifyHandlerReturn<R>(returnValue, i, options);

if (outcome.kind === 'async') {
// Fire-and-forget: track the (optional) work promise for drain/timeout.
if (outcome.trackedWork !== undefined) {
pending.push(outcome.trackedWork);
}
continue;
}
if (outcome.kind === 'skip') {
// Void return, or result-schema validation failed in non-strict mode.
continue;
if (outcome.kind === 'async') {
// Fire-and-forget: track the (optional) work promise for drain/timeout.
if (outcome.trackedWork !== undefined) {
pending.push(outcome.trackedWork);
}
continue;
}
if (outcome.kind === 'skip') {
// Matcher/filter rejected the entry, void return, or a failure of a
// non-blocking hook in non-strict mode.
continue;
}

const result = outcome.result;
results.push(result);
const result = outcome.result;
results.push(result);

// Apply mutation piping -- only hooks with declared mutations participate.
if (behavior?.mutations) {
const applied = applyMutations(currentPayload, result, behavior.mutations);
if (applied !== currentPayload) {
currentPayload = applied;
mutated = true;
}
}
// Apply mutation piping -- only hooks with declared mutations participate.
const applied = applyMutations(currentPayload, result, behavior?.mutations);
if (applied !== currentPayload) {
currentPayload = applied;
mutated = true;
}

// Short-circuit on the hook's declared block field.
if (behavior?.blockField && isBlockTriggered(result, behavior.blockField)) {
blocked = true;
break;
}
} catch (error) {
if (options.throwOnHandlerError) {
throw error;
}
console.warn(`[HooksManager] Handler ${i} for hook "${options.hookName}" threw:`, error);
// Short-circuit on the hook's declared block field.
if (behavior?.blockField && isBlockTriggered(result, behavior.blockField)) {
blocked = true;
break;
}
}

Expand All @@ -178,6 +175,9 @@ export async function executeHandlerChain<P, R>(
pending,
finalPayload: currentPayload,
blocked,
...(blockReason !== undefined && {
blockReason,
}),
mutated,
};
}
Expand All @@ -188,14 +188,16 @@ export async function executeHandlerChain<P, R>(
* Matchers fail closed: if a matcher is registered and no toolName is
* available for this emit, the handler is skipped rather than invoked
* globally. A throwing matcher function or filter is re-thrown in strict
* mode, or logged and treated as a skip otherwise.
* mode; otherwise it is logged and treated as a skip, or as `fail` for a
* blocking hook so the chain fails closed.
*/
function evaluateEntryGate<P, R>(
entry: HookEntry<P, R>,
payload: P,
index: number,
options: ExecuteChainOptions,
): 'run' | 'skip' {
failsClosed: boolean,
): 'run' | 'skip' | 'fail' {
try {
// Matcher first; the filter must not run when the matcher already
// rejected the entry (filters can be effectful or expensive).
Expand All @@ -211,10 +213,86 @@ function evaluateEntryGate<P, R>(
throw error;
}
console.warn(
`[HooksManager] Matcher/filter for handler ${index} of hook "${options.hookName}" threw:`,
`[HooksManager] Matcher/filter for handler ${index} of hook "${options.hookName}" threw${failsClosed ? '; failing closed' : ''}:`,
error,
);
return 'skip';
return failsClosed ? 'fail' : 'skip';
}
}

type EntryOutcome<R> =
| HandlerReturnOutcome<R>
| {
kind: 'failed';
reason: string;
};

/**
* Evaluate an entry's matcher/filter and, when it passes, run its handler.
* Matcher and filter checks run under the same error policy as handlers:
* in non-strict mode a throwing user-supplied matcher function or filter is
* logged and the entry skipped (or, for blocking hooks, reported as `failed`
* so the chain fails closed), instead of crashing the whole chain.
*/
async function runEntry<P, R>(
entry: HookEntry<P, R>,
payload: P,
context: LifecycleHookContext,
index: number,
options: ExecuteChainOptions,
failsClosed: boolean,
): Promise<EntryOutcome<R>> {
const gate = evaluateEntryGate(entry, payload, index, options, failsClosed);
if (gate === 'skip') {
return {
kind: 'skip',
};
}
if (gate === 'fail') {
return {
kind: 'failed',
reason: `Blocked: ${options.hookName} hook matcher/filter for handler ${index} threw`,
};
}
return runHandler<P, R>(entry, payload, context, index, options, failsClosed);
}

/**
* Run one handler and classify its return value under the chain's error
* policy. A throw or an invalid result is re-thrown in strict mode; otherwise
* it is logged and reported as `failed` for blocking hooks (so the chain
* fails closed) or `skip` for every other hook.
*/
async function runHandler<P, R>(
entry: HookEntry<P, R>,
payload: P,
context: LifecycleHookContext,
index: number,
options: ExecuteChainOptions,
failsClosed: boolean,
): Promise<EntryOutcome<R>> {
try {
const returnValue = await entry.handler(payload, context);
return classifyHandlerReturn<R>(returnValue, index, {
...options,
throwOnHandlerError: options.throwOnHandlerError || failsClosed,
});
} catch (error) {
if (options.throwOnHandlerError) {
throw error;
}
console.warn(
`[HooksManager] Handler ${index} for hook "${options.hookName}" failed${failsClosed ? '; failing closed' : ''}:`,
error,
);
return failsClosed
? {
kind: 'failed',
reason: `Blocked: ${options.hookName} hook handler ${index} failed`,
}
: {
kind: 'skip',
};
}
}

Expand Down Expand Up @@ -366,8 +444,12 @@ function isUnrefable(handle: unknown): handle is {
/**
* Apply mutation fields from a result onto the current payload.
*/
function applyMutations<P, R>(payload: P, result: R, mutationMap: Record<string, string>): P {
if (typeof result !== 'object' || result === null) {
function applyMutations<P, R>(
payload: P,
result: R,
mutationMap: Record<string, string> | undefined,
): P {
if (mutationMap === undefined || typeof result !== 'object' || result === null) {
return payload;
}

Expand Down
12 changes: 11 additions & 1 deletion packages/agent/src/lib/hooks-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import { BUILT_IN_HOOK_NAMES, BUILT_IN_HOOKS } from './hooks-schemas.js';
import type {
BuiltInHookDefinitions,
EmitResult,
HookBehavior,
HookDefinition,
HookEntry,
HookHandler,
HookRegistry,
HooksManagerOptions,
LifecycleHookContext,
} from './hooks-types.js';
import { HOOK_BEHAVIOR } from './hooks-types.js';

//#region Types

Expand Down Expand Up @@ -194,11 +196,19 @@ export class HooksManager<Custom extends HookRegistry = Record<string, never>> {
throw err;
}
console.warn(err.message);
// A blocking hook (PreToolUse, UserPromptSubmit) fails closed: its
// guards never ran, so the emit must not read as an approval.
const failsClosed =
(HOOK_BEHAVIOR as Partial<Record<string, HookBehavior>>)[hookName]?.blockField !==
undefined;
return {
results: [],
pending: [],
finalPayload: chainPayload,
blocked: false,
blocked: failsClosed,
...(failsClosed && {
blockReason: `Blocked: ${hookName} hook payload failed validation`,
}),
mutated: false,
};
}
Expand Down
14 changes: 11 additions & 3 deletions packages/agent/src/lib/hooks-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,19 @@ export interface EmitResult<R, P> {
/** The payload after all mutation piping has been applied. */
readonly finalPayload: P;
/**
* True if any handler triggered a block/reject short-circuit, or if the
* chain of a blocking hook (PreToolUse, UserPromptSubmit) was aborted
* before every handler ran.
* True if any handler triggered a block/reject short-circuit, or if a
* blocking hook (PreToolUse, UserPromptSubmit) failed closed: its chain
* was aborted before every handler ran, its payload failed validation, or
* (outside strict mode) a handler, matcher or filter threw or a handler
* returned an invalid result.
*/
readonly blocked: boolean;
/**
* Why a blocking hook failed closed. Set only in the fail-closed cases
* listed on `blocked`; a handler's own block/reject reason stays in
* `results`. Error details are logged, not included here.
*/
readonly blockReason?: string;
/**
* True if any handler's result actually piped a mutation into the payload
* (e.g. PreToolUse `mutatedInput`, UserPromptSubmit `mutatedPrompt`).
Expand Down
12 changes: 9 additions & 3 deletions packages/agent/src/lib/model-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1598,7 +1598,10 @@ export class ModelResult<
// Every entry in `results` passed the PreToolUseResult schema (see
// EmitResult.results invariant), so no structural re-narrowing needed.
const block = preResult.results.find((r) => r.block)?.block;
const reason = typeof block === 'string' ? block : 'Blocked by PreToolUse hook';
const reason =
typeof block === 'string'
? block
: (preResult.blockReason ?? 'Blocked by PreToolUse hook');
return {
type: 'hook_blocked',
toolCall,
Expand Down Expand Up @@ -2722,7 +2725,8 @@ export class ModelResult<

if (preResult.blocked) {
const block = preResult.results.find((result) => result.block)?.block;
const reason = typeof block === 'string' ? block : 'Blocked by PreToolUse hook';
const reason =
typeof block === 'string' ? block : (preResult.blockReason ?? 'Blocked by PreToolUse hook');
this.preparedToolCalls.set(toolCall.id, {
type: 'blocked',
reason,
Expand Down Expand Up @@ -2950,7 +2954,9 @@ export class ModelResult<
if (emit.blocked) {
// Every entry in `results` passed the UserPromptSubmitResult schema.
const reject = emit.results.find((r) => r.reject)?.reject;
throw new Error(typeof reject === 'string' ? reject : 'Prompt rejected by hook');
throw new Error(
typeof reject === 'string' ? reject : (emit.blockReason ?? 'Prompt rejected by hook'),
);
}

if (!emit.mutated) {
Expand Down
Loading
Loading