工具系统位于 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)
每个工具包含:
ToolDefinition — 工具名称、描述、参数 JSON SchemaHandler — 实际执行函数{
"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"]
}
}
{
"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"]
}
}
{
"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 都遵循「先全部校验,再落盘」:
parallel_edit_files:edits 数组中每一项按 path / old_string / new_string /
replace_all 描述;先对每个文件在内存中累积替换结果,任一项 old_string 缺失或
匹配多次(且未设 replace_all)则整体失败、不写任何文件;全部通过后逐文件写入,
并触发 filehistory 备份与代码图 MarkDirty()。import_patch:读取补丁文件并复用 apply_patch 的解析/预检逻辑,check_only: true
时只校验不落盘。两者在 plan 模式下都被拦截,且在循环守卫中计为状态变更工具。
recall 在已保存会话中做大小写不敏感的子串检索,返回命中消息所在会话 id、
角色与上下文片段;limit(默认 10)、session(前缀匹配)、max_sessions
(默认 50,最新优先)可收窄范围。list_sessions 列出会话 id 简写、标题、消息数与更新时间,当前会话前标 *。memory 与 TUI 的 /remember /forget /memory 共用同一存储:scope=project
写 <workspace>/.opentmd/memory.md,scope=global 写 ~/.opentmd/memory.md。ask_user 通过宿主注入的 AskHandler(tool.Options.OnAsk)向用户提问,可带
options 与 default。TUI 已接线:问题以模态框呈现(internal/tui/ask.go),
有 options 时用 ↑/↓ 或数字键选择,否则直接输入;Esc 跳过。
没有前端注入 handler 时(headless / daemon):给了 default 就返回默认答案,
否则返回「无交互用户,请自行判断」而不是报错,以免模型卡死。report_finding 记录一条审查发现(severity 取 critical|high|medium|low,
默认 medium),在会话内累积;Agent.Findings() / FindingsSummary() 供上层渲染,
Runtime 内部用互斥锁保护追加。
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
error: … 作为工具结果回传给模型,并照常执行 Post 钩子。Runtime.Use(mw) 在内层追加自定义中间件;链的声明顺序即外层到内层(第一个最先看到调用)。Registry 用 parallel 覆盖表 + defaultParallelSafe 白名单标记只读工具;Runtime.SafeToRunConcurrently(call) 额外要求该调用在当前模式启用且权限为 AutoApprove。Agent 只在整批调用都安全时并发执行(internal/agent/tool_exec.go),否则退回串行;结果始终按原始调用顺序写回,loop guard 与步数预算也在回收后按序记账。未知工具和 MCP 工具默认不并行。
工具定义通过 ChatRequest.Tools 发送给 LLM,模型返回 tool_calls 指明要调用的工具和参数。
repair.rs)Runtime.Execute 在 hooks 与权限检查之前调用 RepairToolArgs(internal/tool/jsonrepair.go),依次尝试:
D:\test 中的 \t 不被当作制表符)\. \()、字符串内的控制字符、截断输出(补全引号与括号)edit_file 专用提取"key": value 字段提取超过 512KB 的参数不做修复,原样返回。
/toolbox)Registry.SetToolEnabled(pattern, enabled) 按名称批量启用/禁用工具,pattern 走
path.Match 通配(额外支持 * 全匹配,且始终按全名精确匹配兜底),返回受影响数量。
兼容别名 run_shell / list_dir 不参与开关,始终跟随 bash / list_directory。
Registry.Definitions() 不再下发该工具,Execute() 直接返回
tool "x" is disabled (re-enable it with /toolbox on x),避免模型调用已隐藏的工具。DisabledTools() 返回当前被隐藏的工具名(已排序),供 /toolbox list 显示。offPatterns 记录被关闭的模式,便于在 /toolbox all 时整体恢复。/toolbox 是「按名字隐藏」,在 Registry 层生效;
plan 模式是「按工具类型隐藏」,在 Runtime.Definitions() 里再过滤一遍
(内置工具查静态表,MCP 工具仅当其声明 readOnlyHint 且非 destructiveHint 时放行)。
Runtime.Execute 也会在 plan 模式下拦截 planBlocked 的工具,因此即使模型凭记忆
调用了未下发的工具,也不会真正落地。可通过 r.Register() 注册自定义工具,只需提供 ToolDefinition + Handler 函数。
internal/tool/coerce.go 的 CoerceArgsToSchema 在 JSON 修复之后、Hook/权限之前运行:按工具 schema,把被模型字符串化的数组/对象/整数/数字/布尔还原为真实类型;字符串字段与无法解析的值保持原样。
internal/tool/artifact.go):非自限输出的工具结果超过 50 KiB 时,完整内容存到 $TMPDIR/opentmd-artifacts/<id>,返回 32 KiB 头 + 12 KiB 尾 + fetch_output 提示;超过 4 MiB 只内联截断。fetch_output(artifact_id, offset, limit≤64KiB) 按字符边界分页,artifact_id 限 16 位十六进制防路径穿越。read_file / fetch_output / read_symbol 自带分页,不截断。apply_patch(internal/tool/patch.go):git apply --check 预检通过后才真正应用,任何 hunk 失败则不改任何文件;check_only 只校验。需审批,/plan 下禁用。git_status:分支、变更文件与 diff --stat。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)find_references / trace_callers 在同名定义多于一个时,按 distanceScore 选择最近定义:同文件 4 → 同目录(同包)2 → 同顶层目录 1 → 其他 0;平分按 (file, line) 确定性排序,输出 -> file:line。maxIndexFiles=20000、maxIndexBytes=64MiB;超限时构建失败,查询返回 code graph unavailable: … (use grep/glob instead),不返回部分图。.go 文件的 (size, mtime) 指纹,最多每 2 秒巡检一次;IDE 保存后下一次查询自动重建,不依赖 MarkDirty。.opentmd/graph.gob;加载缓存后首次查询会补一次重建以建立指纹。