Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/snapshots/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

这里存放按 AstrBot Tag 归档的文档快照。

- [v4.23.0](/snapshots/v4.23.0/)
- [v4.12.3](/snapshots/v4.12.3/)
- [v4.12.2](/snapshots/v4.12.2/)
- [v4.12.1](/snapshots/v4.12.1/)
Expand Down
130 changes: 130 additions & 0 deletions docs/snapshots/v4.23.0/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
name: skill-astrbot-dev
description: Reference + workflow notes for AstrBot plugin development (messages, platform adapters, plugin config, agent system).
metadata:
short-description: AstrBot dev reference
---
# skill-astrbot-dev

This skill is the source-of-truth index for AstrBot developer docs in this repo (`docs/`).

Goal: when this skill is selected, immediately ground on the minimum required docs + code entrypoints,
avoid duplicated reading, and always prefer code as the final authority.

## When to use

Use this skill when you ask for help with:

- AstrBot plugin structure, decorators/hooks, lifecycle, schema, sessions
- Message model/event flow and message-chain conversion
- Platform adapter interface and message conversion patterns
- Agent topics (tools/providers/personas/subagents/sandbox/cron/context compression)

## Mandatory workflow (use this every time)

1. Start from a single entrypoint (avoid broad loading):
- Site index: `docs/index.md`
- Core concepts: `docs/design_standards/core_concepts.md`
2. Pick one topic folder and stay focused:
- Agent system: `docs/agent/`
- Plugin config: `docs/plugin_config/`
- Messages: `docs/messages/`
- Platform adapters: `docs/platform_adapters/`
3. For Agent Runner (v4.7.0+): `docs/agent/agent-runner.md`
3. If the user targets a specific AstrBot version, cross-check:
- `docs/snapshots/<version>/`
4. If docs and code disagree, treat code as truth:
- Core code lives under `astrbotcore/astrbot/core/` (read only the needed files)

## STRONGLY ADVISED: use AstrBot SDK while writing plugins

When writing plugin code, strongly advised to install AstrBot SDK locally and use it for API reference,
signature lookup, and IDE auto-completion.

```powershell
python -m pip install -U astrbot
```

Use SDK symbols first when implementing hooks, provider/context calls, and agent runner integration.
This helps reduce guesswork and signature mismatch.

If AstrBot source code in this repo is available, still treat repo code as higher priority than package docs.

## Plugin project structure (strongly advised)

A standard AstrBot plugin project should include:

- `main.py`: entrypoint. Implement plugin startup and primary features here.
- `metadata.yaml`: plugin metadata (name, version, author, repo, description).
- `README.md`: installation, usage, feature overview, and dev links.
- `.gitignore`: ignore Python cache (`__pycache__`) and IDE config files.
- `LICENSE`: open-source license file.

## `metadata.yaml` minimal template

```yaml
name: astrbot_plugin_helloworld # 插件唯一识别名,最好以 astrbot_plugin_ 前缀开头
display_name: helloworld # 展示名(v4.5.0+)
desc: AstrBot 插件示例。 # 插件简短描述
version: v1.3.0 # 版本号:v1.1.1 或 v1.1
author: Soulter # 作者
repo: https://github.com/Soulter/helloworld # 插件的仓库地址
```

## Code rules for plugin implementation

- Use `async def` for handlers/hooks/tool functions.
- Keep `main.py` focused on plugin entry and orchestration; extract complex logic into submodules.
- Add type hints for public methods and hook signatures.
- Do not hardcode provider IDs or secrets; expose configurable fields in `_conf_schema.json`.
- Prefer small, testable functions over large monolithic handler bodies.
- Keep README and metadata consistent with actual plugin behavior and version.
-If you are writing AstrBot core code instead of plugins, you must submit a PR to https://github.com/AstrBotDevs/AstrBot-docs if the changes require doc updates (for instance: new hooks, new APIs, new features, platform adapter changes, and so on). If you don't see the docs repo, please remind the user to clone the docs-repo and add it to the workspace.
## Hooks: avoid missing / outdated references

There are two different "hook" layers you must not mix up:

