Pi Agent 源码级教程
E07

扩展 —— 钩子挂在工具表上,内核不动

1,908 字 · 含 163 行代码 · 约 9 分钟

E06 之后,会话能存了。可你想加一样东西——「写文件前要人工确认」「每次工具结果 记一笔审计」——还是只能去改 tools.ts 和 loop.ts。第一次改很爽,第二次就变成 冲突:你在 runTools 里插的三行,E04 的锁一改,三行就飘了。

这一章不写新机制。先把内核已经开过的孔数清楚,再把钩子挂到其中一个上: 工具就是一组对象,包一层就行。

三个问题:

  1. 内核已经开了哪几个孔?为什么钩子不必是第四个?
  2. 想拦下一次调用,为什么「让工具抛错」就够了?
  3. 包装层的代价是什么,什么时候必须回去改内核?
text
   loop.ts     |  tools: Tool[]        <-- 孔一:工具是数据     |  emit(event)          <-- 孔二:事件流(只读)     |  project(messages)    <-- 孔三:投影     v  withHooks(tools, hooks)   <-- 本章:只包孔一     |     +-- before(call)                -> block | args | undefined     +-- execute(args)               -> text     +-- after(call, text, isError)  -> text

一、本章终点:先跑起来

bash
cd examples/mini-agentnode src/demo-hooks.ts
text
turn 1 end toolUseturn 2 end stopok  c1 echo: 被钩子改写 [审计]err c2 不许写 secretsecret 文件被写了吗: false

五行四件事:

  • 两个 turn_end:钩子只是旁听,循环照常跑完两轮。
  • c1 的参数被 before 从 原始 改成了 被钩子改写——输出里找不到「原始」。
  • c2 被拦下,模型收到的是一条错误文本。
  • 最后一行 false 是最硬的证据:工具根本没执行,不是执行完再把结果丢掉。
文件 行数 本章变化
src/hooks.ts 46 新增:钩子接口 + 包装器
src/demo-hooks.ts 68 新增:本章入口
合计 1,146 E06 的 1,032 + 本章 114

另有 test/hooks.test.ts(30 行,2 个测试),不计入行数链。


二、先数孔,再决定要不要打洞

loop.ts 只有 98 行,但它对外开了三个孔:

  • 孔一 Tool[]。 E04 把工具做成「名字 + 描述 + 参数 + execute」的对象, 循环只认这张表。换表不用动循环——钩子要的就是这个口子。
  • 孔二 emit。 E01 的事件流里已经有 turn_end,转发一次就有了「每轮结束」 钩子,内核不用加一行。
  • 孔三 project。 E02 的投影,决定模型看到什么。改上下文去包它,不归本章。

所以本章只有两个新增文件,loop.ts 和 tools.ts 一个字符都没改。这不是克制, 是判据:如果你的扩展非得改内核,先问一句「哪个孔没开够」,而不是直接加 if。


三、包装器:46 行

<!-- file: examples/mini-agent/src/hooks.ts -->

ts
import type { AgentEvent, Tool, ToolCallBlock } from "./types.ts";/** 调用前的裁决:拦下、改参数,或放行(undefined)。 */export type BeforeVerdict =  | { block: string }  | { args: Record<string, unknown> }  | undefined;export interface ToolHooks {  /** 校验之后、执行之前。 */  before?(call: ToolCallBlock): BeforeVerdict;  /** 执行之后(失败也算)。返回值就是模型看到的文本。 */  after?(call: ToolCallBlock, text: string, isError: boolean): string;  /** 第三道孔:事件流只读,改不了流程。 */  onEvent?(event: AgentEvent): void;}/** * 把钩子包成一层工具表。内核(loop.ts / tools.ts)一行都不用改, * 因为「工具就是一个带 execute 的对象」是 E04 定下的契约。 * 代价:包装层看不到 loop 分配的 call.id,也接不到 validateArgs。 */export function withHooks(tools: Tool[], hooks: ToolHooks): Tool[] {  return tools.map((tool) => ({    ...tool,    async execute(args) {      /* 借用工具名占位:这一层没有真 id */      const call: ToolCallBlock = {        type: "toolCall",        id: tool.name,        name: tool.name,        args,      };      const verdict = hooks.before?.(call);      if (verdict && "block" in verdict) throw new Error(verdict.block);      const realArgs = verdict && "args" in verdict ? verdict.args : args;      try {        const text = await tool.execute(realArgs);        return hooks.after?.(call, text, false) ?? text;      } catch (error) {        const text = error instanceof Error ? error.message : String(error);        throw new Error(hooks.after?.(call, text, true) ?? text);      }    },  }));}

