opentmd

工具系统

概述

工具系统位于 internal/tool/,实现 Agent 的工具注册与执行机制,支持 Function Calling。

核心结构

type Handler func(ctx context.Context, args json.RawMessage) (string, error)

type Registry struct {
    mu          sync.RWMutex
    workDir     string
    tools       map[string]toolEntry
    parallel    map[string]bool // 显式覆盖并行安全
    disabled    map[string]bool // /toolbox off
    offPatterns []string        // 便于 /toolbox all 恢复
    beforeWrite func(path string) error // filehistory 备份
}

type toolEntry struct {
    def    llm.ToolDefinition
    handle Handler
}

Runtime 在 Registry 之上叠加 permission、hook、skills、mcp、graph、lsp、filehistory,并以 []ToolMiddleware 组织执行顺序。

注册机制

NewRegistry(workDir) 初始化并注册默认工具:

r.Register(llm.ToolDefinition{...}, handler)

每个工具包含:

内置工具

1. read_file — 读取本地文件

{
  "name": "read_file",
  "description": "Read the contents of a local file. Large files are truncated.",
  "parameters": {
    "type": "object",
    "properties": {
      "path": {
        "type": "string",
        "description": "File path relative to the project root or absolute path"
      }
    },
    "required": ["path"]
  }
}

2. bash — 执行 Shell 命令

{
  "name": "bash",
  "description": "Run a shell command in the project directory. Use for tests, builds, git, etc.",
  "parameters": {
    "type": "object",
    "properties": {
      "command": {"type": "string", "description": "Shell command"}
    },
    "required": ["command"]
  }
}

3. list_directory — 列出目录内容

{
  "name": "list_directory",
  "description": "List files and directories in a path.",
  "parameters": {
    "type": "object",
    "properties": {
      "path": {"type": "string", "description": "Directory path (default: project root)"}
    }
  }
}

run_shell 与 list_dir 是 bash / list_directory 的兼容别名(仅为执行兼容): Definitions() 不会下发别名,审批、权限规则与默认并行标记都按主名处理。

内置工具清单

除上面三个完整示例外,其余工具只在此列出用途,参数 schema 以 internal/tool/registry.go 的注册为准(/tools 可查看当前会话实际可见的工具)。

分类 工具 用途
文件 write_file edit_file search_replace 创建 / 单文件精确替换 / 多文件批量替换
文件 apply_patch 应用 git 格式 unified diff,预检失败不落盘
文件 open_file 用系统默认程序打开文件 / 目录 / URL,需审批
搜索 grep glob 正则搜内容 / 按模式找文件
搜索 ast_grep 结构化(AST)搜索:$NAME / $$$ARGS / $_ 元变量,可选 rewrite 预览改写
Shell bash bash_start bash_poll bash_kill 同步执行 / 后台任务三件套
Shell pwsh 显式执行 PowerShell(Unix pwsh / Windows powershell),仅在依赖 PS 语法时使用
版本控制 git_status 分支、变更文件、diff stat
输出 fetch_output 分页读取被外存的大输出
符号 list_symbols read_symbol tree-sitter 符号索引与按名读取源码
代码图 trace_callers trace_callees trace_chain find_references blast_radius file_dependencies Go 调用关系与影响面
诊断 diagnostics LSP 实时错误 / 告警
联网 web_search web_fetch DuckDuckGo 搜索 / 抓取公开 URL(含 SSRF 防护)
编排 task todo todowrite use_skill list_skills 子 Agent 委派 / 任务清单(todowrite 为 atomcode 拼写别名)/ 加载 Skill 模板 / 列出 Skills 而不展开
批处理 parallel_edit_files import_patch 多处替换一次性全成或全不成 / 应用补丁文件中的 unified diff
会话回溯 recall list_sessions 按关键字检索历史会话消息 / 列出已保存会话
记忆 memory 读写持久记忆(action=add\|list\|forget,scope=global\|project)
待办扫描 todo_sources 扫描 TODO/FIXME/HACK/XXX 标记(file:line: 文本,可用 pattern 收窄)
项目概览 repo_architecture 语言构成、清单文件、入口点与目录树(探索陌生仓库的第一站)
交互 ask_user report_finding 向用户提问并等待回答 / 记录代码审查发现(分级)
定时 schedule_create schedule_list schedule_update schedule_delete 持久定时任务(~/.opentmd/schedule.json)
自省 describe_self 当前装配(模型、模式、可见工具、Skills、MCP、Rules、Agents、记忆与会话路径)
外部 mcp__<server>__<tool> MCP 工具,需审批,默认不并行

权限分级速查

internal/permission 的 Classify 决定每个工具默认是否需要审批([permissions] 规则可再收紧或放宽,deny 始终优先):