- Plugin event hooks (decorators): `docs/plugin_config/hooks.md`
- Agent runner hooks (`BaseAgentRunHooks`): `docs/agent/agent-related-hooks.md`

If you need a complete hook inventory (because context may be truncated), generate it locally:

```powershell
python scripts/generate_hook_inventory.py
```

This writes to `docs/.tmp/hook_inventory/` (gitignored). Use it as a scratchpad for writing/updating docs;
do not reference `.tmp` paths as public documentation URLs.

## High-signal code entrypoints (open only when needed)

- Event hooks registration + signatures: `astrbotcore/astrbot/core/star/register/star_handler.py`
- Event types: `astrbotcore/astrbot/core/star/star_handler.py`
- Agent runners + hook call order: `astrbotcore/astrbot/core/agent/runners/`
- Agent hook interface: `astrbotcore/astrbot/core/agent/hooks.py`
- Main agent build (sandbox/cron/tools): `astrbotcore/astrbot/core/astr_main_agent.py`
- Skills system (AstrBot runtime skills): `astrbotcore/astrbot/core/skills/skill_manager.py`
- Subagents config loading: `astrbotcore/astrbot/core/subagent_orchestrator.py`

## v4.5.7+ New Tool Definition Pattern

推荐使用 dataclass 模式定义 Tool(见 `docs/design_standards/core_concepts.md` 第7节):

```python
from pydantic.dataclasses import dataclass
from astrbot.core.agent.tool import FunctionTool

@dataclass
class MyTool(FunctionTool):
name: str = "my_tool"
description: str = "工具描述"
parameters: dict = {...}

async def call(self, context, **kwargs) -> str:
return "结果"
```

注册:`self.context.add_llm_tools(MyTool())`

装饰器方式仍然支持,但推荐新项目使用 dataclass 模式。

29 changes: 29 additions & 0 deletions docs/snapshots/v4.23.0/Storage & Utils/file_storage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
category: storage
---

# 文件存储规范

对于大文件、日志或插件特有的资源文件,AstrBot 建议遵循以下存储规范。

### 目录规范

所有插件特有的文件应存储在以下目录:
`data/plugin_data/{plugin_name}/`

### 获取存储路径

建议在插件中使用以下方式获取路径,以确保兼容性:

```python
from astrbot.core.utils.astrbot_path import get_astrbot_data_path

# 获取插件专属数据目录
plugin_data_path = get_astrbot_data_path() / "plugin_data" / self.name
plugin_data_path.mkdir(parents=True, exist_ok=True) # 确保目录存在
```

### 注意事项

- 不要将大文件直接存储在 `docs/` 或插件根目录下。
- 建议定期清理不再使用的临时文件。
21 changes: 21 additions & 0 deletions docs/snapshots/v4.23.0/Storage & Utils/kv_storage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
category: storage
---

# 键值对存储 (KV Storage)

AstrBot 为插件提供了简单易用的 KV 存储接口,适合存储配置、轻量级状态或用户数据。

### 核心接口 (>= v4.9.2)

这些方法在插件类(继承自 `Star`)中可以直接调用:

- `await self.put_kv_data(key: str, value: Any)`: 存储数据。
- `await self.get_kv_data(key: str, default: Any = None) -> Any`: 获取数据。
- `await self.delete_kv_data(key: str)`: 删除数据。

### 特点

- **隔离性**: 数据按插件 ID 隔离,不同插件之间的 Key 不会冲突。
- **持久化**: 数据会自动持久化到 `data/metadata/kv_storage.db`(或相应目录)。
- **异步**: 接口均为异步方法。
109 changes: 109 additions & 0 deletions docs/snapshots/v4.23.0/Storage & Utils/text_to_image.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# 文转图 (Text to Image)

将文本或 HTML 模板渲染为图片。

## 插件方法(Star)

### `text_to_image`

```python
async def text_to_image(self, text: str, return_url: bool = True) -> str
```

- 内部调用:`html_renderer.render_t2i(...)`
- 使用当前激活模板:`t2i_active_template`
- `return_url=True` 返回可发送的 URL;`False` 返回本地文件路径
- **网络渲染失败会自动 fallback 到本地渲染**

