Skip to content

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 ​

CallLifetime
registry.add(fn) → signaturepersistent, fires on every occurrence; the returned token removes it again
registry.add_once(fn) → signatureremoved after the first invocation (used e.g. by the image tool's step cleanup)
registry.remove(signature)drop a registration by the signature it came back with; a no-op if it already fired or was removed
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; when a cancel cuts an invoke short, the one-shots of that batch are consumed without running.

Handlers receive one dataclass argument and may mutate it in place — that is the main mechanism, not the return value.

Hook points ​

HookArgsNotes
run_start / run_endRunArgs(agent)Only on real idle → running → idle transitions, not nested scopes; run_end fires for success, error and cancellation alike.
after_initializeAfterInitializeArgs(agent)Extensions, tools and commands are all in place.
before_executionBeforeExecutionArgs(agent, schema, max_iterations, context_value, takeover_result)Once per execute(), before the first model call. See takeover below.
before_execution_stepBeforeExecutionStepArgs(agent)Per loop iteration, before the model call; the auto-compactor hooks here.
after_execution_stepAfterExecutionStepArgs(agent, should_continue)After tool results are in the conversation, before the next model call. Mutating should_continue to False ends the run — see below.
before_tool_callBeforeToolCallArgs(agent, tool_calls)tool_calls is editable — rewrite arguments, drop calls.
after_tool_callAfterToolCallArgs(agent, tool_results)(tool_id, result) pairs, editable.
before_command / after_commandCommandArgs(agent, command, arguments)After the command is resolved (unknown names do not fire); arguments is editable.
model_text_delta / model_reasoning_deltaTextDelta(agent, model_call_id, content)Called before a streamed delta is applied; rewriting content changes what is recorded and shown.
completion_token_updateTokenMetrics(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_errorAgentMessageArgs(agent, message)Redact or rewrite the agent's messages; mutating message changes what the user sees.
before_finalizeBeforeFinalizeArgs(agent)Release resources here — the display is still bound.

Ending a run early ​

after_execution_step decides whether the loop keeps going. Clearing should_continue ends the run right there, resolving the last model message as the answer (and validating it against the schema, when there is one):

python
def budget_cap(args):
    if (args.agent.conversation.total_tokens or 0) > 200_000:
        args.should_continue = False     # stop here, with what we have

agent.hooks.after_execution_step.add(budget_cap)

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.

Xun 1.5.1 (source 88942ea, 2026-11-07) documentation, generated from the source tree.