# 内置工具

本页列出 Bub 应用层自带的全部内置工具与会话命令。

- **名称转换**：工具暴露给模型时，名称中的点号会自动转换为下划线别名（如 `fs.read` 在模型侧为 `fs_read`）；在终端用命令前缀（如 `,fs.read path=README.md`）直接调用时保留原名。
- **文本命令传参**：支持位置参数和 `key=value` 键值对；布尔值写 `true` / `false`，列表写 JSON 字符串，含空格的值用引号包裹：
  ```text
  ,bash command='printf "hello world"' timeout_seconds=10
  ,tool.describe names='["web.fetch", "tape.search"]'
  ```
- **执行环境**：`fs.*`、`bash*` 和 `run_code` 均通过当前会话的 `Environment` 执行，默认直接在宿主机当前用户权限下运行（无安全沙箱）。

## 进程管理 {#processes}

### `bash` {#bash}

```text
bash(command, cwd=None, timeout_seconds=30, background=False)
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `command` | `str` | 要执行的 Shell 命令 |
| `cwd` | `str \| None` | 工作目录；相对路径基于当前会话的 `Environment.workspace` 解析 |
| `timeout_seconds` | `float` | 前台等待秒数（默认 30）；超时未结束时不会报错，而是自动转为后台继续运行并返回 `shell_id` |
| `background` | `bool` | 是否直接在后台启动；设为 `True` 时立即返回 `shell_id` 并忽略 `timeout_seconds` |

前台命令退出码非零时作为工具错误返回（保留已打印输出）；正常退出且无输出时返回 `(no output)`。

### `bash.output` {#bash-output}

```text
bash.output(shell_id, offset=0, limit=None)
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `shell_id` | `str` | `bash` 返回的后台进程 ID（如 `bsh-12345678`） |
| `offset` | `int` | 起始**字符偏移量**（非行号，自动限制在 `0` 到当前缓冲总长度之间） |
| `limit` | `int \| None` | 本次最多读取的字符数 |

返回进程状态 `status`、退出码 `exit_code`（运行中为 `null`）、本次输出 `output` 以及供下次读取使用的 `next_offset`。

### `bash.kill` {#bash-kill}

```text
bash.kill(shell_id)
```

终止指定的后台 Shell 进程，并返回其最终状态与退出码。

## 文件操作 {#files}

### `fs.read` {#fs-read}

```text
fs.read(path, offset=0, limit=None)
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `path` | `str` | 文件路径 |
| `offset` | `int` | 起始行号（从 `0` 开始，默认 `0`） |
| `limit` | `int \| None` | 最多读取的行数（省略时读到文件末尾） |

除读取 UTF-8 文本文件外，当 `path` 指向 `.png`、`.jpg`、`.jpeg`、`.webp` 或 `.gif` 图片（且不超过 10 MiB）时，会作为多模态图片对象返回给模型（此时忽略 `offset` 和 `limit`）。

### `fs.write` {#fs-write}

```text
fs.write(path, content)
```

将完整的 UTF-8 文本写入 `path`（自动创建缺失的父目录；已存在的文件会被直接覆盖）。

### `fs.edit` {#fs-edit}

```text
fs.edit(path, old, new, start=0)
```

从第 `start` 行（从 `0` 开始）起，将文件中所有与 `old` 完全匹配的字面文本替换为 `new`；未找到匹配项时返回工具错误。

## 网页抓取 {#web}

### `web.fetch` {#web-fetch}

```text
web.fetch(url, headers=None, timeout=10)
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `url` | `str` | 目标 HTTP/HTTPS URL |
| `headers` | `dict \| None` | 自定义请求头（可覆盖默认的 `Accept: text/markdown`） |
| `timeout` | `float` | 请求总超时秒数（默认 10） |

发送 HTTP GET 请求并返回最终 `url`、状态码 `status`、`content_type` 和响应正文（非 2xx 状态码返回工具错误）。

## 技能与工具发现 {#discovery}

### `skill` {#skill}

