工具 —— 注册表、校验,和一把写锁
E03 结束时 tools: [],模型只会说话。可是工具执行这段代码,从 E01 起就一直
挤在 loop.ts 里:找工具、try/catch、拼消息,26 行,和循环的节奏缠在一起。
这一章把它搬出来,顺便回答三个一直没有答案的问题:
- 模型给了一个不存在的工具名,或者参数类型不对,谁来报错?
- 一轮里有三个工具调用,为什么不能让它们排队等?
- 既然并发,两个工具同时写同一个文件,谁赢?
loop.ts 的职责 tools.ts 的职责 --------------- ---------------- 轮次、退出、消息 -> runTools() |-- 找不到工具 -> isError: true |-- 参数不对 -> isError: true |-- 执行抛错 -> isError: true '-- write 同一路径 -> withFileLock一、本章终点:先跑起来
cd examples/mini-agentnode src/demo-tools.ts不加锁: A@47ms C@47ms B@48ms加锁 : A@42ms B@89ms C@155ms文件里最后留下: Cok c1 wrote 5 chars to tmp-e04.txterr c2 未知工具:nopeerr c3 text 应该是 string,收到 number前两行是同一件事的两种做法:三个 30ms 的写任务同时出发,不加锁时几乎同时落地 (47/47/48),加锁后是一个接一个(42/89/155,间隔≈45ms)。第三行是并发的代价: 最后落地的那个决定文件内容,而「最后」在并发下是不确定的。
| 文件 | 行数 | 本章变化 |
|---|---|---|
src/tools.ts |
139 | 新增:注册表 + 校验 + 写锁 + 并发调度 |
src/loop.ts |
98 | 工具执行那段搬走(−14) |
src/demo-tools.ts |
52 | 新增:本章入口 |
| 合计 | 861 | E03 的 684 + 本章 177 |
二、先把执行搬出循环
E01 的 loop.ts 里,这一段有 26 行。它做了四件事:查表、发事件、执行、拼消息。
四件事里只有「拼消息」属于循环,其余三件属于工具层。所以先把 26 行换成 10 行:
<!-- file: examples/mini-agent/src/loop.ts -->
const results = await runTools(calls, options.tools, emit); for (const result of results) { errors = result.isError ? errors + 1 : 0; messages.push({ role: "tool", toolCallId: result.id, toolName: result.name, content: result.text, isError: result.isError, }); }runTools 返回的是一个数组,顺序和 calls 一样——这一点后面解释。
errors 的计数逻辑没变:连续三次失败才认输(MAX_TOOL_ERRORS)。
搬家的直接好处是:循环不再知道「工具可能不存在」「参数可能不对」「execute 可能 抛错」这三件事。它们是工具层的不变量,不该让每一层都记一遍。
三、工具层:139 行
<!-- file: examples/mini-agent/src/tools.ts -->
import { readFile, writeFile } from "node:fs/promises";import type { AgentEvent, Tool, ToolCallBlock } from "./types.ts";const MAX_CHARS = 4000;export const readTool: Tool = { name: "read", description: "读一个文本文件,返回前 4000 个字符。", parameters: { type: "object", properties: { path: { type: "string", description: "相对或绝对路径" }, }, required: ["path"], }, async execute(args) { const file = String(args.path ?? ""); if (!file) throw new Error("path 不能为空"); const text = await readFile(file, "utf8"); const body = text.length > MAX_CHARS ? text.slice(0, MAX_CHARS) : text; return `# ${file}(${text.length} 字符)\n${body}`; },};export const echoTool: Tool = { name: "echo", description: "原样返回传入的 text,用来验证工具通路。", parameters: { type: "object", properties: { text: { type: "string", description: "要回显的内容" }, }, required: ["text"], }, execute(args) { return `echo: ${String(args.text ?? "")}`; },};export const writeTool: Tool = { name: "write", description: "把 text 写入 path,返回写入的字符数。", parameters: { type: "object", properties: { path: { type: "string", description: "目标路径" }, text: { type: "string", description: "文件内容" }, }, required: ["path", "text"], }, async execute(args) { const file = String(args.path ?? ""); if (!file) throw new Error("path 不能为空"); const text = String(args.text ?? ""); /* 同一路径的写排队:并发调用时后到者等前一个落盘 */ return withFileLock(file, async () => { await writeFile(file, text, "utf8"); return `wrote ${text.length} chars to ${file}`; }); },};/** E01/E02 只用这两个;E03 才把 write 注册进来。 */export const baseTools: Tool[] = [readTool, echoTool];const locks = new Map<string, Promise<unknown>>();/** * 同一个 key 的任务排队执行:前一个不管成功失败,后一个才开始。 * 进程内锁,够挡住「同一轮里两个 write 抢一个文件」。 */export function withFileLock<T>( key: string, fn: () => Promise<T>,): Promise<T> { const prev = locks.get(key) ?? Promise.resolve(); const next = prev.then(fn, fn); locks.set( key, next.catch(() => {}), ); return next;}/** 参数校验:只查 required 与类型,不做 schema 全集。 */export function validateArgs( tool: Tool, args: Record<string, unknown>,): string | null { for (const name of tool.parameters.required) { if (!(name in args)) return `缺参数 ${name}`; } for (const [name, spec] of Object.entries(tool.parameters.properties)) { const value = args[name]; if (value === undefined) continue; if (typeof value !== spec.type) { return `${name} 应该是 ${spec.type},收到 ${typeof value}`; } } return null;}export interface ToolOutcome { id: string; name: string; text: string; isError: boolean;}/** 一轮里的所有工具调用并发跑,结果按原始顺序返回。 */export async function runTools( calls: ToolCallBlock[], tools: Tool[], emit: (event: AgentEvent) => void,): Promise<ToolOutcome[]> { const runOne = async (call: ToolCallBlock): Promise<ToolOutcome> => { const miss = (text: string): ToolOutcome => { emit({ type: "tool_end", id: call.id, isError: true }); return { id: call.id, name: call.name, text, isError: true }; }; emit({ type: "tool_start", id: call.id, name: call.name }); const tool = tools.find((item) => item.name === call.name); if (!tool) return miss(`未知工具:${call.name}`); const bad = validateArgs(tool, call.args); if (bad) return miss(bad); try { const text = await tool.execute(call.args); emit({ type: "tool_end", id: call.id, isError: false }); return { id: call.id, name: call.name, text, isError: false }; } catch (error) { const text = error instanceof Error ? error.message : String(error); return miss(text); } }; return Promise.all(calls.map((call) => runOne(call)));}前 60 行是工具定义,从 E01 就存在,这里只是加了锁。真正新的是后面 80 行。
四、锁:一条 promise 链
const prev = locks.get(key) ?? Promise.resolve();const next = prev.then(fn, fn);locks.set(key, next.catch(() => {}));return next;四行,值得逐行读。
prev 是「这个 key 上一次的任务」。 第一次调用时没有,就当成「已完成」。
prev.then(fn, fn) 里的两个 fn:成功也执行、失败也执行。如果写成
prev.then(fn),前一个写失败之后链就断了,后面的写永远不跑——你会看到「文件
没生成,也没有报错」,这是最难查的一类问题。
locks.set(key, next.catch(() => {})) 存的是「吞掉异常后的版本」。 目的是
让链不断,同时不制造 unhandled rejection。return next 返回的才是带异常的
原版,所以调用方仍然能拿到错误。
为什么要 .catch 而不是 .finally? finally 会把值也吞成 undefined,
下一环拿不到结果;我们只需要「错误不阻断链条」,不需要改结果。
再看实验数据:
不加锁: A@47ms C@47ms B@48ms加锁 : A@42ms B@89ms C@155ms文件里最后留下: C不加锁时三者的落地时刻几乎一样——它们真的在同时跑;加锁后间隔约 45ms(30ms 的 sleep + 开销),说明后一个在等前一个。判据不是「代码里有锁」,而是「时间被 拉开了」。
进程内锁的边界也要说清楚:它只挡同一个 Node 进程。两个 CLI 进程同时写一个文件, 它一点用都没有。那需要文件锁或原子重命名,属于另一章的事。
五、校验:模型给的参数永远别信
validateArgs 只做两件事:required 都在、类型对得上。不做嵌套、不做枚举、
不写完整的 JSON Schema。理由是:这一层的目标是「别把明显坏的参数喂给工具」,
不是「实现一个校验器」。工具自己仍然要检查语义(比如路径不能为空)。
真实输出里的第三行就是它:
err c3 text 应该是 string,收到 number注意报错文案里带上了「收到什么」——这是可修的报错和不可修的报错的分界。只写
「参数错误」,用户只能猜;写「收到 number」,他立刻知道模型把 "42" 写成了 42。
还有一个容易漏的点:校验失败不抛异常,而是返回一条 isError: true 的结果。
因为这是模型的问题,不是程序的问题。把它当异常抛,整个循环会崩;把它当消息
回给模型,它下一轮有机会自己改。
六、并发:Promise.all 为什么还能保序
return Promise.all(calls.map((call) => runOne(call)));Promise.all 返回的数组按输入顺序排列,不按完成顺序。这是规范行为,不是
实现巧合:下标是 promise 在数组里的位置。
所以模型看到的 tool 消息顺序和它发出的 toolCall 顺序一致——这对下一轮很关键。
多数 provider 要求 tool 结果紧跟在对应的 toolCall 后面,顺序错位就是 400。
代价是:一个慢工具会拖住整批的返回时刻,但不拖住别人开始。要「谁先好
谁先回」就得改成流式收集,那要动 AgentEvent(得有个「结果已就绪」的事件),
留给 E07 的钩子一起做。
七、入口:52 行看两件事
<!-- file: examples/mini-agent/src/demo-tools.ts -->
/** * E04 的终点:一把进程内的写锁,一次并发执行。 * 运行:cd examples/mini-agent && node src/demo-tools.ts */import { readFile, writeFile } from "node:fs/promises";import { runTools, withFileLock, writeTool, echoTool } from "./tools.ts";import type { ToolCallBlock } from "./types.ts";const file = "tmp-e04.txt";const labels = ["A", "B", "C"];const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));async function slowWrite(label: string): Promise<void> { await sleep(30); await writeFile(file, label, "utf8");}/** 三个任务同时开跑,记录各自落地时刻。 */async function race(useLock: boolean): Promise<string> { const t0 = performance.now(); const done: string[] = []; await Promise.all( labels.map(async (label) => { const run = () => slowWrite(label); if (useLock) await withFileLock(file, run); else await run(); done.push(`${label}@${Math.round(performance.now() - t0)}ms`); }), ); return done.join(" ");}console.log(`不加锁: ${await race(false)}`);console.log(`加锁 : ${await race(true)}`);console.log(`文件里最后留下: ${await readFile(file, "utf8")}`);/* 一轮里的三个调用:一个正常、一个没有这个工具、一个参数类型不对 */const calls: ToolCallBlock[] = [ { type: "toolCall", id: "c1", name: "write", args: { path: file, text: "final" }, }, { type: "toolCall", id: "c2", name: "nope", args: {} }, { type: "toolCall", id: "c3", name: "echo", args: { text: 42 } },];const outcomes = await runTools(calls, [writeTool, echoTool], () => {});for (const out of outcomes) { const flag = out.isError ? "err " : "ok "; console.log(`${flag} ${out.id} ${out.text}`);}race(true) 和 race(false) 用的是同一个 slowWrite,唯一差别是外面套没套
withFileLock。做 A/B 时保持一处差异,是能不能得出结论的关键。
八、代码地图
| 文件 | 关键符号 | 下一章怎么用 |
|---|---|---|
src/tools.ts |
runTools() / validateArgs() / withFileLock() |
E08 的 CLI 用 baseTools + writeTool |
src/loop.ts |
MAX_TOOL_ERRORS / runTools 调用点 |
E07 在两侧插钩子 |
src/demo-tools.ts |
race() |
以后测任何「并发 vs 串行」都能照抄 |
注意 loop.ts 从 112 行缩到 98 行,功能反而多了。搬家不等于加代码:把不
属于这一层的事挪走,主流程会变短。
自检
prev.then(fn)和prev.then(fn, fn)差在哪?各举一个会出问题的场景。Promise.all保序,是指「按完成顺序」还是「按输入顺序」?如果模型要求 tool 结果和 toolCall 一一对应,哪一处代码在保证这件事?- 三个工具里有一个 sleep 10 秒,另外两个 30ms。
runTools的返回时刻是多少? 如果想「先好的先回」,要改哪一层的契约?
参考答案:
第 1 题:prev.then(fn) 只在前一个成功时继续。前一个 write 失败(磁盘满、
权限拒绝)后,后面的写全部不执行,而且没有报错——因为异常已经被前一条链吞在
catch 里。prev.then(fn, fn) 两个分支都继续,失败只影响自己那一次。
第 2 题:按输入顺序。保证它的是 calls.map(...) 的顺序 + Promise.all
的下标语义;loop.ts 拿到的 results 和 calls 一一对应,写消息时不会错位。
第 3 题:约 10 秒——Promise.all 等最慢的那个。要「先好的先回」,得把
runTools 从「返回数组」改成「逐个 yield 结果」,同时给 AgentEvent 加一个
tool_result 事件;这是协议层改动,不是调度层。
九、与 Pi 的对照(可选)
Pi 的 packages/agent/src/agent-loop.ts 里,同一件事叫
executeToolCallsParallel(:596),收尾也是 Promise.all(:656),并且有一个
orderedFinalizedCalls 变量名——顺序是被显式维护的,不靠运气。
它还有一段注释,几乎就是我们 miss() 的说明书(:818):
Never rejects for tool failures: unknown tools, validation errors, blocked calls,and thrown errors come back as `isError: true`.差别在于 Pi 在「执行前」还有 beforeToolCall(权限、审批)和 afterToolCall
(结果改写),所以它需要 prepare / execute / finalize 三段。我们只有一段,
E07 加钩子时会自然长出这三段。
十、下一章
tools.ts 有了锁,但上下文还在无限增长:一轮对话 20 条消息,跑到第 30 轮,
请求体就装不下了。
E05 做压缩:估算 token、设一道阈值、把前面几条换成一条 note——然后用 E02 那道
闸门把它送进 prompt。node src/demo-compact.ts 会打印四个数字:压了没有、丢了
几条、剩几条、第一条是不是摘要。