# Host services

Send messages, call models, store data, and work with the shell and subagents.

`self.context` is the entry point to the services ShiritaiBot gives plugins. This page groups the most useful methods by what they're for.

## Send messages

```python
await self.context.send_message(session, "Reminder: time to drink some water")
await self.context.notify_owner("The backup failed. Check the free disk space.")
```

* `send_message(session, text)` sends text to a session. Get `session` from `MessageEvent.session` or `ToolContext.session`; once you've saved it, you can use it any time. Messages pass through the [send hooks](https://shiritaibot.dev/en/docs/plugins/hooks#send).
* `notify_owner(text)` goes straight to the owner, skipping the proactive engine's triage, quiet hours and rate limits.

## Call a model

Plugins can borrow the models set up in ShiritaiBot for simple text processing:

```python
summary = await self.context.llm_generate(
    f"Summarize this announcement in one sentence:\n{notice}",
    system="You write concise summaries.",
)
```

| Parameter  | Description                                                                            |
| ---------- | -------------------------------------------------------------------------------------- |
| `prompt`   | The user message                                                                       |
| `messages` | Optional earlier messages; `prompt` is added at the end                                |
| `system`   | The system prompt                                                                      |
| `route`    | Which model route to use; `light` by default, the "Proactive triage and summary model" |

This is a plain call without tools, and it returns the model's text.

If a decision model is set up, `await self.context.decide(state, questions)` asks structured multiple-choice or rating questions. Without one it returns `None`, and you can fall back to `llm_generate`.

## Store data

For small pieces of data, use KV storage. Each plugin has its own, and values must be JSON-serializable:

```python
count = await self.get_kv_data("count", 0)
await self.put_kv_data("count", count + 1)
await self.delete_kv_data("count")
```

Put files and larger data in `self.data_dir`, which is `data/plugin_data/<plugin ID>/`. The folder is created when the plugin loads and isn't deleted when the plugin is removed, so the data is still there after a reinstall.

Settings that users need to see or change belong in [plugin settings](https://shiritaibot.dev/en/docs/plugins/config), not in KV storage.

## Logging

Logs from `self.logger` appear in the terminal, in `data/logs/shiritaibot.log` and in **Activity Log → Runtime logs** in the WebUI, tagged with the plugin ID:

```python
self.logger.debug("Only shown with --log-level debug")
self.logger.log("Received 3 new emails")
self.logger.warning("Couldn't fetch mail (TimeoutError)", "INBOX")   # the second argument is an extra tag
self.logger.error("Sync failed", exc=exc)                             # the traceback goes to the log file
```

Write each log line as one sentence a person or model can understand. Don't print whole JSON documents, message bodies or credentials. To squeeze a dict or long string onto one line, use `brief(value, limit)`:

```python
from shiritaibot.api import brief

self.logger.log(f"Received request {brief(payload, 80)}")
```

Logs always use the bot's global language; plugin text for users can follow each chat's language, as described in [Languages](https://shiritaibot.dev/en/docs/plugins#languages).

## Protocol clients

To call the API of a OneBot protocol client (to list a group's members, for example):

```python
platform = self.context.get_platform(event.adapter)
if platform and platform.status == "connected":
    members = await platform.call("get_group_member_list", {"group_id": int(event.group_id)})
```

`adapter` is the ID of the protocol client instance, available as `MessageEvent.adapter`. `platform.self_id` is the bot's own QQ number.

`self.context.get_plugins()` returns information about every loaded plugin.

## The shell and subagents

ShiritaiBot's shell tool and subagents (Codex, Claude Code) start subprocesses. Plugins can influence those subprocesses:

| Method                       | Description                                                                |
| ---------------------------- | -------------------------------------------------------------------------- |
| `set_process_env(env)`       | Adds environment variables for subprocesses, such as a git commit identity |
| `add_shell_filter(rewrite)`  | Rewrites shell commands after they're approved and before they run         |
| `add_subagent_note(text)`    | Appends a note to the prompt of newly started subagents                    |
| `session_workspace(session)` | Returns a session's shell working folder                                   |

The built-in GitHub plugin uses these: an environment variable makes the model commit as the bot account, and a shell filter adds Co-authored-by to its commits.

Keep in mind:

* The model controls these subprocesses, so **never pass credentials such as API keys through `set_process_env`**. Different plugins can't set the same variable.
* `rewrite(command)` must be synchronous, fast and free of side effects, and only make small, predictable changes. If it fails, it's ignored and the original command runs.
* All of these are undone automatically when the plugin is reloaded or disabled.

## The old plugin API

Early plugins used `plugin.toml` as their manifest, with an `Entry` class in `main.py` imported from `shiritaibot.plugin_api`, and `start()` / `close()` as lifecycle methods:

```python main.py
from shiritaibot.plugin_api import Plugin, schema


class Entry(Plugin):
    async def start(self):
        self.context.register_tool("my_query", "What the tool does", schema({}), self.query, risk="safe")

    async def query(self, ctx, args):
        return {"answer": "hello"}
```

These plugins still load, but they can't use commands, message listeners or any hooks. Write new plugins the way this chapter describes. When a folder has both manifests, the new one is used.

Support for the old API will be removed in a few versions, so please move your plugins to the new API soon. Why not ask your ShiritaiBot to do it?