```text
skill(name=None)
```

省略 `name` 时列出所有可用技能及简述；传入 `name` 时返回该技能的路径与变量展开后的 `SKILL.md` 正文（不存在时返回 `(no such skill)`）。

### `tool.describe` {#tool-describe}

```text
tool.describe(names)
```

加载延迟工具（`deferred=True`）的完整描述与 JSON Schema 参数定义。成功加载的工具从**下一个 Step** 起即可被模型调用，并在当前会话 Tape 重置前保持已加载状态（未知名称列入 `unknown`，已加载名称列入 `already_loaded`）。

## 会话 Tape 管理 {#tape}

### `tape.info` {#tape-info}

无参数。返回当前会话的物理 Tape 名称、总条目数（`entries`）、锚点总数（`anchors`）、最近一个锚点（`last_anchor`）、自该锚点以来的条目数（`entries_since_last_anchor`），以及最近一次模型调用的 Token 用量与缓存命中率。

### `tape.search` {#tape-search}

```text
tape.search(query, limit=20, start=None, end=None, kinds=["message", "tool_result"])
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `query` | `str` | 搜索关键词（不区分大小写；内置 `FuzzyFileTapeStore` 对 3 字符以上查询支持模糊匹配并按倒序去重） |
| `limit` | `int` | 最多返回条数（默认 20） |
| `start` / `end` | `str \| None` | 可选的起止 ISO 日期或时间范围（含边界） |
| `kinds` | `list[str]` | 要检索的条目类型列表 |

返回匹配条目列表 `matches` 和被过滤的重复/自身输出计数 `filtered`。

### `tape.anchors` {#tape-anchors}

无参数。按写入顺序列出当前会话 Tape 中的所有 anchor 名称（无 anchor 时返回 `(no anchors)`）。

### `tape.handoff` {#tape-handoff}

```text
tape.handoff(name="handoff", summary="")
```

向当前会话 Tape 追加一个名为 `name` 的新 anchor（`summary` 保存在 `state.summary` 中），将默认模型上下文的读取起点前移到此处。不会自动调用模型生成摘要。

### `tape.reset` {#tape-reset}

```text
tape.reset(archive=False)
```

清空当前会话 Tape 并写入新的 `session/start` 锚点。`archive=True` 时会在清空前将主 Tape 和 Sidecar 备份到 `<BUB_HOME>/tapes/`（带 UTC 时间戳和 `.bak` 后缀）。

## 子 Agent {#subagent}

### `subagent` {#subagent-tool}

```text
subagent(prompt, agent=None, description=None, model=None, reasoning_effort=None,
         session="temp", allowed_tools=None, allowed_skills=None, timeout_seconds=None)
