深入理解 DeepSeek Harness · 第 8 篇
工具管线:Schema 注入与执行流水线
前情回顾
第 7 篇把流式输出讲完,并明确把工具管线留给本篇。第 5 篇的 turn 骨架里,工具调用出现在 step 内;本篇展开它从注册、schema 注入到结果落日志的完整链路。
本章要回答的问题
工具的 schema 是怎么进入 model prompt 的?tools/pre-execute → tools/execute → tools/post-execute → tools/result 这条管线每一段做什么、为什么前三个是 waterfall 而最后一个是 emit?策略拒绝、守卫拒绝、工具抛错三类失败分别落在哪一行?一次 read_file 调用怎样从定义走到日志?
你会学到什么 / 先验知识
你会看懂工具注册作为副作用、四个事件的派发契约、单调守卫与审批接缝的消费方式、内容投影与最终化的边界,以及 tool/call / tool/result 的落盘顺序。先验是第 3 篇的 waterfall 与第 6 篇的 durable 事件。
核心概念:注册表统一收集 schema
工具定义由 defineTool()(把普通对象校验成 ToolDefinition,即工具的 schema + 执行 + 可选最终化/展示/guidance 的声明)产生;guidance 是工具附带的 system prompt 段落说明。docs/cookbook/adding-a-tool.md:17-39 给出完整的 read_file 例子:
export function apply(ctx: Context) { ctx.tools.register(defineTool({ name: 'read_file', description: 'Read a file from disk.', // what the model sees parameters: { path: { type: 'string', required: true, description: 'Absolute path' }, limit: { type: 'number' }, // optional by default }, output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }], }, async execute(args, exec) { // args is TYPED from the schema: { path: string; limit?: number } // exec carries immutable identity + token; signal is the operational field // A production tool converts errno failures such as ENOENT into FsError codes return readFile(args.path, { encoding: 'utf8', signal: exec.signal }) }, })) }
description 的注释写着 what the model sees:schema 不是手写进 prompt 模板的,而是从注册表收集后由 system prompt 装配器统一拼入。[源码] packages/core/tools/src/index.ts:141-152 就是那个收集点:
constructor(ctx: Context) { super(ctx, 'tools') ctx.systemPrompt.tools(({ scope, toolStep }) => { const declared = toolStep !== undefined && toolStep.agent === scope ? toolStep.declarations : this.getAll(scope) return { schemas: declared.map(definition => projectToolSchema(definition, false)), knownNames: [...new Set([...declared.map(definition => definition.name), ...this.names(scope).known])], } }) }
几个术语先定死:scopeTarget 是把调用按 agent 作用域打标的助手(pipeline.ts:269,378);PreToolDecision 是 pre-execute 阶段的决策类型(allow / ask / cancel);materializeFinalResult 把候选结果固化成不可变最终结果;ToolCallBlock 是模型发起的一次工具调用块,含 id、name、arguments(batch.ts:243)。
graph LR
A[ctx.tools.register] --> B[注册副作用<br/>insert + guidance section]
B --> C[schema 统一收集<br/>systemPrompt.tools → prompt assembly]
C --> D[模型发起 tool/call]
D --> E[tools/pre-execute<br/>waterfall:allow/ask/cancel]
E --> F[单调 guard + 审批接缝]
F --> G[tools/execute<br/>waterfall:around 包装]
G --> H[tools/post-execute<br/>waterfall:接受/替换/阻断]
H --> I[contentProjectors.project → applyFinalContent → notify]
I --> J[tool/result 按 sourceEventSeqs 落盘]
I -. emit .-> K[tools/result 监听者]
源码走读:一次调用的五个断面
证据一:注册是一个可卸载的副作用。 [源码] packages/core/tools/src/index.ts:166-196:
register(tool: ToolDefinition): () => void { assertToolDefinition(tool) this.read(() => { const offered = findToolCandidate(undefined, this.ownLayer()?.includes.values() ?? [], tool.name, undefined) // A different definition already offered here makes the name ambiguous, which resolving reports. if (offered !== undefined) resolveToolCandidate(tool.name, mergeToolCandidate(offered, tool)) }) const guidance = tool.guidance if (guidance === undefined) { return this.layers.effect(this.ctx, layer => layer.tools.insert(tool.name, tool), { label: 'tools.register()' }) } const section = guidance.section ?? `tool:${tool.name}` // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; preserve the Cordis disposer identity return this.ctx.effect(function* (this: ToolsService) { yield this.layers.effect(this.ctx, layer => layer.tools.insert(tool.name, tool), { label: 'tools.register()' }) const tools = this.guidanceTools.get(section) ?? [] this.guidanceTools.set(section, tools) tools.push(tool) yield () => { tools.splice(tools.indexOf(tool), 1) if (tools.length === 0) this.guidanceTools.delete(section) } yield this.ctx.systemPrompt.section({ name: section, order: this.ctx.systemPrompt.getSectionOrder(guidance.order), interpolate: false, ...guidance.retirement === undefined ? {} : { retirement: guidance.retirement }, text: context => this.guidanceText(tools, guidance, context), }) }.bind(this), 'tools.register()') }
有 guidance 的工具用一个生成器副作用把「注册工具、维护 guidance 列表、注册 prompt section」三件事绑在一起,返回同一个 disposer——卸载时按第 3 篇的逆序展开,不会留下半套状态。
证据二:四个事件的派发契约。 [源码] packages/core/tools/src/events.ts:18-49(节选关键声明与 JSDoc):
'tools/pre-execute'(this: Scoped<ToolsService>, exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> /** * Around-dispatch waterfall for timeout, retry, or metrics. `next()` returns * a normalized result; wrappers may change only `exec.signal`, while call * identity remains immutable. The registry re-fuses the original caller * signal before the body, so replacement cannot detach caller cancellation; * wrappers must still restore their signal and reach quiescence. ... * @mode waterfall */ 'tools/execute'(this: Scoped<ToolsService>, exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> /** * Accept, replace, enrich, or block a normalized dispatch result. `next()` * accepts it unchanged; thrown tools still reach this waterfall as errors. Async * listeners must observe `exec.signal`; after they settle, caller * cancellation replaces only a successful accepted outcome with the code * selected by whether the tool body was invoked. ... * @mode waterfall */ 'tools/post-execute'(this: Scoped<ToolsService>, exec: ToolExecution, result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision> /** * Observe the frozen, lossless-JSON final outcome. Listener failures are contained. ... * @mode emit */ 'tools/result'(this: Scoped<ToolsService>, exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): undefined
前三个是 waterfall,因为它们要改写决策或结果,必须靠 next() 委托;tools/result 是 emit,只观察最终结果、失败被隔离,因为最终结果一旦落盘就不该被监听器改写。三条规定尤其重要:tools/execute 的包装器只能改 exec.signal,调用身份不可变;注册器会在 body 前重新融合原始调用方 signal;异步监听器必须观察 signal 并达到静止(quiescence)。
证据三:prepare 阶段——决策、守卫与审批。 [源码] packages/core/tools/src/pipeline.ts:261-304:
async prepare(input: ToolExecutionInput): Promise<ScheduledToolPreparation> { const created = this.createExecution(input) if (created.kind !== 'ready') return created const exec = created.exec if (this.callerCancelled(exec)) { return { kind: 'final-result', exec, result: toolAbortedBeforeDispatchResult() } } try { const carrier = scopeTarget(this.tools, exec.agent) const gate = await this.ctx.waterfall( carrier, 'tools/pre-execute', exec, () => Promise.resolve<PreToolDecision>({ kind: 'allow' }), ) const askResolution = gate.kind === 'ask' ? await this.serviceAsk(exec, gate) : { decision: gate, approvalCancelled: false } const { decision } = askResolution if (this.callerCancelled(exec) && askResolution.approvalCancelled) { return { kind: 'post-result', exec, result: toolAbortedBeforeDispatchResult() } } if (decision.kind === 'cancel') { return { kind: 'post-result', exec, result: toolAbortedBeforeDispatchResult() } } const denial = decision.kind === 'allow' ? this.tools.checkGuards(exec) : decision if (denial !== undefined) { const { reason: denialReason, info: denialInfo } = denial return { kind: 'post-result', exec, result: this.materializeFinalResult({ content: [{ type: 'text', text: `Error: ${denialReason}` }], isError: true, error: { message: denialReason, ...denialInfo === undefined ? {} : { info: denialInfo } }, }), } } if (this.callerCancelled(exec)) { return { kind: 'post-result', exec, result: toolAbortedBeforeDispatchResult() } } return { kind: 'dispatch', exec } } catch (error: unknown) { return { kind: 'final-result', exec, result: toolErrorResult(error) } } }
三个决策源:pre-execute waterfall 的 ask / cancel / allow、审批接缝 serviceAsk()、以及 tools.checkGuards()。关键细节在 :284:decision.kind === 'allow' 时才检查守卫,否则 denial 直接采用 decision——guards 只能拒绝,不能返回 allow 放行。审批接缝 [源码] pipeline.ts:526-537 用 ctx.get('approval') 机会式消费:没有 ApprovalService、会话中途卸载、或没有 agent 可审计时,都降级为 APPROVAL_UNAVAILABLE 的拒绝。
证据四:dispatch、post-execute 与最终化。 [源码] packages/core/tools/src/pipeline.ts:375-404(节选到 :383):
async dispatch(exec: ToolRunContext): Promise<ScheduledToolDispatch> { try { const mutableExec = exec as MutableToolRunContext const carrier = scopeTarget(this.tools, exec.agent) const result = await this.ctx.waterfall( carrier, 'tools/execute', mutableExec, () => this.dispatchToolBody(mutableExec), ) const normalized = this.normalizeDispatchResult(exec, result)
tools/execute 的 innermost next 就是真正的工具 body。工具 body 自己抛错时被 [源码] pipeline.ts:354-357 捕获并转成 toolErrorResult(取消且属于未分类取消时用 TOOL_ABORTED);:402-404 捕获的是 wrapper 抛错,:450-452 捕获的是收尾阶段失败——三处 catch 对应不同失败路径。收尾 [源码] pipeline.ts:437-449:
const project = this.contentProjectors.get(exec) this.contentProjectors.delete(exec) const content = project?.(exec, result) const projected = content === undefined ? result : this.markCanonical(exec, this.materializeFinalResult({ ...result, content })) const postResult = await this.postExecute(exec, projected) return this.finish( exec, this.callerCancelled(exec) && !postResult.isError ? this.cancellationResult(exec, postResult) : postResult, )
contentProjectors.project(即 projectContent)只替换 content;随后 finish() [源码] pipeline.ts:463-478 用 applyFinalContent 做工具自有的最终内容变换,再 notifyResult() 触发 tools/result emit:
private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult { let materializedResult: ToolExecutionResult try { materializedResult = this.materializeFinalResult(result) } catch (error: unknown) { materializedResult = this.materializeFinalResult(toolErrorResult(error)) } let finalResult: ToolExecutionResult try { finalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult)) } catch (error: unknown) { finalResult = this.materializeFinalResult(toolErrorResult(error)) } this.notifyResult(exec, finalResult) return finalResult }
证据五:结果落盘。 [源码] packages/core/tools/src/batch.ts:243-269:
start(block: ToolCallBlock): SessionSeq | undefined { if (this.input.log === undefined) return undefined const { agent, log: { turn, step } } = this.input // oxlint-disable-next-line typescript/no-non-null-assertion -- ToolBatchInput requires agent whenever log is provided return agent!.session.append('tool/call', { turn, step, callId: block.id, name: block.name, arguments: block.arguments, }).seq } commit(block: ToolCallBlock, result: ToolExecutionResult, callSeq: SessionSeq | undefined): void { if (this.input.log !== undefined) { const { agent, log: { turn, step } } = this.input // oxlint-disable-next-line typescript/no-non-null-assertion -- ToolBatchInput requires agent whenever log is provided agent!.session.append('tool/result', { turn, step, message: createToolResultMessage({ callId: block.id, content: result.content, isError: result.isError }), ...result.error?.info ? { error: result.error.info } : {}, ...result.meta !== undefined ? { meta: result.meta } : {}, }, { surfaceOp: 'append', // oxlint-disable-next-line typescript/no-non-null-assertion -- start records a call seq whenever this batch logs results sourceEventSeqs: [callSeq!], }) } this.results.push({ callId: block.id, result }) this.contexts.push(...result.additionalContexts ?? []) }
tool/call 在派发前追加并返回 seq,tool/result 在提交时追加,并通过 sourceEventSeqs: [callSeq] 指回调用事件。注意 :258 落盘的是 result.content——投影后的内容本身就写进 durable 日志,所以内容投影不是保密手段。第 6 篇的硬中断补录识别悬空调用靠的是 ToolCallRecovery.pendingCalls(packages/core/session/src/repair.ts:105-149):它记录 assistant 消息里的 tool-call 身份,tool/call 事件给 entry 补 callSeq,tool/result 带 surfaceOp: 'append' 时删除该条;sourceEventSeqs 只是结果指回调用的引用,不是识别机制。
贯穿示例:read_file 从定义到日志
把上面的断面串起来:defineTool 定义 read_file(cookbook:18-35)→ ctx.tools.register() 以副作用插入注册表与 guidance section(index.ts:166-196)→ ctx.systemPrompt.tools() 把 schema 收进 prompt(index.ts:141-152)→ 模型产出 ToolCallBlock,batch.start() 先写 tool/call 并拿到 seq(batch.ts:243-250)→ prepare() 跑 tools/pre-execute、审批与守卫(pipeline.ts:261-304)→ tools/execute 围绕真正的 readFile(args.path, { signal })(pipeline.ts:375-383、cookbook:29-34)→ tools/post-execute 接受/替换结果,contentProjectors.project 与 applyFinalContent 只改 content(pipeline.ts:437-449、:463-478)→ notifyResult() 触发 tools/result emit → batch.commit() 写 tool/result,sourceEventSeqs 指回调用 seq(batch.ts:252-269)。
设计取舍
① 为什么 guard 没有 allow 返回? pipeline.ts:284 只在 decision.kind === 'allow' 时跑 checkGuards();守卫只能给出 denial,放行仍由 dispatchToolBody 决定。这保持单一决策点——策略不能主动注入结果,只能否决。代价是策略无法「替模型写一个答案」,必须靠 tools/post-execute 的替换能力表达。
② 为什么内容投影不等于保密? contentProjectors.project 与 applyFinalContent 只改 content(pipeline.ts:437-449、:481-485),但 batch.ts:258 把投影后的 result.content 写进 tool/result 日志。代价是 secret 不能靠内容投影抹除——需要保密的输入从一开始就不该进日志;原始 tool/call 与 assistant/message 事件仍是不可变事实。
③ 为什么取消要等静止(quiescence)而不是硬杀? events.ts:20-24 要求 wrapper 改 signal 后必须恢复、并等待所有异步监听器 settle;注册器还会重新融合原始调用方 signal。这样日志中不会出现「调用已发出但结果未知」的悬空状态。代价是取消可能延迟。
常见误解
「工具 schema 是手写进 prompt 的。」 不是,ctx.tools.register() 贡献声明,systemPrompt.tools() 统一收集(index.ts:141-152)。
「工具执行就是直接调一个函数。」 不是,中间有 pre-execute 决策、守卫、execute 围绕包装、post-execute 替换、内容投影与最终化五道关口。
「工具抛错了就没有结果事件。」 三类失败都会产出 isError: true 的结果:策略拒绝(pipeline.ts:526-537)、守卫拒绝(:284-295)、工具本身抛错(:354-357);wrapper 与收尾阶段的失败分别在 :402-404 与 :450-452 被包成错误结果。
小结
工具注册是可卸载副作用(packages/core/tools/src/index.ts:166-196),schema 由 systemPrompt.tools() 统一收集进 prompt(:141-152);管线依次经过三个 waterfall——前三个要改写决策或结果故必须用 next(),末段 tools/result 只观察最终结果故用 emit(packages/core/tools/src/events.ts:18-49)。prepare 阶段处理决策、审批与单调守卫(pipeline.ts:261-304、:526-537),execute 围绕真正的工具 body(:375-383),收尾只投影 content 再最终化并通知(:437-449、:463-478)。三类失败分别落在策略拒绝 pipeline.ts:526-537、守卫拒绝 :284-295、工具抛错 :354-357(wrapper 与收尾失败在 :402-404、:450-452);tool/call 与 tool/result 通过 sourceEventSeqs 配对落盘(batch.ts:243-269),而悬空调用的识别靠 pendingCalls(repair.ts:105-149)。
代价落在三处:守卫只能拒绝不能注入结果、投影后的 content 本身会落日志、取消要等异步监听器静止。第 9 篇转向能力接缝,看这棵工具树背后的能力如何被换掉。
思考题
- 在
packages/core/tools/src/pipeline.ts:284找到checkGuards(exec)的调用条件。如果让 guard 能返回allow直接放行,会破坏哪条不变量?策略想「替模型写一个答案」应该改走哪个事件? - 在
packages/core/tools/src/pipeline.ts:437-449找到contentProjectors.project。它为什么只能改content而不能改isError或error?结合packages/core/tools/src/batch.ts:258说明:投影后的内容写进日志后,「保密」为什么不能靠投影实现? - 对比
packages/core/tools/src/batch.ts:264的sourceEventSeqs: [callSeq!]与packages/core/session/src/repair.ts:105-149的pendingCalls:前者在日志里起什么作用?硬中断补录为什么必须靠后者识别悬空调用?