# 插件与 Hooks

Bub 基于标准 [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/) 自动发现插件，并通过 Hook 将自定义逻辑接入应用的各个运行阶段。

插件主要提供三类扩展能力：
- **自定义工具**：通过 `provide_tools` 注册工具函数；
- **常驻后台服务**：通过 `Lifecycle` 挂载随网关或交互会话运行的守护服务（如 MCP 客户端、消息渠道）；
- **流程改写与拦截**：通过 Hook 改写提示词、拦截或审批工具调用、持久化跨 Turn 状态。

## 创建最小插件 {#create-a-plugin}

在深入了解各种高级 Hook 之前，我们先写一个无需配置模型 API Key 的最小回声（Echo）插件，走通从创建到运行的完整流程。

### 1. 初始化项目 {#initialize-project}

使用 `uv` 创建 Python 库项目：

```bash
uv init --lib bub-echo-plugin
cd bub-echo-plugin
```

在 `src/bub_echo_plugin/` 下新建 `plugin.py`：

- bub-echo-plugin/
  - pyproject.toml
  - src/
    - bub_echo_plugin/
      - \_\_init\_\_.py
      - **plugin.py** # 存放插件与 Hook 实现

### 2. 声明入口点 {#declare-entry-point}

在 `pyproject.toml` 中添加 `[project.entry-points."bub"]`：

```toml title="pyproject.toml" mark={11-12}
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "bub-echo-plugin"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["bub[app]"]

[project.entry-points."bub"]
echo = "bub_echo_plugin.plugin:echo_plugin"
```

- 入口点组名必须为 `"bub"`；
- 键名 `echo` 是插件名称，值指向要加载的模块、实例或类。

### 3. 实现 Hook {#implement-hooks}

使用 `@hookimpl` 装饰器标记 Hook 方法：

```python title="src/bub_echo_plugin/plugin.py" "@hookimpl"
from bub import hookimpl

class EchoPlugin:
    @hookimpl
    def run_model(self, prompt, session_id, state):
        return f"[echo:{session_id}] {prompt}"

echo_plugin = EchoPlugin()
```

这里实现了 `run_model` Hook 接管模型执行阶段，直接将会话 ID 与输入拼接返回，方便离线验证插件链路。

### 入口点的三种目标形式 {#entry-point-forms}

入口点可指向模块、实例或类（工厂函数）：

| 目标写法 | 注册对象 | 适用场景 |
| --- | --- | --- |
| `bub_myplugin.plugin` | 模块 | Hook 均为无状态的普通函数 |
| `bub_myplugin.plugin:plugin` | 已有实例 | 多个 Hook 需要通过 `self` 共享内部状态 |
| `bub_myplugin.plugin:MyPlugin` | 类或工厂函数 | 插件初始化时需要访问 `BubFramework` 实例 |

当入口点指向类或工厂函数时，Bub 会在实例化时自动传入当前 `BubFramework`：

```python
from bub import BubFramework, hookimpl

class MyPlugin:
    def __init__(self, framework: BubFramework) -> None:
        self.framework = framework

    @hookimpl
    def build_prompt(self, message, session_id, state):
        return f"当前工作区路径：{self.framework.workspace}\n{message}"
```

## 安装与验证 {#install-and-run}

写完插件后，把它安装到 Bub 所在的虚拟环境中，然后验证 Hook 是否正常加载并生效。

### 本地开发安装 {#local-install}

在插件根目录下安装到当前虚拟环境：

```bash
uv sync
```

### 检查注册状态 {#check-hook-registration}

运行 `bub hooks` 确认插件已被发现：

```bash
uv run bub hooks
```

输出中的 `run_model` 行应包含 `echo`。

### 运行测试 {#run-tests}

现在可以向应用发送一条测试消息，看看插件是不是已经生效了：

```bash
uv run bub run "hello from my plugin"
```

终端会输出被插件拦截后的回声文本：

```text
[echo:cli:local] hello from my plugin
```

### 排查加载与执行顺序 {#troubleshooting-and-dispatch}

若插件未生效，请依次检查：

