# Agent and send hooks

Add your own logic at each step of model requests, tool calls and sending messages.

Hooks let a plugin be called at specific steps of how ShiritaiBot handles things.

## The agent lifecycle

Each round of conversation ShiritaiBot handles (a turn) goes through these steps:

| Decorator                 | Handler arguments                 | When it runs and what it's for                      |
| ------------------------- | --------------------------------- | --------------------------------------------------- |
| `@hook.on_agent_begin()`  | `(turn)`                          | A turn starts                                       |
| `@hook.on_llm_request()`  | `(turn, request)`                 | Before each model request; can change the request   |
| `@hook.on_llm_response()` | `(turn, response)`                | After the model answers; can rewrite the reply text |
| `@hook.on_tool_call()`    | `(turn, name, arguments)`         | Before the model calls a tool; observe only         |
| `@hook.on_tool_result()`  | `(turn, name, arguments, result)` | After a tool returns; observe only                  |
| `@hook.on_agent_done()`   | `(turn, result)`                  | A turn ends                                         |

The model may call tools several times in one turn, so `on_llm_request` and `on_llm_response` can run more than once.

These hooks apply to conversations with users and to handling [proactive events](https://shiritaibot.dev/en/docs/plugins/proactive), but not to ShiritaiBot's internal model calls, such as subagents, event triage and memory maintenance.

## Change the model request

`on_llm_request` is the most used hook. This example adds the current weather to the user's message on the first request of each turn:

```python main.py
from shiritaibot.api import LLMRequest, Plugin, Turn, hook


class WeatherHint(Plugin):
    @hook.on_llm_request()
    async def add_weather(self, turn: Turn, request: LLMRequest):
        if request.step != 0 or turn.background:
            return
        weather = await self.current_weather()
        request.add_context(f"<weather>Current weather: {weather}</weather>")
```

What you can change on `request`:

| Field / method      | Description                                                     |
| ------------------- | --------------------------------------------------------------- |
| `system_prompt`     | The system prompt                                               |
| `messages`          | The messages sent to the model                                  |
| `tools`             | The tools offered to the model                                  |
| `add_context(text)` | Appends text after the latest user message; the most common one |
| `step`              | Which model request of this turn it is, from 0; read-only       |
| `route`             | The model route this request uses; read-only                    |

Changes only apply to this one request and aren't written to the conversation history. So you need to add them again on every request.

## Rewrite the model's reply

```python main.py
@hook.on_llm_response()
async def polish(self, turn: Turn, response: LLMResponse):
    response.text = response.text.replace("I'm an AI", "I'm ShiritaiBot")
```

The rewritten `response.text` is saved to the history and sent to the user. `response.tool_calls` is read-only.

## Turn and AgentResult

`turn` describes the current turn:

| Field             | Description                                            |
| ----------------- | ------------------------------------------------------ |
| `id`              | This turn's ID                                         |
| `session`         | The session ID                                         |
| `actor`           | The user who started this turn                         |
| `owner` / `group` | Whether it's the owner / whether it's in a group chat  |
| `background`      | Whether it's a background task                         |
| `mode`            | `chat` or `agent`                                      |
| `text`            | The user input that started this turn                  |
| `proactive`       | Whether it's handling a proactive event                |
| `event_id`        | The receipt ID of the proactive event; empty otherwise |

The `result` that `on_agent_done` receives has `status` (`completed`, `failed` or `cancelled`), `steps` (how many model requests were made) and `text` (the final reply).

## Send hooks

Every text ShiritaiBot sends to QQ and the WebUI, including model replies, command output and proactive notifications, passes through these two hooks:

| Decorator                      | Handler arguments | When it runs and what it's for                                    |
| ------------------------------ | ----------------- | ----------------------------------------------------------------- |
| `@hook.on_decorating_result()` | `(message)`       | Before the message joins the send queue; can rewrite or cancel it |
| `@hook.after_message_sent()`   | `(message)`       | After the message joins the send queue; runs in the background    |

```python main.py
from shiritaibot.api import OutgoingMessage

@hook.on_decorating_result()
async def sign(self, message: OutgoingMessage):
    if message.session.startswith("web:"):
        message.text += "\n\n— from ShiritaiBot"

@hook.on_decorating_result()
async def block_words(self, message: OutgoingMessage):
    if "something it shouldn't say" in message.text:
        message.cancel()
```

Tool approval prompts don't pass through these hooks; plugins can neither rewrite nor cancel them.

## When plugins have loaded

A `@hook.on_loaded()` handler receives only `self`. It runs once ShiritaiBot has finished starting up, or later when the plugin is reloaded. Put work here that must wait until other parts, such as the QQ protocol client, are ready.

## Order and timeouts

* When several plugins register the same hook, they run by `priority`, highest first, as in `@hook.on_llm_request(priority=10)`. With equal priority they run in plugin load order, and later plugins see the objects earlier ones changed.
* A hook may run for at most 10 seconds. A hook that fails or times out only logs a warning and doesn't affect normal handling.
* Hooks are called often, so keep them light. Cache slow lookups ahead of time.