六处值得停一下:

BeforeVerdict 是三态。 返回 undefined 是放行,{ args } 是改参数, { block } 是拦下。三种意图三种形状,比 { ok: boolean, args?, reason? } 少一堆 if,也不会出现「既 block 又给 args」的矛盾值。

拦下用 throw,不是返回错误对象。 E04 的 runTools 早就有一条 「工具抛错 → isError: true → 结果进历史」的通路(tools.ts:132),复用它是 零改动;而且模型看到的和「工具自己失败了」一模一样——它不需要知道是权限还是 bug。

代价当场出现:after 看不到被拦的那次。 throw 在 try 外面, 所以输出里 err c2 不许写 secret 没有 [审计] 后缀。要审计「被拦下的尝试」, 只能在 throw 之前自己记一笔。

?? text 只挡 null / undefined。 钩子返回空串是「改成空」,不是「没改」。 这两个语义差得很远,别用 ||。

内层 try/catch 里再 throw。 after 返回的文本要重新包成 Error 抛出去, 否则一次失败的调用会被改写成「成功返回一段文本」。

id: tool.name 是妥协。 loop 分配的 call_1 在 execute 这一层根本拿不到。 要真 id,就得改 runTools 的签名——那就是「回去改内核」。


四、入口:68 行

<!-- file: examples/mini-agent/src/demo-hooks.ts -->

ts
/** * E07 的终点:拦一个、改一个、记一笔,内核一行没改。 * 运行:cd examples/mini-agent && node src/demo-hooks.ts */import { existsSync, rmSync } from "node:fs";import { withHooks } from "./hooks.ts";import type { ToolHooks } from "./hooks.ts";import { runAgent } from "./loop.ts";import { toLlm } from "./messages.ts";import { echoTool, writeTool } from "./tools.ts";import type { Provider } from "./types.ts";const target = "tmp-e07-secret.txt";rmSync(target, { force: true });/* 剧本模型:第一轮发两个调用,第二轮收尾。真模型做不到这么可控。 */const scripted: Provider = {  name: "scripted",  async *stream(messages) {    if (messages.some((m) => m.role === "tool")) {      yield { type: "text", text: "两个都试过了。" };      yield { type: "done", stopReason: "stop" };      return;    }    yield { type: "toolCall", id: "c1", name: "echo", args: { text: "原始" } };    yield {      type: "toolCall",      id: "c2",      name: "write",      args: { path: target, text: "x" },    };    yield { type: "done", stopReason: "toolUse" };  },};const hooks: ToolHooks = {  before(call) {    if (call.name === "write" && String(call.args.path).includes("secret")) {      return { block: "不许写 secret" };    }    if (call.name === "echo") return { args: { text: "被钩子改写" } };    return undefined;  },  after(_call, text, isError) {    return isError ? text : `${text} [审计]`;  },  onEvent(event) {    if (event.type === "turn_end") {      console.log(`turn ${event.turn} end ${event.stopReason}`);    }  },};const result = await runAgent({  provider: scripted,  tools: withHooks([echoTool, writeTool], hooks),  messages: [{ role: "user", content: "试试工具" }],  maxTurns: 3,  project: toLlm,  emit: (event) => hooks.onEvent?.(event),});for (const message of result.messages) {  if (message.role !== "tool") continue;  const flag = message.isError ? "err " : "ok  ";  console.log(`${flag}${message.toolCallId} ${message.content}`);}console.log(`secret 文件被写了吗: ${existsSync(target)}`);

scripted 是这一章唯一「作弊」的地方:真模型不会稳定地在同一轮发两个调用。 要可控,要么写剧本 provider(这里),要么用 E03 的 fixture 回放。测钩子测的是 工具表,不是模型——把模型换成脚本,测试才不抖。

after(_call, ...) 的下划线是故意的:参数没用上,但位置不能省——签名是三个。


五、三个代价

代价一:接不到 validateArgs。 runTools 的顺序是「查参数 → execute」 (tools.ts:125),包装层在 execute 里面,所以钩子改出来的参数不会再被查一遍。 echo 拿数字也能跑(它自己 String() 了);write 少了 path 则靠工具自己的 if (!file) throw 兜底(tools.ts:53)。 Pi 也一样:agent-loop.ts:737 校验、:738 才调钩子。

代价二:拦下 = 一次工具失败。 E01 的循环有连续失败计数(loop.ts:86, MAX_TOOL_ERRORS = 3),连续三次被拦会以 stopReason: "error" 结束。 「权限拒绝」和「工具坏了」在这里是一个东西。