```python
url = await self.text_to_image("你好,AstrBot")
yield event.image_result(url)
```

### `html_render`

```python
async def html_render(self, tmpl: str, data: dict, return_url: bool = True, options: dict | None = None) -> str
```

- 内部调用:`html_renderer.render_custom_template(...)`
- 适合自定义 HTML + Jinja2 模板渲染

```python
tmpl = """
<div style='font-size:28px'>
<h1>{{ title }}</h1>
<ul>{% for i in items %}<li>{{ i }}</li>{% endfor %}</ul>
</div>
"""
url = await self.html_render(tmpl, {"title": "Todo", "items": ["吃饭", "睡觉"]})
yield event.image_result(url)
```

## SDK 方法(`html_renderer`)

```python
from astrbot.api import html_renderer
```

### 初始化

```python
await html_renderer.initialize()
```

### 默认文转图

```python
await html_renderer.render_t2i(
text: str,
use_network: bool = True,
return_url: bool = False,
template_name: str | None = None,
)
```

- `use_network=True` 先走网络渲染;失败时 fallback 到本地渲染
- `return_url=False` 时返回本地路径

### 自定义模板渲染

```python
await html_renderer.render_custom_template(
tmpl_str: str,
tmpl_data: dict,
return_url: bool = False,
options: dict | None = None,
)
```

## 渲染选项(`html_render` / `render_custom_template`)

`options` 透传给截图参数(Playwright 风格):

- `timeout`
- `type`: `"jpeg" | "png"`
- `quality`(仅 jpeg)
- `omit_background`(仅 png)
- `full_page`
- `clip`
- `animations`: `"allow" | "disabled"`
- `caret`: `"hide" | "initial"`
- `scale`: `"css" | "device"`

默认值(未传 `options` 时):

```python
{"full_page": True, "type": "jpeg", "quality": 40}
```

## 模板管理方法

`TemplateManager` 提供模板 CRUD:

- `list_templates()`
- `get_template(name)`
- `create_template(name, content)`
- `update_template(name, content)`
- `delete_template(name)`
- `reset_default_template()`
58 changes: 58 additions & 0 deletions docs/snapshots/v4.23.0/agent/agent-registration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
category: agent
---

# Agent 注册(register_agent)

把子智能体注册成 handoff tool,供主模型在工具调用阶段转交任务。

## 何时使用

- 推荐优先:`docs/agent/subagents.md`(配置式,支持 `provider_id`、运维更稳定)。
- 再用 `register_agent`:需要在插件代码里动态组装 Agent 或动态挂载 run hooks。

## API

```python
register_agent(name: str, instruction: str, tools: list[str | FunctionTool] | None = None, run_hooks: BaseAgentRunHooks | None = None)
```

## 最小示例

```python
from astrbot.core.star.register.star_handler import register_agent

@register_agent(
name="writer",
instruction="你是技术写作子智能体,输出精简、可执行内容。",
tools=["get_weather"],
)
async def writer_agent(event):
return None
```

## 给该 Agent 追加专属工具

```python
@writer_agent.llm_tool(name="rewrite_text")
async def rewrite_text(event, text: str):
"""重写文本。

Args:
text(string): 原文
"""
return f"rewrite: {text}"
```

## 当前执行路径(按源码)

- `register_agent` 会创建 `Agent` + `HandoffTool`,并加入全局工具列表。
- 运行时 handoff 走 `tool_loop_agent(...)`,核心来自 `instruction/tools/run_hooks`。
- 当前实现中,`@register_agent` 装饰的函数体不会作为 handoff 主执行入口。

## tips

- `register_agent` 属于 core 注册接口,不在 `astrbot.api.event.filter` 导出。
- `tools=["..."]` 里的字符串工具名必须已注册;未注册会被忽略,不会自动报错。
- 想给子智能体单独指定 `provider_id`,优先走配置式 `subagents`。
- `@writer_agent.llm_tool(...)` 的 docstring 必须写 `Args` 类型(例如 `text(string)`),否则 schema 解析会失败。
Loading