Learning resourcesReviewed · OpenRouter

OpenRouter Agent SDK: Lifecycle Hooks for callModel

This is OpenRouter's documentation page on lifecycle hooks in the TypeScript @openrouter/agent SDK, written for developers who build tool-calling agents with callModel; the catch is that it is an API reference with no version, pricing, licence or run results, and by default a hook that throws is logged and skipped rather than stopping the run. It documents nine built-in hooks (SessionStart, UserPromptSubmit, PostModelCall, PermissionRequest, PreToolUse, PostToolUse, PostToolUseFailure, Stop, SessionEnd), the HooksManager class, tool matchers and filters, asynchronous and detached handlers, and custom Zod-typed hooks.

Researched 13 Nov 2026

In short.

This is OpenRouter's documentation page on lifecycle hooks in the TypeScript @openrouter/agent SDK, written for developers who build tool-calling agents with callModel; its main catch is that it is an API reference only, with no version, pricing, licence or run results, and by default a hook that throws is logged and skipped rather than stopping the run. The page describes nine built-in hooks that let application code watch or steer the agent loop: observe sessions and model calls, rewrite or reject the user prompt, allow or deny approval-gated tools, rewrite or block tool calls, record tool outcomes, and override a stop condition. It also covers the HooksManager class, tool-name matchers and payload filters, sequential handler chains with mutation piping, detached async work with timeouts, and custom hooks with Zod schemas. Nothing was run for this report; every statement comes from the page text.

Researched and written by an AI model and checked by a second AI model. How it works