级别 工具
免审批(只读,多数可并行) read_file grep glob list_directory ast_grep todo_sources list_symbols read_symbol list_skills describe_self fetch_output
需审批(状态变更) write_file edit_file search_replace apply_patch parallel_edit_files import_patch bash run_shell bash_start pwsh open_file schedule_create schedule_update schedule_delete、memory(action=add\|forget)
始终审批 写工作区外路径、危险 shell 命令
MCP mcp__* 默认需审批、不并行;声明 readOnlyHint 且非 destructiveHint 时免审批、plan 模式可调用且可并行

memory 的只读动作(list)与交互类工具(ask_user、report_finding)免审批。

describe_self(internal/agent/self.go)是只读工具且标记为并行安全:它把 「本轮真实生效的装配」告诉模型,避免把易过时的能力清单写死进系统提示词。 它在 plan 模式下仍可见。

批处理与原子性

parallel_edit_files 与 import_patch 都遵循「先全部校验,再落盘」:

两者在 plan 模式下都被拦截,且在循环守卫中计为状态变更工具。

会话回溯与记忆

交互类工具

report_finding 的结果通过 Agent.Findings() / FindingsSummary() 取用,TUI 里用 /findings 打印。recall / repo_architecture 也有对应的 /recall、/architecture。 daemon 侧未接线 ask_user(走「无 handler」分支:有 default 用默认值,否则让模型自行判断)。

工具执行流程

Agent 检测到 Tool Call
    ↓
解析 ToolCall.Name + Arguments (JSON)
    ↓
Registry.Execute(name, args)
    ↓
查找注册的 Handler
    ↓
执行 Handler
    ↓
返回结果字符串

执行中间件链(middleware.go)

Runtime.Execute 不再是一条直线,而是固定顺序的 ToolMiddleware 链:

plan mode 拦截
  → 参数修复 + schema 类型纠正
  → PreToolUse hooks(可改写参数)
  → 权限规则 / 审批
  → 执行 handler
  → 大输出外存、LSP 通知、代码图标脏、PostToolUse hooks

并发执行与并行安全

Registry 用 parallel 覆盖表 + defaultParallelSafe 白名单标记只读工具;Runtime.SafeToRunConcurrently(call) 额外要求该调用在当前模式启用且权限为 AutoApprove。Agent 只在整批调用都安全时并发执行(internal/agent/tool_exec.go),否则退回串行;结果始终按原始调用顺序写回,loop guard 与步数预算也在回收后按序记账。未知工具和 MCP 工具默认不并行。

集成 LLM

工具定义通过 ChatRequest.Tools 发送给 LLM,模型返回 tool_calls 指明要调用的工具和参数。

工具参数 JSON 修复(对齐 atomcode repair.rs)

Runtime.Execute 在 hooks 与权限检查之前调用 RepairToolArgs(internal/tool/jsonrepair.go),依次尝试:

  1. Windows 路径预转义(D:\test 中的 \t 不被当作制表符)
  2. 原样合法则直接返回
  3. 单遍扫描修复:代码围栏、尾逗号、单引号字符串、无引号 key、缺失逗号、非法转义(\. \()、字符串内的控制字符、截断输出(补全引号与括号)
  4. edit_file 专用提取
  5. 兜底 "key": value 字段提取

超过 512KB 的参数不做修复,原样返回。

工具的启用与禁用(/toolbox)

Registry.SetToolEnabled(pattern, enabled) 按名称批量启用/禁用工具,pattern 走 path.Match 通配(额外支持 * 全匹配,且始终按全名精确匹配兜底),返回受影响数量。 兼容别名 run_shell / list_dir 不参与开关,始终跟随 bash / list_directory。

扩展性

可通过 r.Register() 注册自定义工具,只需提供 ToolDefinition + Handler 函数。

Schema 类型纠正

internal/tool/coerce.go 的 CoerceArgsToSchema 在 JSON 修复之后、Hook/权限之前运行:按工具 schema,把被模型字符串化的数组/对象/整数/数字/布尔还原为真实类型;字符串字段与无法解析的值保持原样。

大输出外存与补丁工具

后台任务

bash_start / bash_poll / bash_kill(internal/tool/jobtools.go + internal/shell/jobs.go):长命令(dev server、watcher、慢构建)放后台运行,返回 job_id: bg-N。每个任务输出环形缓冲 256 KiB(丢最旧),最多 64 个运行中任务;bash_poll 返回自上次以来的新输出与 status: running | exited (code N) | killed,wait_until=exit|output + wait_ms(≤60000)可阻塞等待;kill 终止整个进程组(Unix)。bash_start 与 bash 共用危险命令分类与 permissions 规则,/plan 下禁用,退出时自动清理。

代码图(internal/graph)