```

| 参数 | 类型与默认值 | 说明 |
| --- | --- | --- |
| `prompt` | `str \| list`（必填） | 委派给子 Agent 的任务指令 |
| `agent` | `str \| None`（`None`） | 要使用的[子 Agent Profile](/zh-cn/docs/app/subagents/#profiles) 名称；调用中显式传入的参数优先于 Profile |
| `description` | `str \| None`（`None`） | 任务简短标签；默认取 `prompt` 第一行 |
| `model` | `str \| None`（`None`） | 子 Agent 模型（`provider:model`）；默认取 Profile 模型或父 Agent 模型 |
| `reasoning_effort` | `str \| None`（`None`） | 子 Agent 推理强度 |
| `session` | `str`（`"temp"`） | 会话模式：`"temp"`（新建空白临时会话，结束后丢弃）、`"fork"` / `"inherit"`（复制调用时的对话快照，结束后丢弃）或自定义固定会话 ID（结束后保留） |
| `allowed_tools` | `list[str] \| None`（`None`） | 允许使用的工具列表（不能超出父 Agent 本轮可用工具；子 Agent 始终不能再调用 `subagent*`） |
| `allowed_skills` | `list[str] \| None`（`None`） | 允许使用的技能列表（不能超出父 Agent 范围；传 `[]` 禁用技能） |
| `timeout_seconds` | `int \| None`（`None`） | 超时秒数；默认先取 Profile 时限，再取 `BUB_SUBAGENT_TIMEOUT_SECONDS` |

`subagent` 在后台异步启动子任务，立即返回 `task_id` 与初始状态（`queued` 或 `running`）。当子任务结束时，父 Agent 会在下一步前收到 `<subagent-notification>` 消息（仅含子 Agent 最后一步的最终回答）。只要父 Agent 启动的子任务尚未全部结束，当前运行就会等待所有子任务完成后再结束。

### `subagent.wait` {#subagent-wait}

```text
subagent.wait(task_ids=None, timeout_seconds=60)
```

等待并读取子任务结果（`task_ids` 省略时覆盖当前会话所有未读子任务；`timeout_seconds=0` 时仅查询状态不阻塞）。已被 `subagent.wait` 读取的结果不再发送 `<subagent-notification>`。

### `subagent.send` {#subagent-send}

```text
subagent.send(task_id, message)
```

向运行中的子任务追加指令（在下一步前生效），或唤醒已结束的自定义命名会话子任务继续工作（已结束的 `temp` / `fork` 任务不可继续）。

### `subagent.cancel` {#subagent-cancel}

```text
subagent.cancel(task_id)
```

终止运行中的子任务，状态置为 `cancelled` 并保留已产生的部分输出。

### 子 Agent 事件 {#subagent-events}

子任务在 `agent.events` 上发布以下事件（定义于 `bub.builtin.subagents`，均携带 `event.task: SubagentTask`）：

| 事件类 | 触发时机 |
| --- | --- |
| `SubagentStarted` | 子任务离开队列、开始执行时 |
| `SubagentOutput` | 子任务每产出一条 `StreamEvent` 时（保存在 `event.event`） |
| `SubagentFinished` | 子任务以 `completed`、`failed` 或 `cancelled` 结束时 |

## 代码模式与大输出转存（Spill） {#code-and-spill}

### `run_code` {#run-code}

```text
run_code(code, timeout_seconds=120)
```

在代码模式开启时执行 Python 代码。代码内通过 `await tools.<name>(key=value)`（关键字参数）调用其他工具；只有 `print()` 输出和显式附加的媒体会进入返回结果。

### `attach_image` / `attach_audio` / `attach_video` {#attach-media}

```text
attach_image(image)
attach_audio(audio)
attach_video(video)
```

将 Republic 媒体对象、本地文件路径或 URL 附加到当前 `run_code` 的返回结果中（`exposure="code"`，仅可在 `run_code` 内调用）。

### `spill.read` {#spill-read}

```text
spill.read(handle, cursor=0, count=1, from_end=False)
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `handle` | `str` | 工具输出预览中给出的 spill 句柄 ID |
| `cursor` | `int` | 起始分块游标 |
| `count` | `int` | 本次连续读取的分块数（单次最多 4 块） |
| `from_end` | `bool` | 是否从末尾倒序读取 |

返回 `next_cursor` 和 `complete`（是否已读到边界）。转存阈值由 [`BUB_SPILL_THRESHOLD`](/zh-cn/docs/reference/settings/#spill-settings) 控制。

## 会话控制命令 {#session-commands}

以下工具的 `exposure="command"`，仅可通过命令前缀（默认 `,`）直接调用，不暴露给模型：

| 命令 | 参数 | 作用 |
| --- | --- | --- |
| `,help` | 无 | 列出可用内部命令与命令前缀 |
| `,model` | `model_id` | 切换当前会话从下一次 Turn 起使用的模型（保存在 Tape 中） |
| `,reasoning_effort` | `reasoning_effort` | 设置当前会话从下一次 Turn 起的推理强度 |
| `,code_mode` | `enable=true` / `false` | 开启或关闭当前会话的代码模式（从下一次 Turn 起生效） |
| `,quit` | 无 | 清空当前会话的待处理消息队列、取消运行中的子任务并终止后台 Shell 进程 |