This report covers only the single documentation page at [https://openrouter.ai/docs/agent-sdk/call-model/lifecycle-hooks.md], captured in full on 13 November 2026. Pages it links to (Tools, Tool Approval and State, Stop Conditions, API Reference and the docs index) were not read, so statements about them are limited to their titles on this page. No package, repository, licence file, changelog or pricing page was part of the evidence. Nothing was installed or executed, so no behaviour was tested; all behaviour described is the vendor's own documentation.

The overview

What this resource is

This is one documentation page titled Lifecycle Hooks, subtitled Observe and control the agent loop with typed lifecycle hooks. It sits in the OpenRouter docs under the Agent SDK, in the call-model section, at [https://openrouter.ai/docs/agent-sdk/call-model/lifecycle-hooks.md]. It documents a feature of the @openrouter/agent package, where the OpenRouter client exposes callModel, the agent loop that sends a request, runs tools and sends follow-up requests.

The page is a feature guide and reference, not a software package. The code it describes is imported from @openrouter/agent, and HooksManager is also available from the focused subpath @openrouter/agent/hooks-manager. The page does not name an author beyond OpenRouter, give a package version, or give a publication or revision date.

Overall assessment

As a reference, the page is specific and well organised. For each hook it gives the firing point, the payload type, the result type where one exists, and edge cases such as when a hook does not fire, how multiple handlers combine, and what happens at the override limit. A developer could build guardrails and tracing from it without guessing the main contracts.

It is not a gentle introduction. It assumes you already know callModel, tool definitions with Zod schemas, approval-gated tools and stopWhen conditions, which are covered on other OpenRouter pages that this report did not read. Its code samples call undefined helpers such as runInSandbox, recordToolLatency, audit and containsSecret, so they show the shape of the API rather than runnable programs. No benchmark, test result or measured overhead appears, so claims about behaviour are the vendor's description, not independently confirmed.

Who it is for

The audience is TypeScript or JavaScript developers building agents on OpenRouter who need control points around the loop. The page lists the uses itself: inspect, modify or block tool calls; record tool successes and failures; rewrite or reject user prompts; decide whether approval-gated tools run; override stop conditions; track sessions, model calls, token usage, latency and cost; and run custom type-safe application events.

Typical readers would be teams adding audit logs, policy checks, cost and latency tracing, or human-approval rules to an agent. Beginners to agent loops can learn the vocabulary from the nine hook names and the table of when each fires, but they will probably need the linked Tools and Tool Approval and State pages first. People not using the @openrouter/agent SDK get little from it, because the page does not describe other clients or languages.

What the hooks can do

Nine built-in hooks are documented. SessionStart fires before the first request and is observe-only; its config currently carries three booleans: hasTools, hasApproval and hasState. UserPromptSubmit can replace the prompt with mutatedPrompt or reject it with reject set to true or a reason string. PostModelCall fires for each completed model response and reports responseId (the OpenRouter generation ID), model, durationMs, turnType (initial, resume, tool_round, final or retry), turnNumber and optional usage with input, output, total, cached and reasoning tokens plus an optional usage.cost.

PermissionRequest fires before an approval pause and returns allow, deny or ask_user with an optional reason; it also gives the handler a riskLevel of low, medium or high. PreToolUse can replace arguments with mutatedInput or stop execution with block. PostToolUse reports toolOutput and durationMs. PostToolUseFailure reports the error. Stop fires when a stopWhen condition halts the loop, and a handler can return appendPrompt and forceResume. SessionEnd reports a reason of user, error, max_turns or complete. Its totalUsage field, including the modelCalls count, is present only when at least one model response completed; token fields are summed across calls, and totalUsage.cost is included when at least one response reported cost, so complete cost coverage is not guaranteed.

Around the hooks, the page documents matchers (an exact string, a RegExp or a predicate on tool name) and a filter function over the payload. Handlers can be async, or can return an AsyncOutput signal to detach telemetry work. Custom hooks can be declared with Zod payload and result schemas and fired with emit().

Using it

What you need to use it

The examples need the @openrouter/agent package, an OpenRouter API key passed to the OpenRouter constructor (the samples read process.env.OPENROUTER_API_KEY), and Zod, imported from zod/v4, for tool schemas and custom hook schemas. The code is TypeScript with ES module imports.

The page does not state a minimum Node.js version, the package version that introduced hooks, supported runtimes such as browsers or edge workers, or how to install the package. Those are unknown from this evidence. The examples also use the model identifier openai/gpt-5.4, so you need access to a model through OpenRouter, but the page does not say which models work best with hooks.

How it works

There are two ways to attach hooks. Inline, you pass a hooks object to callModel with arrays of entries per hook name, each with a handler and optional matcher. Alternatively, you create a HooksManager, register handlers with hooks.on(name, entry), which returns an unsubscribe function, and pass the manager as the hooks option. The manager is needed for custom hooks, dynamic registration, programmatic emission or explicit lifecycle control. One manager can be shared by concurrent callModel runs because the SDK supplies each run's sessionId in the handler context along with an AbortSignal and the hook name.

Handlers for an event run one after another in registration order. For each handler the SDK checks the matcher and filter, calls it with the latest payload, then pipes any mutation into later handlers. A block or rejection ends the chain, although the blocking handler's own mutation is still applied. Empty strings do not block or reject. For PermissionRequest the last returned decision wins. For Stop, appendPrompt strings from several handlers are joined with newlines and any forceResume of true continues the loop, limited to three consecutive overrides without progress. A tool output, a fresh model response, or a blocked or denied tool result resets that counter.

The page lists several cases where hooks do not fire. If the model supplies invalid JSON tool arguments, no tool hooks fire. PostToolUseFailure does not fire if the tool never ran (a PermissionRequest denial, user rejection, a PreToolUse block, invalid JSON, or an HITL tool pausing). A stream that fails before a complete response emits no PostModelCall. On a no-tools streaming path, PostModelCall fires at teardown just before SessionEnd. Approval and HITL resume calls skip SessionStart and SessionEnd but still fire tool hooks.

Handler errors are, by default, logged and skipped. Passing throwOnHandlerError: true to the HooksManager constructor propagates them, which the page suggests for tests. Returning { async: true, work, asyncTimeout } detaches work with a default 30 second timeout, after which the context signal is aborted. hooks.abortInflight() and await hooks.drain() are provided for shutdown, and the agent loop also drains pending work when a run ends.

Setup

The page gives no installation steps. Its setup is code only: create an OpenRouter client with an API key, define tools with the tool() helper and Zod input and output schemas, and call openrouter.callModel with model, input, tools and hooks. Pass tools with as const as the samples do.

The simplest start is the inline hooks option with one or two entries, as in the quick start. Move to a HooksManager when you need custom hooks, unsubscribe control or direct emit() calls. If you emit directly from a manager shared by overlapping operations, the page advises passing a per-emit sessionId, because setSessionId() sets a last-writer-wins default. Package installation commands, lockfile advice and framework integration are not covered, so unknown.

Worked example from the page

The quick start defines a run_shell tool that executes a command in a sandbox, then calls callModel with the input Delete temporary build files. A PreToolUse entry matched to run_shell inspects toolInput.command and, if the text contains rm -rf /, returns a block with the reason Refusing to run a destructive command, which is sent to the model instead of running the tool. A PostToolUse entry records the tool name and durationMs for latency tracking. Finally the program prints await result.getText().

A second example uses a HooksManager with a PreToolUse matcher of /^db_/, a filter that requires non-empty input, an audit call using context.sessionId, and a mutatedInput that adds dryRun: true to every matching database tool call. Another registers a PermissionRequest handler for read_file that allows paths inside the workspace and otherwise denies with a reason. These are the page's illustrations; this report did not run them.

A plain substring check such as the rm -rf / test is a demonstration, not a robust safety control, since many equivalent destructive commands would not match it. That is an assessment drawn from reading the sample, not a statement on the page, which does not claim otherwise.

Assessment & evidence

Limitations and risks

Handler failures fail open by default. A throwing handler, matcher or filter is logged and skipped, and payload or result schema failures follow the same policy. If a PreToolUse or PermissionRequest handler is meant to enforce a safety rule and it throws, the page says the error is logged and the handler skipped, so the failed handler's restriction is skipped; other handlers, approval requirements or validation may still prevent execution. Enforcement hooks should therefore be written not to throw unexpectedly, or you should use throwOnHandlerError: true, which the page presents mainly as a testing aid.

Hooks do not cover every event. PreToolUse is documented for client tool execution, invalid JSON arguments bypass the tool hooks, and PostToolUseFailure misses tools that never ran. PermissionRequest results are last-decision-wins, so registration order matters. The Stop payload currently has only the reason max_turns. An approval pause is currently reported to SessionEnd as complete. The page uses the word currently for these, which suggests they may change.

The page does not document performance overhead, behaviour of hooks across SDK versions, error messages, or testing patterns beyond strict mode. Custom hooks do not inherit built-in mutation or blocking behaviour, and inline configuration supports only built-in hooks. Nothing here was run, so every behaviour is as described by the vendor and unverified.

Why this assessment

The assessment rests on what the page itself states: typed payload and result definitions, a table of when each hook fires and whether it observes or controls, explicit lists of cases where hooks are skipped, and API signatures for HooksManager. These are the details a developer needs to decide whether the feature covers a given guardrail or tracing need, so the page is judged useful for that purpose.

The catches come from reading the specified behaviours together rather than from any tests. Skip-on-error handling combined with enforcement hooks is a risk because the page says both. Samples that depend on undefined helper functions are a limit on how directly they can be copied. Missing version, licence and price information is a gap in the evidence, not a finding that those things are absent from the product.

Alternatives and related options

The page names one distinction itself: lifecycle hooks are different from transport hooks such as SDKHooks and BeforeRequestHook, which intercept HTTP requests rather than events inside the agent loop. If you need to alter or log raw requests, those are the documented alternative, though this page does not describe them.

The page also points to related OpenRouter pages on Tools, Tool Approval and State, Stop Conditions and the API Reference. Approval-gated tools and stopWhen conditions are separate mechanisms that hooks can complement, for example PermissionRequest sits on top of the approval flow. The page does not compare hooks with putting checks inside each tool's execute function or wrapping callModel in your own code, nor with other agent frameworks, so any such comparison is outside this evidence.

Evidence used

The sole source is the full text of the Lifecycle Hooks page, captured as a single file of 19,996 bytes. It includes the intro, the quick start, the HooksManager section, all nine built-in hooks, their payload types, applicable result types, and selected examples, the matcher and filter section, handler chain rules, async handling, custom hooks, the HooksManager API listing and a next-steps list of links.

The evidence is documentation prose and code snippets only. It contains no repository, package metadata, changelog, licence file, issue tracker, benchmark or execution output. The statements in this report are limited to what that text says.

Access & freshness

Costs

The page states no price for the SDK, for hooks, or for any model. The cost of using it is therefore unknown from this evidence. The examples call callModel with an OpenRouter API key, but the page does not describe billing arrangements, rates, free tiers or limits, so these remain unknown from this page.

The page does show how to observe cost. PostModelCall.usage.cost is present only when server-side usage accounting reports cost, and usage is omitted entirely when the server does not report usage. SessionEnd.totalUsage, including its modelCalls count, is present only when at least one model response completed, and SessionEnd.totalUsage.cost is included when at least one response reported cost, so complete cost coverage is not guaranteed. Custom hook handlers, such as telemetry calls or policy lookups, run in your own application and may add latency or costs; the page quantifies neither. Detached async work defaults to a 30 second timeout.

Rights and licence

The page contains no licence text, copyright notice or terms of reuse. Whether the @openrouter/agent package is open source, which licence it carries, and whether the documentation and code samples may be copied or redistributed are all unknown from this evidence. Check the package's own published licence and OpenRouter's terms before copying samples into a product or redistributing the text.

Reading the page, linking to it and following its described patterns in your own code are ordinary uses, but this report cannot confirm any reuse rights.

Freshness

The page was captured on 13 November 2026. It shows no publication date, last-updated date, SDK version or changelog, so how current it is relative to the published package is unknown. Examples use the model identifier openai/gpt-5.4, which reflects the docs at capture time and may age.

Wording such as the agent loop currently emits this config, and an approval pause currently ends with reason complete, signals behaviour that could change in later releases. Before relying on specific payload fields or limits, such as the three-override cap on forceResume or the 30 second async default, compare them with the SDK version you install.

What to do next

If you use @openrouter/agent, start with read-only hooks: PostModelCall for tracing model calls, tokens, latency and cost, and PostToolUse and PostToolUseFailure for tool outcomes. Then add control hooks such as PreToolUse and PermissionRequest once you have a test that proves they fire as expected, using throwOnHandlerError: true in tests. Do not rely on a simple string match as your only protection for destructive tools; keep tools sandboxed and scoped to what they need.

Before adopting it in a product, confirm the installed package version, the package licence, the pricing and billing terms that apply to the models you plan to call, and any behaviour the page labels as current. Read the linked Tools, Tool Approval and State, and Stop Conditions pages for the parts this page assumes. Treat the samples as illustrations, since the helper functions they call are not defined here.

Evidence for this report

selected-page.txtselected · checked 2026-11-13