代价三:没有顺序,也没有优先级。 两个扩展各自 withHooks,谁先跑取决于你 包的顺序;被外层拦下的调用根本到不了内层。真正的扩展系统要排序,还要能声明 「我只观察,不裁决」。

什么时候必须回去改内核?三条任一成立:

  1. 钩子要真 call.id,或者要改 messages;
  2. 要「拦下但不计入失败」;
  3. 要多个扩展按优先级组合。

六、测试:2 个,断言「真的没跑」

bash
node --test "test/*.test.ts"# tests 14 / pass 14

<!-- file: examples/mini-agent/test/hooks.test.ts -->

ts
import { test } from "node:test";import assert from "node:assert/strict";import { withHooks } from "../src/hooks.ts";import { echoTool } from "../src/tools.ts";test("block 之后工具根本不执行,错误文本回到模型", async () => {  let ran = 0;  const tool = {    ...echoTool,    execute() {      ran += 1;      return "不该出现";    },  };  const hooked = withHooks([tool], {    before: () => ({ block: "拒绝" }),  })[0];  assert.ok(hooked);  await assert.rejects(() => hooked.execute({ text: "x" }), /拒绝/);  assert.equal(ran, 0);});test("before 改参数、after 改返回值,各一层", async () => {  const hooked = withHooks([echoTool], {    before: () => ({ args: { text: "改写" } }),    after: (_call, text) => `${text}!`,  })[0];  assert.ok(hooked);  assert.equal(await hooked.execute({ text: "原始" }), "echo: 改写!");});

第一个测试的 assert.equal(ran, 0) 才是重点。只断言 rejects 通过,你分不清 「拦住了」和「跑完了才报错」——这是拦截类功能最常写假的地方。


七、与 Pi 的对照(可选)

Pi 没有把钩子藏在工具表里,而是写进内核参数(agent-loop.ts:693):

Pick<AgentLoopConfig, "beforeToolCall" | "afterToolCall">

两个钩子名字直接挂在循环配置上,不经过任何包装。prepareToolCall 在 :737 校验参数、:738 调 beforeToolCall,:755 看 block,没给原因就填 "Tool execution was blocked"(:756)。钩子拿到 assistantMessage / toolCall / args / context,比我们的 args 富裕得多。

外面还有一层扩展事件:extensions/types.ts:1474 的 ToolCallEventResult 有 block / reason / terminate 三个字段,注册在 :1685 的 on("tool_call", ...)。 那个 terminate(:1478)正是我们缺的「拦下并停下」。

Pi 分两层:内核钩子(工具嵌套调用也走它,agent-loop.ts:812 的注释写的就是 「hook 例如权限检查」)+ 扩展事件(第三方插件)。我们压成一层——够用,但说不清 「插件」和「内核自己的权限检查」的先后。


八、代码地图

文件 关键符号 下一章怎么用
src/hooks.ts withHooks() E08 的 CLI 里包工具表
src/demo-hooks.ts scripted 剧本 任何「要精确复现一轮」的调试
test/hooks.test.ts ran === 0 拦截功能的验收断言

自检

  1. 删掉 if (verdict && "block" in verdict) throw ... 这一行,输出会变成什么样?
  2. 把 after 改成对 isError 也加 [审计],c2 会有这个后缀吗?
  3. 钩子把 echo 的 text 改成数字 42,谁会报错?

参考答案:

第 1 题:c2 变成 ok,最后一行变成 true——write 真的把 secret 文件写了, 模型还会以为成功。这就是「钩子被删掉了但没人发现」的样子,所以要有第 1 个测试。

第 2 题:不会有。throw 在 try 外面,after 根本没被调用。要记被拦下的 尝试,只能在 throw 之前自己调一次;把 throw 挪进 try 也行,但 after 抛错 会再被 catch 接住,容易套娃。

第 3 题:没人报错。validateArgs 已经在包装层外面跑完了,echo 里 String(args.text) 把 42 变成 "42",一路成功。拦得住的地方只有钩子自己。


九、下一章

工具、压缩、会话、钩子,四块都齐了,但它们各自待在自己的 demo-*.ts 里。 真正交付要给用户一个入口:一个命令行、一串参数、一个能一直聊下去的终端。

E08 拼 cli.ts:--mock / --fixture / --openai 选 provider,--session 接 会话,--tools 打开写权限,project 里顺手接上 E05 的压缩。最省事的验收是 node src/cli.ts "你好":一条命令走完 provider → 循环 → 投影 → 输出。