1. **Python 环境一致**：确认运行 `bub` 的环境与安装插件的虚拟环境相同；
2. **刷新入口点元数据**：修改 `pyproject.toml` 的 `entry-points` 后，需重新执行 `uv sync` 或 `pip install -e .`；
3. **Hook 优先级**：Bub 先注册内置实现（`builtin`），再加载第三方插件。同优先级下**后注册的插件先执行**（LIFO）。可通过 `@hookimpl(tryfirst=True)` 或 `@hookimpl(trylast=True)` 显式调整顺序，详见 [Hooks 参考：执行优先级](/zh-cn/docs/reference/hooks/#priority-and-dispatch)。

## 常用 Hook 写法 {#advanced-hooks}

Bub 提供了一整套覆盖入站解析、模型调用、工具拦截、状态与生命周期的扩展点（全部 27 个 Hook 的完整签名见 [Hooks 参考](/zh-cn/docs/reference/hooks/)）。日常开发中最常用的扩展可以分为下面四类：

### 1. 提供工具 {#provide-tools}

通过 `provide_tools` 注册由 `@tool` 装饰的工具函数：

```python
from bub import hookimpl, tool
from bub.core.tools import Tool

@tool(name="orders.get")
def get_order(order_id: str) -> dict[str, str]:
    """根据订单 ID 查询发货状态。"""
    return {"id": order_id, "status": "shipped"}

class OrdersPlugin:
    @hookimpl
    def provide_tools(self) -> list[Tool]:
        return [get_order]
```

#### 延迟加载工具 Schema {#deferred-loading}

若插件提供大量工具，一次性将全部 Schema 注入系统提示词会占用过多上下文。可设置 `deferred=True`：

```python "deferred=True"
@tool(name="orders.export", deferred=True)
def export_orders(format: str) -> str:
    """导出历史订单报表。"""
    ...
```

带有 `deferred=True` 的工具初始仅向模型展示名称和简短描述；当模型需要调用它时，会自动先调用内置的 `tool.describe` 加载完整参数定义，并在下一步发起调用。

### 2. 改写提示词、拦截调用与保存状态 {#rewrite-and-intercept}

#### 改写提示词 {#change-the-prompt}

- **改写本轮用户输入**（`build_prompt`）：
  ```python
  from bub import hookimpl
  from bub.envelope import content_of

  @hookimpl
  def build_prompt(message, session_id, state):
      text = content_of(message)
      return [f"请使用项目术语回答：\n\n{text}"]
  ```

- **追加系统提示词**（`system_prompt`，多个插件的返回值会按优先级换行拼接）：
  ```python
  @hookimpl
  def system_prompt(prompt, state):
      return "请在回复末尾附上参考的代码文件路径。"
  ```

#### 拦截模型或工具调用 {#control-a-model-or-tool-call}

拦截 Hook 在调用执行前触发。注意：在拦截 Hook 中抛异常只会被记录日志并跳过，**不能阻止调用执行**；如需修改参数或拒绝调用，必须返回对应的决策对象：

- **修改模型请求参数**（`before_llm_call`）：
  ```python
  from dataclasses import replace
  from bub import hookimpl
  from bub.hooks.interception import LLMCallRequest

  @hookimpl
  def before_llm_call(request: LLMCallRequest, state):
      max_tokens = min(request.max_tokens or 512, 512)
      return replace(request, max_tokens=max_tokens)
  ```

- **审批或拒绝工具调用**（`before_tool_call`）：
  ```python
  from bub import hookimpl
  from bub.hooks.interception import ToolCall, ToolCallDecision

  @hookimpl
  def before_tool_call(call: ToolCall, state):
      if call.tool == "orders.cancel" and not state.get("can_cancel_orders", False):
          return ToolCallDecision.deny("当前会话无权撤单。")
      return None
  ```

决策语义见[调用前拦截与控制](/zh-cn/docs/concepts/events/#call-control)，返回类型见 [`ToolCallDecision`](/zh-cn/docs/reference/hooks/#toolcalldecision)。

#### 记录调用耗时与审计日志 {#observe-completed-calls}

完成类 Hook 在调用结束后触发，适合统计耗时、上报指标或记录审计日志：

```python
from bub import hookimpl

@hookimpl
def after_llm_call(request, result, state):
    print(f"model={request.model} error={result.error!r} elapsed={result.duration_ms}ms")

@hookimpl
def after_tool_call(call, result, state):
    print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms")
```

#### 跨 Turn 保存应用状态 {#keep-application-state-across-turns}

使用 `load_state` 和 `save_state` 在多个 Turn 之间读写应用状态（状态边界见 [TurnState](/zh-cn/docs/concepts/turn/#state)）：

```python
import asyncio
from bub import hookimpl

class TurnCounter:
    def __init__(self) -> None:
        self.counts: dict[str, int] = {}
        self.lock = asyncio.Lock()

    @hookimpl
    async def load_state(self, message, session_id):
        async with self.lock:
            return {"completed_turns": self.counts.get(session_id, 0)}

    @hookimpl
    async def save_state(self, session_id, state, message, model_output):
        async with self.lock:
            self.counts[session_id] = state.get("completed_turns", 0) + 1

turn_counter = TurnCounter()
```

### 3. 挂载服务与存储资源 {#services-and-resources}

#### 常驻后台服务 {#lifecycle}

MCP 客户端、外部通道或定时任务等常驻组件，可继承 `Lifecycle` 并通过 `provide_channels` 注册：

```python
from bub.channels.base import Lifecycle

class MyRuntime(Lifecycle):
    name = "myapp.lifecycle"

    async def start(self, stop_event) -> None:
        await self._connect(stop_event)

    async def stop(self) -> None:
        await self._close()
```

- `Lifecycle` 服务会在 `bub chat` 和 `bub gateway` 启动时自动运行，退出时清理；单次执行的 `bub run` 不会启动它。
- 可通过 `--enable-channel '!myapp.lifecycle'` 在启动时排除指定服务。

#### 进程级共享资源 {#runtime-resources}

使用 `provide_lifespan` 异步生成器管理数据库连接池或共享 HTTP 客户端（覆盖整个 `framework.running()` 周期）：

```python
from bub import hookimpl

@hookimpl
async def provide_lifespan():
    client = await connect_database()
    try:
        yield
    finally:
        await client.close()
```

#### 替换会话存储 {#provide-a-tape-store}

通过 `provide_tape_store` 替换默认的本地文件存储（见[使用数据库存储会话历史](/zh-cn/docs/integrations/storage/)）：

```python
from pathlib import Path
from bub import hookimpl
from bub.core.store import FileTapeStore

@hookimpl
def provide_tape_store():
    return FileTapeStore(Path("./application-tapes"))
```

### 4. 注册 CLI 子命令 {#add-an-application-command}

通过 `register_cli_commands` 向 `bub` 注册自定义子命令：

```python
import typer
from bub import hookimpl

@hookimpl
def register_cli_commands(app: typer.Typer):
    @app.command()
    def my_cmd(name: str = "world") -> None:
        typer.echo(f"执行成功：{name}")
```

#### 终端交互式输入 {#prompt-for-input}

在自定义 CLI 命令中向用户请求输入或确认时，可使用 `bub.inquirer`：

```python
from bub.inquirer import ask_confirm, ask_text

token = ask_text("请输入验证 Token")
if ask_confirm("确认继续执行？", kind="permission"):
    pass
```

## 分发与跨语言扩展 {#share-a-plugin}

### 打包分发 {#package-and-distribute}

插件可打包为标准 Python Wheel 分发，并同时包含入口点、技能和自定义 CLI 命令，详见[打包与分发](/zh-cn/docs/app/distribution/)。跨平台的声明式插件规范见[使用 Agent Plugins](/zh-cn/docs/integrations/agent-plugins/)。

### WASM 插件（实验性） {#wasm-plugins}

借助 [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism)，可将 Go、Rust 等语言编译的 WebAssembly 模块挂载为 Bub Hook：

```json title="extism.json"
{
  "plugins": {
    "prompt": {
      "manifest": { "wasm": [{ "path": "go-build-prompt.wasm" }] },
      "wasi": true,
      "hooks": { "build_prompt": "build_prompt" }
    }
  }
}
```

```bash
export BUB_EXTISM_CONFIG_PATH=./extism.json
bub run "Say hello from a prompt built outside Python."
```