Nous.Hook behaviour (nous v0.13.3)
View SourceLifecycle interceptors for agent tool execution and request/response flow.
Hooks provide granular control over agent behavior at specific lifecycle events. They can block actions, modify inputs/outputs, and execute external commands for policy enforcement.
Hook Events
| Event | When Fired | Can Block? |
|---|---|---|
:session_start | Agent run begins | No |
:pre_request | Before LLM API call | Yes |
:post_response | After LLM response received | No |
:pre_tool_use | Before each tool execution | Yes |
:post_tool_use | After each tool execution | No (can modify result) |
:session_end | After run completes | No |
Hook Types
:function— Inline functionfn event, payload -> result end:module— Module implementingNous.Hookbehaviour:command— Shell command executed viaNetRunner.run/2
Matchers
Matchers filter hooks to specific tools (for :pre_tool_use / :post_tool_use):
nil— matches all tool calls"tool_name"— exact name match~r/pattern/— regex match on tool namefn payload -> boolean end— arbitrary predicate
Examples
# Block dangerous tool calls
%Nous.Hook{
event: :pre_tool_use,
matcher: "delete_file",
type: :function,
handler: fn _event, %{arguments: %{"path" => path}} ->
if String.starts_with?(path, "/etc"), do: :deny, else: :allow
end
}
# External policy check via shell command
%Nous.Hook{
event: :pre_tool_use,
matcher: ~r/^(write|delete)/,
type: :command,
handler: "python3 scripts/policy_check.py",
timeout: 5_000
}
Summary
Callbacks
Handle a hook event with the given payload.
Functions
Returns whether an event type supports blocking (returning :deny).
Check if a hook's matcher matches the given payload.
Create a new function hook.
Types
@type event() ::
:pre_tool_use
| :post_tool_use
| :pre_request
| :post_response
| :session_start
| :session_end
@type hook_type() :: :function | :module | :command
Callbacks
Functions
Returns whether an event type supports blocking (returning :deny).
Check if a hook's matcher matches the given payload.
For :pre_tool_use and :post_tool_use events, matches against the tool name.
For other events, nil matchers always match.
Create a new function hook.