English
Hooks
Every agent owns a Hooks object. Each hook is a registry of callbacks invoked in registration order; callbacks are wrapped so a raising handler is swallowed instead of breaking the run — the failure is silent, so log inside the handler if you want to see it (CancelledError / Ctrl-C still propagate).
python
from xun import Agent, Hooks
hooks = Hooks()
hooks.after_initialize.add(lambda a: print("initialized:", a.agent.name))
hooks.before_tool_call.add(lambda a: print(a.tool_calls))
agent = Agent(name="HookAgent", hooks=hooks).initialize()Hooks are not inherited by sub-agents — a child gets a fresh Hooks. Extensions add hooks to every agent at initialization.
Adding handlers
| Call | Lifetime |
|---|---|
registry.add(fn) | persistent, fires on every occurrence |
registry.add_once(fn) | removed after the first invocation (used e.g. by the image tool's step cleanup) |
registry.invoke(args) | what the framework calls; also available to you if you want to fire a hook yourself. A one-shot registered while the hook is firing waits for the next firing, and pending one-shots still run when the invoke is interrupted by a cancel. |
Handlers receive one dataclass argument and may mutate it in place — that is the main mechanism, not the return value.
Hook points
| Hook | Args | Notes |
|---|---|---|
run_start / run_end | RunArgs(agent) | Only on real idle → running → idle transitions, not nested scopes; run_end fires for success, error and cancellation alike. |
after_initialize | AfterInitializeArgs(agent) | Extensions, tools and commands are all in place. |
before_execution | BeforeExecutionArgs(agent, schema, max_iterations, context_value, takeover_result) | Once per execute(), before the first model call. See takeover below. |
before_execution_step / after_execution_step | …StepArgs(agent) | Per loop iteration; the auto-compactor hooks before_execution_step. |
before_tool_call | BeforeToolCallArgs(tool_calls) | tool_calls is editable — rewrite arguments, drop calls. |
after_tool_call | AfterToolCallArgs(tool_results) | (tool_id, result) pairs, editable. |
before_command / after_command | CommandArgs(command, arguments) | After the command is resolved (unknown names do not fire); arguments is editable. |
model_text_delta / model_reasoning_delta | TextDelta(agent, model_call_id, content) | Called before a streamed delta is applied; rewriting content changes what is recorded and shown. |
completion_token_update | TokenMetrics(model_call_id, completion_tokens, prompt_tokens, total_tokens, prompt_tokens_cached) | Per model call, for statistics. |
before_display_info / before_display_warning / before_display_error | AgentMessageArgs(agent, message) | Redact or rewrite the agent's messages; mutating message changes what the user sees. |
before_finalize | BeforeFinalizeArgs(agent) | Release resources here — the display is still bound. |
Taking over a run
before_execution can replace the whole execution loop:
python
def short_circuit(args):
if args.max_iterations < 0:
args.takeover_result = "cancelled by policy"
agent.hooks.before_execution.add(short_circuit)With takeover_result set, the loop is skipped entirely: no model call, no further hooks or events inside the loop, and no conversation history. If the execution had a schema, the string is validated against it — an invalid takeover fails the run.
This is the cheapest interception point for caches, replays and tests: a mock provider is a before_execution handler that returns a canned answer.