> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xenovia.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Hooks

> The SDK's hooks, execute() and @guard(), and how to give one step its own checks.

Each hook sends one stage of your agent's work to Xenovia and returns a decision. Pick the hook for the action, check the response, and act on it.

## The hooks

Hooks are the main API. Each one sends one stage and returns a `XenoviaResponse`. Hooks never skip work for you: check the response and act on it.

| Hook | Stage | Sends |
| - | - | - |
| `tool_pre(name, arguments)` | `tool_call` | The tool's arguments before it runs |
| `tool_post(name, content)` | `tool_result` | The tool's output before the model sees it |
| `memory_write(content)` | `memory_write` | Content your agent is about to persist |
| `context_summary(summary, original)` | `context_summary` | A summary replacing earlier context |
| `model_pre(messages, system_prompt=None, tools=None)` | `model_request` | The model request, for agents that call the model directly |
| `model_post(response, messages=None)` | `model_response` | The model reply, for agents that call the model directly |
| `model_post_stream(chunks, messages=None)` | `model_response` | Buffers streamed text chunks, then checks the full reply |

Every hook also accepts `session_id=`.

```python theme={null}
check = xenovia.tool_pre("send_email", {"to": to, "body": body})

if not check.is_success():  # blocked, or failed
    return "This action is not allowed."

args = check.payload["arguments"] if check.is_redacted() else {"to": to, "body": body}
result = send_email(**args)

reviewed = xenovia.tool_post("send_email", str(result))
if not reviewed.is_success():
    return "The tool result was withheld."
```

A redacted tool call returns the masked arguments in `payload["arguments"]`; a redacted tool result, memory write, or reply returns masked text in `payload["content"]` or `payload["response"]`.

> [!NOTE]
>
> If your model calls already go through the agent endpoint, leave `model_pre` and `model_post` off: the runtime checks the model request and reply there. Use them only for agents that call their model provider directly.

`model_pre` accepts messages with string content or a list of content parts (OpenAI or Anthropic style), and tools as flat `{name, description}` objects or OpenAI function tools. Only text is checked: text parts, `refusal` parts, and the text of Anthropic `tool_result`, `mcp_tool_result` and `search_result` blocks (string content or nested text parts) are joined. Media and file parts, the model's own tool calls (`tool_use`, `server_tool_use`, `mcp_tool_use`) and thinking, and Anthropic server tool results (web search, web fetch, code execution) are not sent, so their content is not checked. On success, `payload["messages"]` and `payload["tools"]` are your own objects, with any redaction written back into the part it came from.

`model_pre`, and `model_post` when you pass `messages`, raise `ValueError`, and send nothing, when messages are not a list of dicts, a role is not a string, content is not a string, a list, or `None`, or a content part is malformed or of a type not listed above. `model_pre` also raises it when a tool is not a dict or has no name.

## `execute()` — a single check

`execute()` is the call the hooks are built on. Use it for actions that are not a tool, memory, or model step.

```python theme={null}
response = xenovia.execute(
    {"amount": 500, "to": "acct_123"},
    operation="payments.transfer",   # inferred from the calling function if omitted
    stage="tool_call",               # default
)

if response.is_blocked():
    print(f"Blocked. Trace: {response.trace_id}")
elif response.is_success():
    print(f"Allowed. Trace: {response.trace_id}")
```

`stage` is one of `model_request`, `model_response`, `tool_call`, `tool_result`, `memory_write`, or `context_summary`. If `operation` is omitted, the SDK uses the caller's `module.function` name. `execute()` also accepts `session_id=` and `turn=` (see [Sessions](https://docs.xenovia.io/sdk/reference.md#sessions)).

> [!NOTE]
>
> `capability=` was renamed to `operation=` in 0.2.0. It still works on `execute()` and `@guard()` as a deprecated alias and emits a `DeprecationWarning`.

## `@guard()` — decorator

`@guard()` checks a function call as a `tool_call` before the body runs. The decorated function returns a `XenoviaResponse`; read `.result` for the function's return value.

```python theme={null}
@xenovia.guard(operation="payments.transfer")
def transfer_funds(amount: int, to: str) -> dict:
    return run_transfer(amount, to)

response = transfer_funds(500, "acct_123")

if response.is_blocked():
    handle_block(response.trace_id)
else:
    receipt = response.result
```

* The payload sent is `{"arguments": {...}}`, with every bound argument (including defaults).
* On `allow`, the function runs with its original arguments. On `redact`, it runs with the masked arguments. On `deny` or `error`, it does not run.
* `async def` functions are supported.
* `mode="enforce"` is the only mode. The SDK has no observe mode: to trial a rule without blocking, set the policy or guardrail to **Monitor** in the console. Monitor evaluations return `allow`.

## Sub-agents

To give one step of your agent its own checks, create an inline [sub-agent](https://docs.xenovia.io/agents/sub-agents.md) and a key scoped to it, then use that key for the step's client:

```python theme={null}
planner = Xenovia(api_key=os.environ["XENOVIA_API_KEY"], auto_session=True)
researcher = Xenovia(api_key=os.environ["RESEARCHER_KEY"])  # a key scoped to the "researcher" sub-agent

plan = planner.tool_pre("plan_research", {"topic": topic})  # creates the session
check = researcher.tool_pre("web_search", {"query": query}, session_id=planner.session_id)
```

A sub-agent key belongs to the same agent, so its checks run the agent's policies and guardrails, plus the sub-agent's own. It can share the parent's session, as above. Nothing in the request body selects a sub-agent: only the key does.

`subagent()` returns a client with the same key, its own session, and the parent's settings. It does not change which rules apply. Don't pass it `role=`: that sets `agent_role`, which the runtime refuses.

## What next?

> [card] [Reference](https://docs.xenovia.io/sdk/reference.md)
>
> XenoviaResponse, sessions and errors.

> [card] [Sub-agents](https://docs.xenovia.io/agents/sub-agents.md)
>
> Give a step its own key and guardrails.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.