Hooks
Hooks inspect or modify messages and tool calls at supported boundaries in the root chat loop. Use them for input checks, output redaction, and approval rules on model-selected calls.
Hooks are not applied inside delegated subagent loops, nested composite calls, or direct tool evals. Enforce rules that must cover those paths in the tool implementation or downstream API.
Folder shape
Hooks live at the repo root under hooks/, one folder per hook:
hooks/
└── ready-to-quote-guard/
├── hook.json ← declarative manifest (binding, capabilities, config)
└── index.mjs ← decision module (exports createHook)The manifest is authoritative for what the hook binds to and what it may do; the module only supplies the decision function. The runtime discovers every subfolder of hooks/ automatically; there is no registration list.
Ship the handler as .mjs. Unlike intents and tools, the hook loader imports the module directly (no esbuild step), so plain ESM JavaScript is the reliable format. (index.js and index.ts are probed too, but a .ts handler only works where the host process can already import TypeScript.)
hook.json
{
"name": "ready-to-quote-guard",
"points": ["preToolUse"],
"capabilities": ["reads_tool_io", "gates_tools"],
"failPolicy": "closed",
"priority": 10,
"config": {
"guardedTools": ["store__submissions__set"],
"blockedRecommendation": "ready-to-quote"
}
}| Field | Required | Meaning |
|---|---|---|
name | no | Stable identifier, unique within the agent's hook chain. Defaults to the folder name. |
points | yes | Lifecycle points to bind to (non-empty array; see below). |
capabilities | yes | Declared capabilities (required array). Only store:read is enforced by the runtime; other entries describe intent. |
failPolicy | no | "closed" (a failing hook blocks) or "open" (a failing hook allows). Defaults per point: closed everywhere except postTurn (open). |
priority | no | Number; lower runs first at a shared point. Default 0. |
config | no | Author-supplied defaults, passed to createHook. Overridable per agent via amodal.json (see Chain configuration). |
trustTier | no | "first_party", "verified", or "community". Metadata only; not enforced. |
The loader validates the manifest on startup. A malformed hook (bad JSON, unknown point or capability, missing handler) is skipped with a hook_skipped warning; it does not disable the other hooks. Two hooks with the same name keep the first one loaded (local hooks win over package hooks) and log hook_name_conflict.
Hook points
| Point | Fires | Payload |
|---|---|---|
preInput | before a user/trigger message enters context (and before it is persisted) | { text, source } where source is 'chat' | 'webhook' | 'automation' | 'channel' |
preToolUse | before a tool call executes, ahead of the permission gate | { toolName, args, connection?, endpointPath?, method?, intent?, isDelegated?, planModeActive? } |
postToolUse | after a tool returns, before its result re-enters context | { toolName, args, status, result, durationMs } (result is the tool's string output; structured results such as image blocks bypass this point) |
preOutput | before assistant text is streamed, persisted, or routed to a channel; runs on every turn's text, not just the final answer | { text, channels } |
postTurn | after a turn completes; observe-only | { turn, usage, toolCalls, terminal } |
preToolUse runs before the connection ACL (access.json), so a hook can block or rewrite args first; the ACL then has the final, authoritative say (and re-evaluates rewritten args).
Live root turns pass source: 'chat' to preInput and channels: ['chat'] to preOutput. isDelegated and planModeActive are not populated. Do not base a permission decision on these absent fields.
When any hook is loaded (whatever points it binds to), assistant text is buffered instead of streamed token by token: a preOutput hook cannot unsend text already on the wire, so the runtime holds each turn's text, runs the chain, and emits the result as one block.
postTurn is accepted by the loader and test endpoint, but the live loop does not invoke it.
Handler contract
The module exports createHook(config) (or a default export) returning the decision function:
// hooks/ready-to-quote-guard/index.mjs
/** @param {Record<string, unknown>} config merged hook.json config + amodal.json overrides */
export function createHook(config) {
const guarded = new Set(config.guardedTools ?? []);
return {
/**
* @param {string} point the lifecycle point that fired
* @param {object} payload that point's payload (see table above)
* @param {object} ctx HookContext
* @returns {Promise<{action: 'allow'} |
* {action: 'block', reason: string} |
* {action: 'modify', payload: object, note?: string} |
* {action: 'ask', reason: string}>}
*/
async run(point, payload, ctx) {
if (point !== 'preToolUse' || !guarded.has(payload.toolName)) {
return { action: 'allow' };
}
const row = payload.args?.value;
if (row?.recommendation === config.blockedRecommendation) {
ctx.log(`blocked recommendation in ${payload.toolName}`);
return { action: 'block', reason: 'This workflow cannot set the ready-to-quote recommendation.' };
}
return { action: 'allow' };
},
};
}Accepted export shapes: a factory (config) => {run} or (config) => run, a plain {run} object, or a bare run function. run may be sync or async. A hook bound to several points receives each one through the same run and switches on point.
ctx (HookContext)
| Property | Meaning |
|---|---|
config | Reserved; always {}. The resolved config (hook.json config plus amodal.json overrides) is passed to createHook(config); capture it in the factory closure rather than reading ctx.config. |
env(name) | Read a runtime process environment variable. The root chat hook runner does not apply an allowlist or require the secrets capability for this method. |
log(message) | Structured log line, scoped to the session (guardrail_hook in runtime logs). |
signal | AbortSignal; aborts when the session or request is cancelled. |
agentId, scopeId, sessionId | Identifiers for the current turn, when available. |
caller | The verified caller of the turn: { userId?, source, orgId? }, sourced from the authenticated request (JWT claims), never from the client-supplied scopeContext. Absent for unauthenticated triggers. Use this for permission decisions. |
store | Read-only access to the agent's own stores: get(store, key) and query(store, filter?). Present only when the hook declares the store:read capability. Reads are scoped to the agent and the caller's scope. |
A common pattern is a permission hook that gates a tool on your own membership store: check ctx.caller.userId against a team_members row via ctx.store.get, allow on a matching role, block otherwise, with failPolicy: "closed" so a failed read never fails open.
Decisions
run returns one of four decisions:
| Action | Effect |
|---|---|
{ action: 'allow' } | No opinion; the chain continues. |
{ action: 'block', reason } | Refuse. Terminal: short-circuits the rest of the chain. |
{ action: 'modify', payload } | Replace the payload; the modified payload feeds the next hook, so transformers (successive redactors) compose. Valid at every point except postTurn. |
{ action: 'ask', reason } | Require human confirmation. Non-terminal: a later hook may still block. Meaningful at preToolUse, where it routes the call through the standard confirmation flow. |
When several hooks fire at one point, they run in ascending priority order and their decisions combine with precedence block > ask > modify > allow.
What block concretely does at each point:
| Point | Effect of block |
|---|---|
preInput | The turn is rejected before the message enters context or is persisted; the client receives an error event with your reason. |
preToolUse | The tool never executes; the model sees an error tool result: Blocked by guardrail: <reason>. |
postToolUse | The result is masked: the model sees [output withheld by guardrail: <reason>]. |
preOutput | The assistant text is replaced with [response withheld by guardrail: <reason>]. |
postTurn | Ignored (observe-only). |
modify details worth knowing: a preInput modify rewrites the text everything downstream sees (context, persistence, intent matching, the LLM), and the client is notified so the optimistic bubble can update; a preOutput modify is persisted to history, so the model's own next-turn view matches what the user saw; a preToolUse modify rewrites args before the ACL evaluates them.
Failure behavior
Each hook invocation is capped by a wall-clock timeout (default 1500 ms). A hook that throws, rejects, or times out is converted to a decision by its failure policy:
failPolicy: "closed": the failure becomes ablock(reason:Hook "<name>" failed (fail-closed)). This is the default atpreInput,preToolUse,postToolUse, andpreOutput.failPolicy: "open": the failure becomes anallow. Default atpostTurn; opt into it elsewhere only for pure observability hooks.
Every non-allow decision and every failure is logged (guardrail_decision in runtime logs) with the hook name, point, action, and reason.
Capabilities
Declare the capabilities used by the handler. Except for store:read, these declarations do not restrict access or validate returned decisions. Hooks run as trusted in-process code.
| Capability | Grants |
|---|---|
reads_input | Reads incoming message text (preInput). |
modifies_input | Rewrites incoming message text (preInput modify). |
reads_output | Reads assistant output (preOutput, postTurn). |
modifies_output | Rewrites assistant output (preOutput modify). |
reads_tool_io | Reads tool args/results (preToolUse, postToolUse). |
modifies_tool_io | Rewrites tool args/results (modify at tool points). |
gates_tools | Can block or require confirmation on a tool call. |
network | Makes outbound network calls (a sidecar or external policy engine). |
secrets | Declares use of runtime secrets; does not gate ctx.env. |
store:read | Reads the agent's own stores via ctx.store (read-only). Enforced: without it, ctx.store is absent. A store backend must also be supplied. |
Chain configuration (amodal.json)
The agent controls the composed chain through the optional hooks block:
{
"hooks": {
"order": ["pii-redactor", "ready-to-quote-guard"],
"disabled": ["verbose-audit"],
"config": {
"ready-to-quote-guard": { "blockedRecommendation": "ready-to-quote" }
}
}
}| Key | Meaning |
|---|---|
order | Explicit chain order by hook name. Listed hooks run first in this order; unlisted discovered hooks append after, sorted by their own priority. |
disabled | Hook names to skip entirely. |
config | Per-hook config overrides, keyed by hook name; merged over the hook's own hook.json config. |
Hooks from packages
An installed package (declared in amodal.json packages) can contribute hooks: a hook package is a package with a hooks/ directory inside it, scanned by the same loader. Select a subset with the use selector:
{
"packages": [{ "package": "@acme/compliance-pack", "use": ["hooks.pii-redactor"] }]
}A bare string entry loads everything the package ships (hooks included). A use list that names no hooks.<name> entries opts the package out of contributing hooks. On a name conflict, the local hooks/ folder wins. A declared but uninstalled package logs a warning rather than failing the agent.
Testing a hook
The runtime exposes a deterministic test runner so you can exercise a hook against a fixture payload without driving a real turn:
# inventory the hook manifests discovered under hooks/ and installed packages
curl $RUNTIME/inspect/hooks
# run one hook (or the whole chain, omit hookName) at a point
curl -X POST $RUNTIME/inspect/hooks/test \
-H 'content-type: application/json' \
-d '{
"point": "preToolUse",
"hookName": "ready-to-quote-guard",
"payload": {
"toolName": "store__submissions__set",
"args": { "value": { "recommendation": "ready-to-quote" } }
}
}'The response reports the combined decision (action, reason), the input and output payloads, whether the payload was modified or blocked, which hooks ran, and any ctx.log lines.
A failing hook with failPolicy: "closed" blocks calls at its configured points. Test handler errors and timeouts as well as successful decisions. Keep handlers below the 1500 ms deadline.
Local and packaged hooks run in the runtime process. Capability declarations and trustTier do not sandbox the module. Install only hook code you trust.