{ name, preToolCall?, postToolCall?, preGenerate?, postGenerate? } that runs inside the agent loop, around every tool call and every model call. Use one to write an audit log, deny a tool, redact or truncate a result, inject context before the model call, or change the request (a header, temperature) it sends.
Hooks are code you write, not policy and not a human decision: for rules that allow, deny or ask per tool, and for a person approving a call, use permissions and needsApproval (Approvals). Listeners such as onEvent only watch a run and cannot change it (Streaming); a hook can.
Your first hook
Pass hooks tocreateAgent({ hooks }). This one logs every tool call and what it returned:
ctx.args, ctx.messages or ctx.request in place also changes the run.
The four hook points
The common fields on every context are
agentId, agentName, sessionId, messages (the live conversation history), metadata (a free-form bag) and subagent (set inside a sub-agent). Tool-call contexts also carry resumedAfterApproval: true only when the hook fires for a call being re-run after a human approved its pause, so a stateful hook (a loop guard, an audit counter) can skip the re-fire with if (ctx.resumedAfterApproval) return;. ctx.emit exists when the run has listeners (createAgent({ onEvent }), onAgentEvent) or is streamed, and adds compaction.start / compaction.done events to the run’s events. Inside an executor run, preGenerate also gets ctx.generate(provider, request, purpose): a side model call (the compaction summarizer uses it) that gets its own chat span tagged lousho.call.purpose and counts in the run’s usage and budgets.
Hook outcomes
A tool-call hook can change what happens, not just watch it. ApreToolCall
hook may return:
- nothing: the call goes on unchanged (mutating
ctx.argsin place still works). { deny: reason }: the call does not run. The model gets the samekind: 'denied'tool error aneedsApprovaldeny produces (see Approvals), streams seetool.error, andonPermissionDecisionrecordsdecision: 'deny'withhookandreason.{ result: value }: the call does not run andvalueis its result. Thetool.doneevent and the transcript’stoolmessage (metadata) carryreplacedByHook: '<hook name>'.{ input: args }: the call runs withargs. They are validated against the tool’s input schema again; a mismatch becomes akind: 'validation'tool error whose message names the hook, and the tool does not run.
postToolCall hook may return { result: value } to replace the result the
model sees (to redact or truncate it); nothing keeps it. Hooks run in
registration order: the first deny or result of a pre-hook skips the
pre-hooks after it, inputs chain (each hook sees the previous one’s as
ctx.args), and each post-hook sees the result an earlier one replaced. A hook
that throws still rejects the run, as before. Sub-agents inherit the lead
agent’s hooks and their outcomes.
Recipes
Each recipe is a complete program. They run againstmockModel, so none of them needs an API key or a live model call; the same pattern tests your own hooks offline (Testing). Each one scripts a model turn that calls a tool, then a final answer.
Stop a run that makes no progress
createProgressGuard() stops a run spending its budget on calls that aren’t
getting anywhere. It’s off unless you add it:
- From the second failure of a tool with the same error, it adds a
hintto the result, with advice for the class of failure (classifyToolFailure(): bad input, timeout, missing capability, permission or unknown). - After
maxFailuresfailures with the same error (default 3), it denies that tool for the run. Numbers in the message don’t make an error different. - After
maxRepeatsidentical calls returning the same result (default 3), it denies that call. A call whose result changes isn’t repeating. - After
maxSameResultscalls to a tool return the same result (default 5), it denies that tool, even when each call’s arguments differ. This catches a model rewording a search that keeps finding the same thing. - After
maxDenialsdenials (default 3), the next denial stops the run withLOUSHO_RUN_NO_PROGRESS, whichagent.recover()won’t retry.
heal.action event. A result it replaced is marked
on the tool’s span as lousho.tool.replaced_by_hook, and a denial is recorded as
the span’s error. The guard counts from the run’s transcript, so a resumed run
keeps its history. Calls in one batch aren’t counted until the batch settles, and
compaction can remove old calls from the count.
Check what a tool produced
A successful write doesn’t prove the output is usable.createOutputCheck() runs
your check after a tool succeeds. If it returns a problem, or throws, the model
sees it as outputCheckFailed on the result and can fix the output. The check
is your code, so make it independent of what the model wrote.
Deny a tool by name
Add a default argument
Return{ input } to run the tool with different arguments. They are validated against the tool’s schema again.
Truncate or redact a result
postToolCall receives the settled result and may return { result } to replace what the model sees. The tool itself ran unchanged.
Inject context before a model call
preGenerate sees the live ctx.messages and ctx.request. Push a message to add context, or change a request field.
Order and interaction
For one tool call, the order is: argument validation,preToolCall hooks,
permission rules (permissions), tool guardrails, the tool’s needsApproval,
the approval pause, execution, postToolCall hooks. Hooks run before every
approval decision, so rules, needsApproval and the human all see (and approve)
the input a hook produced; the pending approval’s args show it. When an
approved call is resumed, the pre-hooks run again: they may still deny it or
supply its result, but an { input } that differs from the approved input is
refused with a tool error instead of running. See Approvals for the pause and the resume.
- Several hooks run in the order of the
hooksarray, one at a time: each is awaited before the next, so a later hook sees what an earlier one changed. - A hook that throws still rejects the run. Hooks are trusted code: the error is not turned into a tool result for the model.
- Compaction.
createAgent({ hooks })runs your hooks first and the compaction hook after them, so compaction sees what they added (Context compaction). - Sub-agents inherit the lead agent’s hooks.
ctx.subagentis set when a hook runs inside one, so a hook can return early to see only the top-level run (Hooks inside sub-agents).
HookRegistry
createAgent({ hooks }) takes a plain array. Code that uses the executor API (The executor API) passes a HookRegistry: an ordered collection with register, registerMany, get, has, list, unregister, clear and size() — size is a method (hooks.size()), not a Map-style property. Registering a second hook with the same name replaces the first and logs a warning.
HookRegistry, AgentHook and the context types are available from the package root and from the lousho/hooks subpath. Hooks authored in the Agent Forge canvas editor are compiled into a HookRegistry and run sandboxed rather than in the host process: see Agent Forge.