Agent 架构实操
16 / 20

协作协议与计划审批

用一项写文件计划演示怎样匹配批准请求、拒绝错误收件人,以及识别已确认响应的重放。

跟着案例走一遍

每一步都标出谁在行动,以及此刻的状态。

  1. 01登记计划

    Alice 登记 write the file,目标是 Lead,状态暂时是 pending。

    PlanApproval · requestId
  2. 02拒绝错投

    批准响应的收件人错填 Bob,校验报错,原请求保持 pending。

    ProtocolMismatchError
  3. 03保存审批结论

    收件人正确且请求匹配,状态变成 approved,记录响应的消息 ID。

    approved · response messageId
  4. 04确认重复响应

    完全相同的响应可以重投;同一个响应 ID 换正文则报错。

    replay → original resolution

在本机复现

在 Bash 中进入仓库的 code/ 目录,先运行 npm ci。实验先打印运行结果,再跑回归断言,无需 API Key。

npm run demo -- 16
  1. 把正确的响应收件人 Alice 换成 Bob 时,校验报 ProtocolMismatchError,请求仍为 Pending。
  2. 匹配的响应变更为 Approved,保持响应消息 ID;原样重投返回同一决议。

读前自测

一条普通文本「批准」能解除计划门吗?

查看答案

不能。计划门需要和登记请求匹配的类型化响应。

入门导读(可先跑实验)

上一章保证消息能够被交接,这一章验证一条回复是不是对某个请求的有效决定。请求 ID 标识待审批的事;响应消息 ID 识别一封已交付的回信。普通文本「批准了」不能替代这组对应关系。

从仓库根目录启动 Bash(macOS/Linux 直接使用 Bash;Windows 使用 Git Bash,或在装有 Node.js/npm 的 WSL 环境中使用 Bash)。已安装依赖可跳过 npm ci。

export REPO_ROOT="$(pwd)"
cd code
npm ci
npm run demo -- 16

**先看演示输出:**错收件人时请求仍是 pending,只在响应匹配后变成 approved;原样重投不生成新决议。随后自动测试验证三点:

  1. Alice 登记 write the file 计划,目标是 Lead;协议先保存待审批请求。
  2. 把批准响应收件人错填成 Bob,校验抛 ProtocolMismatchError,原请求仍为 Pending。
  3. 正确响应把请求推进为 Approved 并保存响应消息 ID;重复提交一致的响应返回同一决议。实验不真正写任务目标文件,也不用模型密钥。

独立演示 · 实验测试 · 对应实现

当前实践。 计划审批不是工具授权替身:通过计划门后仍须通过原有工具权限。对照 LangGraph Interrupts,要把暂停、恢复和副作用分别设计,尤其避免恢复路径重复提交。本章是队友协议存储,并没有采用 LangGraph。下一章处理多个队友怎样认领同一个任务板里的工作。

下面保留完整的实现、进阶实验和排错说明。


用协议关联请求和决定

投递只能证明消息到了。要让程序安全地据此改变状态,还必须知道它答复了哪个请求,发件人和收件人是否匹配,是否已经处理过。

本章使用两条对照路径:关机请求等待队友结束手头工作,再由运行时返回确认;计划审批先形成决定,再让同一位队友继续工作。两条路径都在发送前登记请求,都依靠请求 ID 和消息 ID 判断重投,只在验证通过时推进状态。计划批准不会代替工具本身的校验和权限。

图片


本章导读

读完这一章,你能做到什么

  • 说清"消息送达"和"协议完成"差在哪,以及为什么前者不能推出后者。
  • 亲手跑出一次完整的优雅关机:从 request_shutdown 到队友 shutdown,全程不多花一次模型调用。
  • 亲手跑出一次计划审批:提交、批准、队友被唤醒继续干活,以及被拒绝之后发生什么。
  • 看懂 .agent_tutorial/protocol/state.json 里每个字段的意思,并能判断一份状态是否合法。
  • 解释为什么 plan gate 必须是一条 PermissionRule,而不是一段 Prompt 提示。
  • 说出五种"协议出错"分别会被怎么处理:release、quarantine、还是让队友进 failed。
  • 独立回答:为什么 Lead 要先把事件写进 history,再去消费协议状态。

你需要先具备什么

前置 具体要求 不满足会怎样
第 15 章的持久 Mailbox 知道 ready -> processing -> done/quarantine 四个目录代表什么 看不懂协议消息为什么也走这套目录
第 15 章的持续队友 知道 spawn 之后队友有独立 Runner 和独立 history,idle 不等于销毁 会以为关机就是把对象删了
第 3 章的权限层 知道 PermissionPolicy 在 handler 之前生效,deny 会让工具根本不执行 会以为 plan gate 只是提示
第 13 / 14 章的事件 知道 EventInbox、JobSupervisor,以及事件如何进入 canonical history 看不懂"先 history 再 ack"为什么重要
Node.js 22.13.0+ 的 22.x(推荐 24 LTS) 本文实测用的是 v25.7.0 npm run build 或 tsx 会报语法错误
Bash macOS/Linux 使用 Bash,Windows 可使用 Git Bash 或 WSL 在该环境中安装并使用 Node.js/npm

没读过第 15 章也不是不能往下看。只要你接受一个前提:队友之间的每条消息都是一个文件,文件所在的目录名就是它的状态。这一章新增的东西全部建立在这句话上。

术语速查(本章第一次出现的词)

词 一句话解释
协议(protocol) 一次有始有终的请求/响应往返,双方都能验证它完成了没有
ProtocolRequest 持久化在磁盘上的请求记录,是"这件事进行到哪了"的唯一真相
request_id ProtocolRequest 的规范 UUID。响应靠它找回自己对应的请求
pending / approved / rejected 请求的三种状态。只能从 pending 迁移出去,且只能迁移一次
resolution 请求的终态凭据,记下是哪条消息、批没批、什么时候结的
TTL / expires_at_utc 响应窗口。默认 5 分钟,超时的响应不再被接受
typed envelope 带类型的信封。协议消息的 kind 是 protocol,和普通消息物理隔离
确定性路由(deterministic router) 在调用模型之前按类型分流。协议消息根本不进模型
plan gate 一条权限规则。计划没批准时,写入/执行类工具直接被 deny
release 把消息退回 ready,等下次重试。用于"消息是好的,只是这次失败了"
quarantine 把消息挪到 quarantine,不再重试。用于"消息本身就是坏的"
effectful 工具 会产生副作用的工具,effect 不是 read 的那些
至少一次(at-least-once) 投递保证。同一条消息可能重复到达,靠稳定 ID 去重

建议的阅读路线

这一章的所有机制都挂在同一条链路上。建议按链路顺序读,不要跳:

[1] 先看一次完整轨迹          <- 建立直觉,知道最后长什么样
      |
[2] 两个新工具 + 一个新能力位   <- 知道公开差量只有这么多
      |
[3] ProtocolRequest 长什么样   <- 状态真相在磁盘上
      |
[4] 硬规则一:先登记,再发送     <- 顺序不能反
      |
[5] typed Mailbox 信封         <- 协议不降级成 content 里的 JSON
      |
[6] 硬规则二:响应必须完整匹配   <- 六个条件全中才算
      |
[7] Lead 侧:先 history 再 ack  <- 本章最容易搞错的一节
      |
[8] shutdown 的完整路由         <- 不进模型
      |
[9] 计划审批:状态先变,Runner 后恢复
      |
[10] plan gate 是真门,不是提示
      |
[11] 失败分类:release / quarantine / failed
      |
[12] 接进组合根 + 跑起来 + 14 个动手实验

如果你只有 10 分钟,读 [1]、[7]、[10] 三节,再跑实验 shutdown 和 gate。这三节是本章真正的新东西。


先看一次完整关机的轨迹

先不解释原理。下面是本章实验 shutdown 在我机器上的真实输出(后面《14 个动手小实验》会教你怎么跑出来),你先看一眼结果,再往下读会轻松很多。

场景:Lead 创建了队友 alice,alice 干完第一轮活,然后 Lead 让它关机。

===== shutdown =====
[1] 队友干完第一轮,Lead 收到 result: "initial result"
    模型调用次数 = 1
    队友状态 = idle

[2] request_shutdown 登记了请求:
    id=00000000-0000-4000-8000-000000000901
    kind=shutdown status=pending sender=lead target=alice

[3] Lead 收到的下一条事件:
    isProtocolMailboxMessage = true
    payload = {
      "kind": "protocol",
      "message_id": "4ad3cdea-6f8e-4a16-aa05-1e75256da05d",
      "sender": "alice",
      "recipient": "lead",
      "protocol_kind": "shutdown_response",
      "content": "Ready to shut down.",
      "created_at_utc": "2026-08-30T12:04:11.304Z",
      "request_id": "00000000-0000-4000-8000-000000000901",
      "approved": true
    }
    队友状态 = shutdown
    模型调用次数 = 1 (关闭没有多花一次模型调用)
    ack 之前,请求状态 = pending

[4] ack 之后:
    id=00000000-0000-4000-8000-000000000901
    kind=shutdown status=approved sender=lead target=alice
    resolution.messageId=4ad3cdea-6f8e-4a16-aa05-1e75256da05d approved=true

这段输出里有五个细节值得你现在就注意,它们是本章的全部重点:

第一,[2] 里请求已经有了 id 和 status=pending。 也就是说,在任何消息被发出去之前,磁盘上已经存在一条记录说"有人请求 alice 关机,还没结论"。这是"先登记,再发送"。

第二,[3] 里 payload 的 kind 是 "protocol",不是 "mailbox"。 协议消息和普通消息在 transport 层是两种不同的信封。这个区别在《typed Mailbox:协议不降级成 content 里的 JSON》一节会变得非常重要。

第三,request_id 精确等于 [2] 里那个 id。 响应不是靠"我猜你在说关机的事"来对应请求的,是靠一个 UUID。

第四,模型调用次数从头到尾是 1。 那一次是 alice 干第一轮活时调的。关机这整个往返,模型一次都没参与。这就是"确定性路由":关机是运行时的事,不需要问模型的意见。

第五,ack 之前请求还是 pending,ack 之后才变 approved。 状态迁移发生在 Lead 确认收到之后,不是在消息发出时。为什么要这样,《Lead 侧:先写 history,再消费状态》一节讲。

再看一次计划审批的轨迹

同一个脚本,实验 plan 的真实输出:

===== plan =====
[1] 第一轮之后,模型调用次数 = 1

[2] 队友提交计划:
    id=00000000-0000-4000-8000-000000000901
    kind=plan_approval status=pending sender=alice target=lead
    Lead 侧收到 protocol_kind = plan_approval_request
    ack 之后请求状态 = pending (请求方向的 ack 不迁移状态)

[3] Lead 批准,队友被唤醒;等它交回结果:
    result = "approved work result"
    模型调用次数 = 2

[4] 第二次模型请求收到的 prompt:
    "Plan approved (00000000-0000-4000-8000-000000000901). Proceed with the approved plan."
    system = "You are alice, serving as writer."
    历史里保留了第一轮吗 = true

[5] 请求终态 -> id=00000000-0000-4000-8000-000000000901
                 kind=plan_approval status=approved sender=alice target=lead
                 resolution.messageId=94820a84-7eee-422c-91e8-fc56fb9b5161 approved=true

这里也有三个细节:

  • [2] 说明请求方向的 ack 不迁移状态。Lead 收到"我要提交计划"这条请求并确认,请求依然是 pending——因为 Lead 还没表态。只有响应才迁移状态。
  • [4] 说明批准之后,队友收到的是一句确定性生成的 prompt,不是 Lead 模型自由写的话。Plan approved (<id>). Proceed with the approved plan. 这句是代码拼的。
  • [4] 最后一行 历史里保留了第一轮吗 = true 说明用的还是同一个 Runner、同一份 history。队友没有被重建,它记得自己之前干了什么。

和第 15 章那条轨迹的关键差别

维度 第 15 章(普通消息) 第 16 章(协议消息)
消息表达什么 内容 内容 + "这是在解决哪个请求"
状态存在哪 没有独立状态,消息本身就是全部 .agent_tutorial/protocol/state.json
谁决定下一步 模型读到消息,自己决定 运行时按类型确定性路由,shutdown 根本不问模型
重复消息怎么办 靠稳定 event ID 不重复进 history 额外靠 request_id + resolution 保证只迁移一次
出错了怎么办 坏消息进 quarantine 分五类处理:release / quarantine / worker failed
能不能拦住执行 不能 能。plan gate 在 handler 之前 deny

问题的本质:消息送达不等于协议完成

Mailbox 和协议存储回答的是不同问题:

运行时需要判断什么 从哪里查
消息是否已投递、认领或确认? Mailbox 目录和消息 ID
这是哪个请求的响应,响应者是否匹配,请求是否过期? 请求 ID 指向的协议状态,核对种类及通信双方
这是同一份响应的重投,还是另一份冲突决定? 已持久化的响应消息 ID 与决定内容

两个 ID 不可互换。消息 ID 只识别这封信;请求 ID 关联同一件工作上的多次通信。

三种能跑通但不可靠的写法

写法一:把协议塞进 content 字符串。

// ❌ 不要这样
await mailbox.send("lead", "alice", "SHUTDOWN_REQUEST:req_a3f9", "message");
// 接收方:if (content.startsWith("SHUTDOWN_REQUEST:")) ...

问题:content 是给模型看的自然语言字段。模型某天在正文里原样引用了这个前缀,运行时就会把一句闲聊当成关机指令。而且 req_a3f9 这种短 ID 会碰撞,也没法验证参与方。

写法二:让模型解析一段自由文本 JSON。

// ❌ 也不要这样
// system prompt: "如果你同意关机,请回复 {\"type\":\"shutdown_ok\"}"

问题:模型可能少个引号、多写一段解释、或者干脆用中文回复"好的我同意关机"。你会被迫写一堆容错解析,而每一处容错都是一个可以被绕过的口子。更根本的问题是:关机根本不该由模型决定。

写法三:用一个进程内的字典存请求。

// ❌ 重启即失忆
const pendingRequests = new Map<string, Request>();

问题:进程崩了、CLI 重开了,字典空了。但 Mailbox 里那条 shutdown_response 还躺在磁盘上等着被消费。下次启动读到它,找不到对应请求——这条消息该扔掉还是该处理?没有任何依据。

所以本章的拆法

P16 增加的是一层确定性运行时,它坐在工具和 transport 之间:

Lead 协议工具                       队友协议工具
request_shutdown / review_plan      submit_plan
        |                                 |
        +-------------+-------------------+
                      |
                      v
              ProtocolRuntime
        「先登记 ProtocolRequest,再发 typed 消息」
                      |
        +-------------+--------------------+
        |                                  |
        v                                  v
  JsonProtocolStore                 FileMailboxStore
  protocol/state.json               mailboxes/<name>/{ready,processing,
  ← 状态真相在这里                            done,quarantine}
        |                                  ← 投递在这里
        |                                  |
        +-------------+--------------------+
                      |
                      v
              TeammateRuntime
      「协议消息走确定性 router,普通消息才进模型」
                      |
        +-------------+--------------------+
        |                                  |
        v                                  v
   kind === "protocol"                kind === "mailbox"
   不调用模型                          调用模型

三句话概括这张图:

  1. 状态和投递分开存。 state.json 管"进行到哪了",mailboxes/ 管"消息在哪"。
  2. 写的顺序固定。 永远先写 state.json,再写 mailboxes。
  3. 读的时候先分流。 是协议消息就自己处理完,不去打扰模型。

要强调的是,协议层没有创建第二套消息目录、第二个 EventInbox、或者第二个 Agent Loop。它复用第 15 章已有的全部基础设施,只是多了一个 state.json 和一个类型分支。

实现集中在这几个文件,现在不用打开,《配套代码索引》有完整清单:


公开差量:只有三个工具

整章新增的公开能力就这么多。Lead 拿两个,队友拿一个:

角色 工具 输入 做了什么
Lead request_shutdown teammate 先登记一条 pending shutdown 请求,再把 typed 请求投给队友
Lead review_plan request_id、approve、可选 feedback 把批准/驳回响应投给原计划提交者
队友 submit_plan plan 先登记一条 pending plan 请求,再投给 Lead

输入 schema 全部是 strictObject,多写一个字段就报错:

const shutdownInput = z.strictObject({ teammate: z.string() });

const reviewPlanInput = z.strictObject({
  request_id: z.string(),
  approve: z.boolean(),
  feedback: z.string().optional(),
});

const submitPlanInput = z.strictObject({ plan: z.string().min(1) });

三点值得注意:

  • review_plan 的 approve 是布尔值,不是字符串。没有 "yes"/"approved"/"ok" 这种模糊输入。
  • feedback 是可选的,但驳回时强烈建议带上——队友被拒之后收到的 prompt 会把 feedback 原样带进去。
  • submit_plan 的 plan 有 .min(1),空计划提交不了。

工具面实测:Lead 20 个,队友 5 个

这不是我编的,是实验 tools 跑出来的:

[3] Lead 看到的工具面(共 20 个),最后四个:
     ["spawn_teammate","send_message","request_shutdown","review_plan"]
    Lead 有 submit_plan 吗 = false

[4] 队友看到的工具面(共 5 个):
     ["shell","read_file","write_file","send_message","submit_plan"]
    队友有 request_shutdown 吗 = false
    队友有 review_plan 吗 = false

Lead 保持第 15 章的完整前缀,只在末尾追加两个。顺序是断言过的(见 ch16-bootstrap.test.ts):

..., spawn_teammate, send_message, request_shutdown, review_plan

队友严格是这五个:

shell, read_file, write_file, send_message, submit_plan

为什么要这么切

这个切法不是随手定的,每一条都有理由:

队友没有 spawn_teammate。 否则队友可以造队友,团队规模会失控,而且没人能说清谁该向谁汇报。

队友没有 request_shutdown。 否则 alice 可以要求 bob 关机。谁能终止谁,是治理决策,不能下放。

队友没有 review_plan。 这条最关键:如果队友能审批计划,它就能审批自己的计划,plan gate 立刻形同虚设。审批权必须在被约束者之外。

Lead 没有 submit_plan。 Lead 不需要向谁提交计划。给它这个工具,只会让模型在不该用的时候用。

这里体现的原则和第 6 章的子 Agent 一样:工具面就是权限边界。不给某个工具,比给了再用 Prompt 劝它别用,可靠得多。

说清一处历史遗留

早期的设计草稿里,Lead 的工具表还单独列过一个 request_plan。当前实现没有这个工具,也没有保留兼容别名。

原因很简单:正文从来没定义过 request_plan 的输入是什么、它会登记什么状态、谁负责响应它。一个没有状态迁移、没有响应方的"协议"工具,只会让读者以为存在一条不存在的链路。

计划请求由队友主动 submit_plan 发起。Lead 想让队友提计划,用普通 send_message 说一句就行——那本来就是普通消息该干的事。


ProtocolRequest:持久请求才是状态真相

先看领域对象。九个字段,没有一个是可选的:

interface ProtocolRequest {
  readonly id: string;                       // 规范 UUID
  readonly kind: "shutdown" | "plan_approval";
  readonly sender: string;                   // 发起方
  readonly target: string;                   // 被请求方
  readonly status: "pending" | "approved" | "rejected";
  readonly content: string;                  // 请求正文
  readonly createdAtUtc: Date;
  readonly expiresAtUtc: Date;
  readonly resolution: ProtocolResolution | null;
}

两个封闭集合,实验 kinds 的第一行输出就是它们:

ProtocolRequestKind   = {"Shutdown":"shutdown","PlanApproval":"plan_approval"}
ProtocolRequestStatus = {"Pending":"pending","Approved":"approved","Rejected":"rejected"}

只有两种请求、三种状态。没有 cancelled、没有 expired 状态、没有 in_review。请求过期不是一种状态,而是"当前时间已经超过 expires_at_utc"这个事实——状态本身还留在 pending,这一点《硬规则二:响应必须完整匹配》里的「过期」小节会再回来说。

六条不变量

不变量 为什么
sender !== target 自己请求自己关机没有意义,只会造成死等
名字必须是安全的小写 slug 名字会被当成目录名,第 15 章已经校验过一次
id 必须是规范 UUID 不接受 req_a3f9 这种短 ID,不接受大小写变体
pending 不能带 resolution 带了就自相矛盾:还在等结论,却已经有结论了
approved/rejected 必须带匹配的 resolution 终态必须能说清"是谁、什么时候、批没批"
resolution 时间落在 [createdAtUtc, expiresAtUtc) 不能早于请求创建,也不能等于或超过过期时刻

最后一条的区间写法值得留意:左闭右开。也就是说恰好在 expires_at_utc 这一刻到达的响应,算过期。边界不含在内,避免出现"到底算不算超时"的争议。

状态机只有两条边

                    ┌─────────────┐
                    │   pending   │  ← 唯一起点,创建时就是这个状态
                    └──────┬──────┘
                           │
          consumeResponse  │  consumeResponse
          approved = true  │  approved = false
              ┌────────────┴────────────┐
              ▼                         ▼
      ┌───────────────┐         ┌───────────────┐
      │   approved    │         │   rejected    │
      │    (终态)    │         │    (终态)    │
      └───────────────┘         └───────────────┘

没有回边。approved 之后不能改成 rejected,rejected 之后也不能反悔。想改主意就重新提一个请求——旧请求的历史保持完整。

磁盘上长什么样

JsonProtocolStore 把所有请求存进同一个文件:

.agent_tutorial/
  protocol/
    state.json          ← 全部请求的单一快照
  .protocol.lock        ← 跨进程锁(proper-lockfile 创建)

实验 state 跑出来的真实内容:

{
  "version": 1,
  "requests": [
    {
      "id": "00000000-0000-4000-8000-000000000901",
      "kind": "plan_approval",
      "sender": "alice",
      "target": "lead",
      "status": "pending",
      "content": "write the config",
      "created_at_utc": "2026-07-30T08:00:00.000Z",
      "expires_at_utc": "2026-07-30T08:05:00.000Z",
      "resolution": null
    }
  ]
}

对照着看几点:

  • 磁盘上是 snake_case(created_at_utc),内存里是 camelCase(createdAtUtc)。这是本教程一贯的约定:磁盘格式是对外契约,改它要考虑兼容;内存字段是实现细节。
  • version: 1 在最外层。以后 schema 变了,靠它判断能不能读。
  • 时间是带 Z 的 ISO 字符串,不是 Unix 时间戳。人能直接读懂,也不会出现时区歧义。
  • 默认 TTL 是 300000 毫秒,也就是 08:00:00 创建、08:05:00 过期,正好 5 分钟。

为什么是单快照,不是一个请求一个文件

第 15 章的 Mailbox 是"一条消息一个文件",这里却把所有请求塞进一个 state.json。看着不一致,其实是两种需求:

Mailbox 消息 Protocol 请求
主要操作 单条投递、单条消费 经常要问"这个队友最新的计划是哪个"
数量级 会持续增长 同时 pending 的很少
需要跨条目比较吗 不需要 需要(判断"最新")
状态怎么表达 目录名 字段

planAllowsEffectful 每次都要找"这个队友最新提交的计划"。如果是一个请求一个文件,那就得列目录、逐个读、再排序——而且这个过程还得是原子的,否则中途有人写入就会读到不一致的视图。单快照让这件事变成一次读取。

两把锁,解决两个不同的问题

同一个进程内的两个 JsonProtocolStore 实例
        |
        v
  #tails: Map<realpath, Promise>   ← 进程内 mutex(Promise 尾链)
        |
        v
  .agent_tutorial/.protocol.lock   ← 跨进程锁(proper-lockfile)
        |
        v
  临时文件 -> fsync -> 原子 rename

进程内 mutex 解决的是:同一个 Node 进程里,你 new 了两个 JsonProtocolStore(比如 Lead 一个、测试里又一个),它们同时读改写 state.json。锁的 key 是 workspace 的 realpath——所以 /home/you/proj 和 /home/you/proj/ 会被认成同一个。

跨进程锁 解决的是:两个 CLI 进程指着同一个工作区。这个进程内 mutex 管不着,得靠文件锁。

两把锁不能互相替代。只有文件锁的话,同进程内的两个实例会互相抢锁、可能死等(同一进程重入文件锁的行为不可靠);只有进程内 mutex 的话,另一个进程照样能把你的写入覆盖掉。

写入纪律和前几章一样:先写临时文件,fsync 落盘,再原子 rename 覆盖。断电只有两种结果——旧文件完整,或者新文件完整,不会出现半个 JSON。

数组顺序就是"谁更新"

快照里的 requests 是数组,保留锁内的创建顺序。判断"最新计划"用的是数组位置,不是 UUID 大小,也不是时间戳比较:

// 找最新计划:从后往前找第一个匹配的,而不是排序
latestPlanRequest(target: string) { /* 倒序扫描 requests */ }

为什么不用时间戳?因为两个请求完全可能有相同的 UTC 毫秒——测试里注入固定时钟时更是必然如此。这时候如果按时间排序,"哪个更新"就成了未定义行为。数组顺序没有这个问题。

为什么不用 UUID?UUID v4 是随机的,字典序和生成顺序毫无关系。拿它排序等于抓阄。

还有一个防御:如果注入的时钟真的倒退了(新请求的 createdAtUtc 早于快照里已有的请求),createRequest 会明确失败,而不是悄悄把新请求排到前面去。


硬规则一:先登记,再发送

不管是 shutdown 还是 plan approval,顺序都是固定的:

const request = await protocol.requestShutdown("alice");
// 到这一行时,state.json 里已经有 pending 记录了,
// 然后才由 TeammateRuntime 把 typed 消息投进 alice 的 mailbox

顺序反了会怎样

假设先发消息、后登记请求。有个特别现实的时序会出问题:

时刻 T1  Lead 把 shutdown_request 写进 alice 的 ready/
时刻 T2  alice 的 worker 恰好被唤醒,claim 了这条消息
时刻 T3  alice 校验 request_id -> state.json 里没有这条记录
         -> ProtocolNotFoundError -> 消息进 quarantine
时刻 T4  Lead 才把请求登记进 state.json

结果:磁盘上留下一条永远等不到响应的 pending 请求,和一条躺在隔离区的合法消息。而且这个 bug 只在"队友恰好在两步之间被唤醒"时出现——本地跑十次可能都碰不到一次,上了生产就开始偶发。

先登记就没有这个窗口。消息还没出现时,请求就已经在磁盘上了;任何时刻收到消息,都能查到对应请求。

发送失败怎么办:保留 pending

那反过来呢?请求登记成功了,但消息发不出去(磁盘满了、队友已经 failed 了)?

当前实现抛 ProtocolDeliveryError,并且保留那条已经持久化的 pending 请求。实验 order 的真实输出:

===== order =====
requestShutdown 抛出: ProtocolDeliveryError(protocol_delivery_error): Protocol message could not be delivered

投递失败后,请求仍然留在磁盘上:
   id=00000000-0000-4000-8000-000000000901
   kind=shutdown status=pending sender=lead target=alice

为什么不回滚掉那条请求?三个理由:

第一,回滚本身也会失败。 你打算在 catch 里删记录,但删除同样要写磁盘——磁盘满了导致发送失败,删除凭什么能成功?于是你需要一个"回滚失败"的处理分支,然后是"回滚失败的回滚"。这条路没有底。

第二,pending 记录是诊断信息。 生产上出问题时,一条"08:00 请求 alice 关机,至今 pending"的记录,比什么都没有有价值得多。

第三,它是可恢复的起点。 请求还在,人可以决定重投一次、或者手工标记放弃。悄悄删掉就什么都不剩了。

这里也说清 P16 不做的两件事:不会自动再创建一个请求来掩盖失败,也不会在后台无限重试。失败就是失败,明确抛出来让调用方知道。


typed Mailbox:协议不降级成 content 里的 JSON

第 15 章的普通消息类型一个字都没改:

MailboxMessageKind = task, message, result

P16 新增的是一个独立的枚举:

ProtocolMessageKind = shutdown_request
                      shutdown_response
                      plan_approval_request
                      plan_approval_response

实验 kinds 的实测输出:

ProtocolMessageKind   = {"ShutdownRequest":"shutdown_request","ShutdownResponse":"shutdown_response","PlanApprovalRequest":"plan_approval_request","PlanApprovalResponse":"plan_approval_response"}

注意这四个名字是成对的:xxx_request 和 xxx_response。《硬规则二:响应必须完整匹配》的校验会用到这个配对关系。

信封字段

ProtocolMailboxMessage 在共享的 transport 字段之外,多了两个:

字段 约束
id transport 自己的规范 UUID,同时是 event ID 和 idempotency key
sender / recipient 安全 Agent 名,两者不能相同
kind 必须来自 ProtocolMessageKind,普通消息类型不接受
content 非空。请求正文或反馈
created_at_utc 带时区的 UTC
request_id 对应 ProtocolRequest 的规范 UUID
approved 请求必须是 null,响应必须是明确的布尔值

最后那条 approved 的规则在构造时就强制,不是等到用的时候才检查。实验 kinds 把六种组合都试了一遍:

createProtocolMailboxMessage 的 approved 校验:
  shutdown_request + approved=null  -> 接受 kind=shutdown_request
  shutdown_request + approved=true  -> 拒绝 TypeError: Protocol response approved must be a boolean and request approved must be null
  shutdown_response + approved=true -> 接受 kind=shutdown_response
  shutdown_response + approved=null -> 拒绝 TypeError: Protocol response approved must be a boolean and request approved must be null
  plan_approval_response + false    -> 接受 kind=plan_approval_response
  message (not a protocol kind)     -> 拒绝 TypeError: ProtocolMailboxMessage kind must be a protocol kind

这个约束的意思是:请求不能自带结论,响应必须有结论。一条 shutdown_request 带着 approved: true 是无意义的——请求方凭什么替被请求方表态?反过来,一条 shutdown_response 带着 approved: null 也无意义——那你回这条消息是为了什么?

kind 是 "protocol",不是 "mailbox"

这是整章最容易被忽略、但影响最大的一个细节。看两个 payload 函数:

// 普通消息
function mailboxPayload(message: MailboxMessage) {
  return { kind: "mailbox", message_id: ..., sender: ..., /* ... */ };
}

// 协议消息
function protocolMailboxPayload(message: ProtocolMailboxMessage) {
  return { kind: "protocol", message_id: ..., protocol_kind: ...,
           request_id: ..., approved: ... };
}

实验 kinds 打出来的完整 payload:

{
  "kind": "protocol",
  "message_id": "00000000-0000-4000-8000-000000000801",
  "sender": "lead",
  "recipient": "alice",
  "protocol_kind": "shutdown_request",
  "content": "Graceful shutdown requested.",
  "created_at_utc": "2026-07-30T08:00:00.000Z",
  "request_id": "00000000-0000-4000-8000-000000000901",
  "approved": null
}
isProtocolMailboxMessage = true
eventId === id            = true
idempotencyKey === id     = true

三点:

  • 外层 kind 是 "protocol"(这是事件类型),里层 protocol_kind 才是 "shutdown_request"(这是协议动作)。两层不要混。
  • eventId、idempotencyKey 都等于消息自己的 id。和第 15 章一样:一个对象,两个身份。它既是一条 Mailbox 消息,也是一个运行时事件。
  • 判定函数要求三件事同时成立:
function isProtocolMailboxMessage(payload) {
  return payload.kind === "protocol"
      && "request_id" in payload
      && "protocol_kind" in payload;
}

普通消息 schema 里没有新增可选的协议字段。这一点很重要:如果当初选的是"给普通消息加两个可选字段 request_id?、approved?",那么每一处处理普通消息的代码都得考虑"万一这俩字段有值呢"。物理隔离成两种信封,类型系统就能帮你把分支管住。

文件 adapter 用严格联合类型解析这两种信封,协议消息继续复用原来的 ready/processing/done/quarantine 原子迁移——没有第二套目录。


硬规则二:响应必须完整匹配

一条响应想改变请求状态,六个条件必须同时成立:

# 条件 挡住什么
1 request_id 指向真实存在的请求 伪造的、或者已经被清理掉的请求
2 response kind 与 request kind 配对 拿 plan_approval_response 去结掉一个 shutdown 请求
3 response 的 sender == request 的 target 别人替被请求方表态
4 response 的 recipient == request 的 sender 把响应发给无关的第三方
5 request 仍然是 pending 重复表态、翻案
6 当前时间严格早于 expires_at_utc 迟到的响应

条件 3 和 4 合起来是一句话:响应必须是原请求的反向。请求是 lead -> alice,响应就必须是 alice -> lead,不能是别的任何组合。

五种拒绝,实测

实验 match 把五种错法各试了一次:

===== match =====
完全匹配的 shutdown_response  -> 通过 status=pending
方向反了(sender=lead)       -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
收件人错了(recipient=bob)   -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
请求 id 不存在                -> 拒绝 ProtocolNotFoundError(protocol_not_found): Protocol request does not exist: 00000000-0000-4000-8000-000000000999
响应类型不配对                -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
id 不是规范 UUID              -> 拒绝 Error: Mailbox message id must be a canonical UUID

validateResponse 只读,请求仍是 pending: pending

最后一行是重点:validateResponse 是只读的。它只回答"这条响应合不合法",不改任何状态。第一行那条"完全匹配"的响应校验通过之后,请求依然是 pending。

为什么要把校验和迁移拆开?因为 Lead 侧需要在两个不同时机做这两件事——校验发生在 drain 阶段,迁移发生在 ack 阶段。下一节专门讲这个。

唯一的写入者:consumeResponse

consumeResponse 是唯一能把 pending 改成终态的函数。它的行为分三种情况,实验 consume 全部覆盖:

===== consume =====
第一次 consume -> id=00000000-0000-4000-8000-000000000901
                  kind=shutdown status=approved sender=lead target=alice
                  resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true
同一条重试   -> id=00000000-0000-4000-8000-000000000901
                kind=shutdown status=approved sender=lead target=alice
                resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true
另一条响应 -> ProtocolStateError(protocol_state_error): Protocol request is already resolved: 00000000-0000-4000-8000-000000000901
同 id 改正文 -> ProtocolStateError(protocol_state_error): Protocol request is already resolved: 00000000-0000-4000-8000-000000000901

逐行解释:

第一次 consume —— 正常迁移。pending -> approved,写下 resolution。

同一条重试 —— 幂等返回同样的结果,不报错。这条是 ack 失败重投时的关键:同一个 message ID 再来一次,就当第一次已经成功了。判断依据是内部的 sameResponse——message ID、approved、content 三者都一致才算"同一条"。

另一条响应(不同的 message ID)—— 报 ProtocolStateError。这不是重试,这是第二次表态,必须拒绝。

同 id 改正文 —— 也报错。message ID 一样但 content 变了,说明这不是重投,是有人在伪造。sameResponse 检查 content,所以这里挡住了。

终态在磁盘上长这样:

{
  "version": 1,
  "requests": [
    {
      "id": "00000000-0000-4000-8000-000000000901",
      "kind": "shutdown",
      "sender": "lead",
      "target": "alice",
      "status": "approved",
      "content": "Graceful shutdown requested.",
      "created_at_utc": "2026-07-30T08:00:00.000Z",
      "expires_at_utc": "2026-07-30T08:05:00.000Z",
      "resolution": {
        "message_id": "00000000-0000-4000-8000-000000000801",
        "approved": true,
        "content": "Ready to shut down.",
        "resolved_at_utc": "2026-07-30T08:00:00.000Z"
      }
    }
  ]
}

resolution 里的四个字段各有用处:message_id 用于判断重试幂等,approved 是结论本身,content 保留原始反馈(驳回时就是 feedback),resolved_at_utc 是审计时间点。

两种"重复",处理方式不同

这个区分很容易糊在一起,单独强调:

情况 A:同一个 message ID 又来了一次
   原因:Mailbox ack 失败,消息被重投
   处理:幂等返回已完成的结果
   理由:这是同一次表态,transport 层的重复

情况 B:不同的 message ID,带着同一个 request_id
   原因:有人第二次表态,或者伪造
   处理:拒绝,报 protocol_state_error
   理由:这是两次表态,语义层的冲突

判断依据就是 message ID。这也解释了为什么每条协议消息都必须有自己的规范 UUID:它是幂等的锚点。

并发时谁赢

两个线程、或者两个 store 实例,同时拿着不同的响应去消费同一个请求,会怎样?

proper-lockfile 锁内只有一个能完成迁移。另一个进锁之后重新读取快照,看到状态已经是 approved,于是走"已经 resolved"的分支报错。

关键是"进锁之后重新读"。如果实现成"进锁前读快照、进锁后直接写",那第二个写入者会拿着过期的视图覆盖掉第一个的结果。这是并发代码里最经典的坑,锁的位置必须包住"读—判断—写"的整体。

过期:状态不变,但不再接受响应

实验 expire 把 TTL 注入成 1000 毫秒,然后拨时钟:

===== expire =====
createdAtUtc = 2026-07-30T08:00:00.000Z
expiresAtUtc = 2026-07-30T08:00:01.000Z (TTL 注入成 1000ms)

时钟 +500ms(未过期):
  consume -> id=00000000-0000-4000-8000-000000000901
             kind=shutdown status=approved sender=lead target=alice
             resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true

第二个请求超过 TTL 才响应:
  consume -> ProtocolExpiredError(protocol_expired): Protocol request has expired: 00000000-0000-4000-8000-000000000902
  磁盘状态仍是 = pending
  getPendingRequest ->
    ProtocolExpiredError(protocol_expired): Protocol request has expired: 00000000-0000-4000-8000-000000000902

三个观察:

  • +500ms 时还在窗口内,正常消费。
  • 超过 TTL 之后,consume 报 protocol_expired。
  • 磁盘状态仍然是 pending。过期不是一次状态迁移。

最后这点是刻意的设计。如果过期要写一次磁盘,那就必须有人定期扫描所有请求、把超时的改掉——这意味着一个后台任务、一个扫描周期、以及"扫描器挂了会怎样"的一整套问题。

把过期做成读取时的判断,这些问题全部消失。getPendingRequest 每次都拿当前时间和 expires_at_utc 比一下,过期就报错。状态字段保持 pending,如实记录"这个请求从来没有得到结论"。

坏状态一律拒绝

state.json 是磁盘上的文件,人可以手改,别的程序也可能写坏。实验 storage 试了六种坏法:

===== storage =====
多一个顶层字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
version 不是 1          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
请求少一个字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
请求多一个字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
pending 却带 resolution -> ProtocolStorageError(protocol_storage_error): Pending protocol request cannot have a resolution
requests 不是数组       -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid

恢复原快照后 listRequests = 1 条

id 生成器返回坏值:
  ProtocolStorageError(protocol_storage_error): Protocol id generator returned an invalid UUID

getRequest 用非 UUID 查询:
  ProtocolNotFoundError(protocol_not_found): Protocol request id must be a canonical UUID

注意"多一个字段"也拒绝。这是 strictObject 的效果:schema 没定义的字段一律不认。宽松解析(忽略未知字段)在这里是危险的——一个 "status": "pending", "statuz": "approved" 的拼写错误会被静默吞掉。

倒数第二条特别有意思:连注入的 ID 生成器都要校验。如果测试里注入了一个返回 "not-a-uuid" 的生成器,createRequest 会明确失败,而不是把一条 ID 非法的请求写进磁盘。不变量要在写入边界守住,不能指望调用方守规矩。

最后一条说明查询也校验:拿 "nope" 去 getRequest,直接报 protocol_not_found 并说明原因是"不是规范 UUID",而不是遍历一遍再说"没找到"。


Lead 侧:先写 history,再消费状态

这一节是本章最绕的地方,也是最值得慢慢看的地方。建议配合实验 shutdown 的输出一起读。

两个阶段,分别干什么

Lead 收到一条协议消息时,TeammateRuntime 分两步处理:

阶段一:drain(把消息取出来,发布成事件)
  claim protocol response(ready -> processing)
  validateLeadMessage      ← 只读校验!不改状态
  发布成 runtime event,进 EventInbox

阶段二:acknowledge(Loop 确认之后)
  event 先写进 Lead 的 canonical history
  acknowledgeLeadMessage -> consumeResponse   ← 这里才迁移状态
  ack Mailbox(processing -> done)

用一条竖线表示时间:

时间 ──────────────────────────────────────────────────>

drain                          acknowledge
  │                                │
  ├─ claim                         ├─ history.push(event)
  ├─ validate(只读)               ├─ consumeResponse(pending→终态)
  └─ publish event                 └─ ack transport(→ done)
                                        ▲
                                        └─ 从这里才算"协议完成"

实验 shutdown 的这两行就是这个顺序的证据:

    ack 之前,请求状态 = pending
...
[4] ack 之后:
    ... status=approved ...

为什么不能在 drain 阶段就迁移状态

假设 drain 时就把请求改成 approved,会出现这个时序:

T1  drain:consumeResponse -> 请求变成 approved  ✅ 磁盘已改
T2  发布 event 到 EventInbox
T3  Loop 准备写 history 时进程崩了              ❌ history 没有这条
T4  重启:state.json 说 approved
        Mailbox 说这条消息还在 processing
        Lead 的 history 里没有任何关于关机的记录

结果是:状态说这件事完成了,但 Lead 的对话历史里完全没有它。下一轮模型看不到"alice 已经确认关机",可能又发一次 request_shutdown。而那条 processing 消息恢复后重投,又会因为请求已 resolved 而报错。

先写 history 就避免了这个不一致:模型能看到的东西(history)永远不晚于状态真相。

反过来会怎样:ack 失败

那如果 history 写了、状态也改了,但最后一步 ack transport 失败呢?

这时候有个"半完成"状态:请求已经是 approved,但 Mailbox 里那条消息还在 processing。恢复机制会把它退回 ready,于是同一条消息会再来一次。

这次重投不会造成任何重复:

层 靠什么去重
Loop 的 history #seenEventIds 记过这个 event ID,不重复 push
ProtocolStore 同一个 message ID,consumeResponse 幂等返回
Mailbox 再 ack 一次,processing -> done

三层各自幂等,所以重投多少次结果都一样。

一个关键区别:协议事件不是 mailbox 事件

这里有个细节,读代码时特别容易看错。loop.ts 里有三处按事件类型分支的判断,它们检查的都是 kind === "mailbox":

// loop.ts:646 —— 普通 user turn 里,mailbox 事件只暂存
if (event.toPayload().kind === "mailbox" && !allowContextEvents) {
  this.#deferredRuntimeEvents.push(event);
  events = this.#eventPump.drainEvents(1);
  continue;
}

// loop.ts:668/673 —— ack 失败时,mailbox 保留"已入历史"的半状态
} catch (error) {
  if (event.toPayload().kind !== "mailbox" && isNewEvent) {
    this.#history.pop();                        // 完整回滚
    this.#seenEventIds.delete(event.eventId);
  }
  if (event.toPayload().kind === "mailbox") this.#pendingEventAcks.add(event.eventId);
  throw error;
}

而协议事件的 payload kind 是 "protocol"。所以这三处分支对协议事件都不成立,行为是:

行为 普通 mailbox 事件 协议事件
普通 user turn 里会被暂存吗 会。等显式 runEvents() 不会,直接参与本轮
ack 失败时 history 怎么处理 保留(半状态),只登记待补 ack 完整回滚:history.pop() + 删 seen id
重投之后 只补 ack,不重进 history 当成新事件重新走一遍

第二行的"完整回滚"配合队友侧的重新发布,效果是一致的:Lead 的 history 里没留下这条事件,消息回到 ready,下次重来一遍。不是半状态,而是整体重试。

这个差异不是设计缺陷,也不是遗漏。它成立的前提是协议消费本身幂等——consumeResponse 对同一个 message ID 幂等,所以"整体重试"和"补 ack"最终收敛到同一个结果。

顺便说一句:loop.ts:640 那个 contextIdentity !== undefined 的暂存分支,只有 Cron 事件会命中(contextIdentity 只在 cron.ts:417,422 设置)。协议事件不设这个字段,所以也不走那条路。

这不是"恰好一次"

这套机制的准确描述是:至少一次投递 + 稳定 ID 幂等。

它保证的是:同一个持久请求的状态迁移只发生一次。

它不保证:任意外部副作用只发生一次。举个例子——如果队友在处理某条消息时发了一封邮件,然后 ack 失败、消息重投,那么邮件会发第二封。ProtocolStore 管不着邮件服务器。

想让外部副作用也只发生一次,需要在那个副作用自己的边界上做幂等(比如给邮件带一个 idempotency key,让邮件服务去重)。这不是协议层能替你解决的问题,任何声称"分布式恰好一次"的说法都要仔细看它的前提。


shutdown:先干完手头的活,再确定性路由

为什么不能直接杀

最朴素的实现是这样:

// ❌ 不要这样
teammates.kill("alice");   // 直接 abort worker,销毁 Runner

问题在于你不知道 alice 此刻在干什么。它可能:

  • 正在 write_file 的中途——留下半个文件;
  • 刚发起一个后台任务——那个任务变成孤儿,没人认领它的结果;
  • 正在等模型返回——那次 API 调用的钱已经花了,结果丢了。

优雅关机的定义就是:让被关的一方自己选择安全点。

关机请求走的是同一个 Mailbox

shutdown 请求不走特殊通道,它就是一条写进 alice ready/ 目录的普通文件。而 worker 每次只处理一个 processing 消息。

这两件事合起来,就自动实现了"先干完手头的活":

alice 的 ready/ 目录(按 FIFO)
  ┌────────────────────────────┐
  │ 1. message: "改一下 README" │  ← worker 正在处理这条
  │ 2. shutdown_request        │  ← 排在后面,还没被 claim
  └────────────────────────────┘

worker 循环:
  claim 第 1 条 -> 调模型 -> 写文件 -> 返回 result -> ack
  claim 第 2 条 -> 发现是协议消息 -> 走 router,不调模型

不需要"检查是否有关机请求"的特判,也不需要在每个工具调用前插一个"要不要停"的检查点。FIFO 顺序 + 单条处理,就是安全点。

协议分流发生在模型调用之前

worker claim 到消息之后,第一件事是判断类型:

当前 task/message 完成并 ack
  |
  v
claim 下一条 -> 是 shutdown_request
  |
  ├─ 校验 request id、类型、双方(validateRequest)
  ├─ Teammate status = shutdown(beginShutdown)
  ├─ 发送 shutdown_response(approved=true),content = "Ready to shut down."
  ├─ ack shutdown_request(processing -> done)
  |
  └─ 不调用模型  ←←← 关键

实验 shutdown 里那行 模型调用次数 = 1 (关闭没有多花一次模型调用)就是在验证这件事。

为什么不问模型?因为关机不是模型的决定。Lead 已经决定了,队友的任务是安全退出,不是发表意见。让模型参与只会带来三个坏处:多花一次 API 调用、多一次失败可能、以及模型可能回复"我还想再干会儿"这种无法处理的答案。

响应的正文是代码写死的 "Ready to shut down."——它不是给人读的散文,是一个协议信号。

shutdown 状态不等于对象销毁

这点第 15 章讲过,这里再确认一次:

status = shutdown  的含义是「这个 worker 不再接收新消息」

它不意味着:
  ❌ Runner 对象被销毁了
  ❌ history 被清空了
  ❌ 内存被释放了

真正的资源释放由组合根统一负责,顺序是依赖的逆序:

Teammate -> Cron -> JobSupervisor

为什么逆序?因为 Teammate 依赖 JobSupervisor 跑 worker。先关 supervisor,正在跑的 worker 就会被硬中断——那不是优雅关闭,是把问题换了个位置。

五种失败,五种处理

这是本章的失败分类表,也是最需要记住的一张表:

情况 处理 队友状态 为什么
close/cancel 打断了正在发响应的 worker release 回 ready 不变 消息是好的,只是这次被打断了
协议状态存储失败(磁盘故障) release 回 ready failed 消息是好的,但这个 worker 已经不可信
响应投递失败 release 回 ready failed 同上
protocol_mismatch / not_found quarantine 不变 消息本身就是无效的,重试一万次也一样
protocol_expired / state_error quarantine 不变 同上

判断标准就一句话:

消息是好的、只是这次没成功 → release(可重试) 消息本身就是坏的 → quarantine(重试无意义)

代码里的分支长这样:

// teammates.ts worker 分支(简化)
if (isProtocolMailboxMessage(message) && !isProtocolQuarantineError(error)) {
  await store.release(message);      // 退回 ready
  this.#setStatus(worker, Failed);   // worker 标记失败
  throw error;
}
// ... 只有 quarantine 类错误才走到这里
await store.quarantine(message);
if (isProtocolMailboxMessage(message)) continue;   // 队友继续活着

实测一:坏消息进隔离区,队友不死

实验 quarantine 手动往 alice 的 ready 里塞了一条 request_id 根本不存在的响应:

===== quarantine =====
[1] alice/quarantine 里的文件数 = 1
    队友状态 = running (没被标 failed)

[2] 坏信封被隔离后,普通消息照样跑完 -> "second result"
    模型调用次数 = 2 (坏信封没有进模型)

[3] 隔离区里的信封长这样:
     {"id":"89f4d60b-952a-408f-8c67-9e3560e4ba97","sender":"lead","recipient":"alice","kind":"plan_approval_response","content":"approved","created_at_utc":"2026-08-30T12:09:45.945Z","request_id":"00000000...

三个结论:

  • 坏消息进了 quarantine,不在 ready 里反复重试。
  • 队友状态是 running,没有被标记 failed——一条坏消息不该毒死整个队友。
  • 坏消息根本没进模型。它在模型调用之前就被 router 判死了。
  • 隔离区保留完整原始信封,供事后诊断。

实测二:投递失败要 release,不能吞

实验 release 包了一层 store,让"队友回给 Lead 的 shutdown_response"这一次投递强制失败:

===== release =====
[1] 投递响应失败后:
    队友状态 = failed
    请求状态 = pending (没有被误判成 approved)
    alice/ready:      1 个文件
    alice/processing: 0 个文件
    alice/quarantine: 0 个文件

[2] 结论:请求信封回到 ready(release),等下次重投;
    状态机停在 pending,宁可重试一次,也不谎报已关闭。

对照上面那张表看:这属于"消息是好的,但 worker 不可信",所以是 release + failed 的组合。

最重要的一行是 请求状态 = pending。响应没送到,请求就不能算完成。如果这里图省事把状态改成 approved,Lead 那边就会以为 alice 已经安全关闭了——而实际上 alice 只是 failed 了,可能还留着一堆没清理的东西。

宁可让 Lead 重试一次,也不能谎报完成。 这是所有协议实现都该守的底线。


计划审批:状态先变,Runner 后恢复

三段轨迹

计划流程由队友发起,一共三段:

【第一段】队友侧
Teammate submit_plan(plan)
  -> createRequest:登记 pending 的 plan_approval 请求
  -> 发 plan_approval_request 给 lead

【第二段】Lead 侧(一个 event turn)
  -> typed request 进 history,然后 ack transport
  -> 注意:请求方向的 ack 不迁移状态,请求还是 pending
  -> Lead 决定:review_plan(request_id, approve, feedback?)
  -> 发 plan_approval_response 给原提交者

【第三段】队友 worker
  -> claim typed response
  -> consumeResponse:pending -> approved / rejected   ←←← 先改状态
  -> 权限层现在能看到新状态了
  -> 复用同一个 Runner,喂一句确定性 prompt          ←←← 后恢复执行

第三段里那两个"先"和"后"是不能换的。下一小节专门说。

为什么状态必须先变

假设顺序反了:先唤醒 Runner,再改状态。

T1  队友 worker claim 到 plan_approval_response
T2  唤醒 Runner,喂 prompt "Plan approved. Proceed."
T3  模型立刻返回 tool_call: write_file
T4  权限层检查 planAllowsEffectful -> 状态还是 pending -> DENY
T5  才去改状态

模型在 T3 做了完全正确的事——它被告知计划批准了,于是开始执行。结果被自己的权限层拒了。而且这个失败会进 history,下一轮模型看到"write_file 被拒绝",可能开始瞎猜原因、或者尝试绕路。

状态先变就没有这个窗口。模型被唤醒时,权限层看到的已经是最终状态。

队友收到的是确定性 prompt

批准和驳回的 prompt 都是代码拼的,不是 Lead 模型自由生成的:

// 批准
`Plan approved (${id}). Proceed with the approved plan.`

// 驳回(message.content 就是 Lead 填的 feedback)
`Plan rejected (${id}). Feedback: ${message.content}`

实验 plan 和 reject 分别验证了这两句:

[4] 第二次模型请求收到的 prompt:
    "Plan approved (00000000-0000-4000-8000-000000000901). Proceed with the approved plan."
===== reject =====
result = "revised plan result"
被拒绝后队友收到的 prompt = "Plan rejected (00000000-0000-4000-8000-000000000901). Feedback: 太危险,换个方案"
请求终态 -> id=00000000-0000-4000-8000-000000000901
            kind=plan_approval status=rejected sender=alice target=lead
            resolution.messageId=29e738f5-526d-46b7-bbd8-0b4e67cc96d5 approved=false

拒绝后 planAllowsEffectful = false (拒绝不等于放行)

prompt 里带上 request id 是有意的:队友的 history 里可能有多个计划,这个 id 让它能对上是哪一个。

reject 那个实验最后一行值得单独强调:被拒绝之后,effectful 工具依然是关着的。有人可能会以为"审批流程结束了就该放行"——不是的,rejected 的含义是"这个计划不许执行",而不是"审批走完了随便干"。队友要想干活,得重新 submit_plan。

review_plan 的三条约束

1. 只接受仍为 pending 的 plan request
   -> 已经批过/驳过的,不能翻案

2. 不能拿 shutdown request 的 id 来做计划审批
   -> kind 必须配对

3. 响应只发给原请求的 sender
   -> 不能把 alice 的计划批准发给 bob

这三条不是 review_plan 自己实现的——它们就是《硬规则二:响应必须完整匹配》那六个条件的自然结果。同一套校验逻辑覆盖两种协议,不需要为计划审批写一份特殊的检查。


plan_gate:Prompt 不能授予执行权限

为什么不能只靠 Prompt

先说清这条路为什么不行:

❌ system prompt: "你必须先提交计划并等待批准,才能修改文件。"

这句话的效力完全取决于模型的配合意愿。它会在三种情况下失效:

  1. 模型忘了。 上下文长了、被压缩过之后,这条约束可能不在有效注意范围内。
  2. 模型误判。 它可能认为"读个文件不算修改",然后 shell 里执行了 rm。
  3. 有人绕过。 队友的 prompt 里如果混进了外部内容(读来的文件、网页),那段内容可以试图覆盖这条约束。

安全边界不能建立在"希望对方配合"上。

plan gate 是一条真的 PermissionRule

this.#planGateRule = new PermissionRule({
  name: "plan-approval-gate",
  behavior: "deny",
  reason: "Effectful teammate tools require the latest submitted plan to be approved",
  matches: (request) => this.#requiresPlanApproval(request),
});

它通过公开的组合入口,只追加到队友策略上:

// bootstrap.ts:166-169
const teammatePermissionPolicy =
  dependencies.protocolRuntime === undefined || basePermissionPolicy === undefined
    ? basePermissionPolicy
    : basePermissionPolicy.withRules([dependencies.protocolRuntime.planGateRule]);

注意 withRules() 返回新对象,不修改原策略。实验 gate 第一行就在验证这个:

withRules 返回新对象 = true

为什么在意这个?因为 Lead 用的是 basePermissionPolicy。如果 withRules 是原地修改,Lead 的策略会被顺带污染——Lead 从来不提交计划,latestPlanRequest 永远是 undefined,那反而会让 Lead 的工具全部放行……直到某天逻辑一改,Lead 的工具集体被自己的队友计划状态拦住。不可变的策略对象从根上避免这类耦合。

withRules() 保留原策略的 ApprovalProvider 和 AuditSink。最终的决策顺序仍然是:

参数验证 -> PreToolUse -> PermissionPolicy -> dispatcher/handler -> PostToolUse
                              ▲
                              └─ plan gate 在这里,和工作区边界同级

也就是说 plan gate 的 deny 和"路径越出工作区"的 deny 发生在同一个位置:handler 和后台提交之前。工具根本不执行。

六条门控规则

// protocol.ts:382-393 的 #requiresPlanApproval,为了看清三条豁免拆成三行写
if (definition.effect === "read") return false;          // 豁免 1
if (definition.name === "send_message") return false;    // 豁免 2
if (definition.name === "submit_plan") return false;     // 豁免 3
return !(await this.planAllowsEffectful(request.context.identity));
// protocol.ts:222-226 的 planAllowsEffectful(省略了 canonicalAgentName 归一化)
const latest = await latestPlanRequest(identity);
return latest === undefined || latest.status === Approved;

翻译成规则:

# 规则 理由
1 从没提交过计划 → 全部放行 不能凭空要求所有任务都走审批。有些活根本不需要计划
2 最新计划 pending 或 rejected → effectful 工具 deny 这是门控的核心
3 read 类工具永远放行 队友得先看代码才能写出计划
4 send_message 永远放行 否则队友没法说"我卡住了"
5 submit_plan 永远放行 否则被驳回之后就再也提不了新计划——死锁
6 最新计划 approved → 按原权限执行 批了就能干,但只是恢复到原本的权限

规则 4 和 5 是防死锁的。少了任何一条,被驳回的队友就彻底动不了了。

规则 1 可能有人觉得太松。它的替代方案是"没提计划就什么都不许干",但那样队友连读文件都做不到(虽然 read 豁免了),更重要的是——spawn 时给的第一条任务可能只是"看一眼 README 告诉我它讲什么",强制这种任务走审批只是增加往返次数。

实测:四个工具,三种状态

实验 gate 造了四个代表性工具(effect 和真实队友工具面一致),在三个时点各测一次:

===== gate =====
withRules 返回新对象 = true

(1) 队友从没提交过计划:latestPlanRequest = undefined
    planAllowsEffectful = true
    read_file     -> allow source=default
    write_file    -> allow source=default
    send_message  -> allow source=default
    submit_plan   -> allow source=default

(2) 刚提交计划,还没批:status = pending
    planAllowsEffectful = false
    read_file     -> allow source=default
    write_file    -> deny  source=plan-approval-gate
    send_message  -> allow source=default
    submit_plan   -> allow source=default

(3) reviewPlan 返回时,状态还没变:status = pending

(3') 队友 worker 消费响应之后:status = approved
    planAllowsEffectful = true
    read_file     -> allow source=default
    write_file    -> allow source=default
    send_message  -> allow source=default
    submit_plan   -> allow source=default

看 (2) 这一组:只有 write_file 被拒了,source 明确写着 plan-approval-gate。另外三个照常放行,正好对应豁免 1、2、3。

(3) 和 (3') 之间的差别顺便印证了《Lead 侧:先写 history,再消费状态》的机制:reviewPlan 返回时状态还是 pending,因为它只负责投递响应;真正的迁移发生在队友 worker 消费那条响应的时候。

批准不等于提权

这点必须说清楚:

plan gate 只增加限制,不放宽任何边界。

举个具体例子。假设 write_file 在原本的策略里需要终端 ASK(人工确认)。计划批准之后:

  • plan gate 不再 deny 它 ✅
  • 但终端 ASK 仍然会弹 ✅
  • audit 照常记录 ✅

批准的效果是"把 plan gate 这一层拿掉",回到原本的权限状态,而不是"从此畅通无阻"。

批准之后又提新计划

计划 A approved -> effectful 放行
       |
       v
队友又提交计划 B -> B 成为最新计划,status = pending
       |
       v
effectful 重新被 deny  ←←← 注意

为什么?因为"最新计划"是 B,而 B 还没批。队友主动说"我要换个方案",那就得重新走审批。

这个行为偶尔会让人意外,但它是对的。反过来的设计(一次批准永久有效)意味着队友可以先提一个无害的计划骗到批准,然后提交真正想干的事——审批就变成了摆设。


idle 不等于轮询

很多多 Agent 教程的队友主循环长这样:

# ❌ 常见但不好的写法
while True:
    msg = inbox.check()
    if msg: handle(msg)
    time.sleep(1)

三个问题:

  1. 长期占着一个线程/task。 十个队友就是十个空转的循环。
  2. 关闭难管。 你得给每个循环一个退出标志,还得等它睡醒才能退出——最坏情况慢一秒。
  3. 它把下一章的东西提前了。 主动"找活"是第 17 章自驱调度的内容,塞进这里会让两章的边界糊掉。

P16 的做法是事件驱动:

队友处理完一批消息
  -> status = idle,worker task 结束
  -> 但 Runner 和 history 保留在内存里
  -> 没有 daemon、没有空转 task、没有真实 sleep

新消息(普通或协议)持久写入之后
  -> TeammateRuntime 发现 status === idle
  -> setStatus(running) + 通过共享 JobSupervisor 启动受管 worker
  -> 复用原来的 Runner,接着原来的 history 往下走

代码里就是这两个分支(send 和 deliverProtocol 各一份):

// teammates.ts:344-348
if (worker !== undefined && worker.teammate.status === TeammateStatus.Idle) {
  // idle 只表示 worker 已结束本轮循环;收到新消息时复用原 Runner 并重新拉取 mailbox。
  this.#setStatus(worker, TeammateStatus.Running);
  this.#startWorker(worker);
}

有个实践上的注意点:直接写 store 不会唤醒 idle 的 worker。唤醒逻辑在运行时的 send/deliverProtocol 里,不在 store 里。实验 quarantine 就踩过这个——它绕过运行时往 ready 里塞了一条坏消息,必须再发一条正常消息才能把 worker 叫起来。

这不是 bug。store 是纯粹的持久化层,不该知道有 worker 存在。真实场景下的写入都会经过运行时,所以不会有问题。

Lead 侧仍然沿用第 15 章的边界

Lead 的普通 Mailbox 事件 -> 显式 run_events() 边界(P15 已有)
Cron 的 wakeup           -> P14 已有,和 Mailbox 协议是两回事
P16 新增的               -> 没有「空闲 Lead 自动找活」

Cron 的 wakeup 和 Mailbox 协议容易被混为一谈,但它们解决的问题不同:Cron 是"到点了该干活",Mailbox 是"有人给你发消息了"。前者是时间驱动,后者是消息驱动。


组合根:一个 Mailbox,两种持久状态

必须共享同一个 store 对象

CLI 只构造一个 FileMailboxStore,TeammateRuntime 和 ProtocolRuntime 共享它:

const mailbox = new FileMailboxStore(workspace);

const teammates = new TeammateRuntime({
  store: mailbox,              // ← 同一个对象
  inbox: eventInbox,
  supervisor,
  cronRuntime,
});

const protocol = new ProtocolRuntime({
  store: new JsonProtocolStore(workspace),   // 协议状态是另一个 store
  team: teammates,
});

teammates.configureProtocol(protocol);       // 双向绑定

如果不共享会怎样?两个 store 实例各有自己的进程内锁,指向同一批文件。协议消息可能被一个实例写入、另一个实例读取,中间的原子性保证就断了。

所以 bootstrap 里有一条显式检查:

// bootstrap.ts:125-133
// 协议与队友必须共享同一个 TeammateRuntime 和 MailboxStore,否则请求与投递会写向不同状态。
if (
  dependencies.protocolRuntime !== undefined &&
  (dependencies.teammateRuntime === undefined ||
    dependencies.protocolRuntime.teamRuntime !== dependencies.teammateRuntime ||
    dependencies.protocolRuntime.mailboxStore !== dependencies.teammateRuntime.mailboxStore)
) {
  throw new Error("protocolRuntime must share the teammate runtime and mailbox store");
}

注意它用的是 !==(引用不等),不是比较路径字符串。两个指着同一个目录的不同实例,也会被拒绝。

四道配对检查

检查 触发条件 报错
P16 必须有 protocolRuntime capabilities.has("protocol") 且没传 protocolRuntime is required for chapter 16 or later
P15 不能传 protocolRuntime 没有 protocol 能力却传了 protocolRuntime requires chapter 16 or later
必须共享 TeammateRuntime 引用不等 must share the teammate runtime
必须共享 MailboxStore 引用不等 同上

前两条是双向的:少传报错,多传也报错。这个模式在前几章反复出现——能力位和依赖必须严格配对,不允许"传了但没用"。因为"传了没用"意味着有人以为某个功能生效了,而实际上没有。

实验 tools 验证了第一条:

[2] 少给 protocolRuntime 会怎样:
    Error: protocolRuntime is required for chapter 16 or later

P16 = P15 + 两个能力位

// profiles.ts:245-249
// P16 只在 P15 上追加协议能力,不改变 P15 普通 Mailbox 的 schema 或工具集合。
export const P16: ChapterProfile = Object.freeze({
  chapter: 16,
  capabilities: new CapabilitySet([...P15.capabilities, "protocol", "plan_gate"]),
});

实验 tools 的第一段就是在验证这个差量:

[1] 能力位差异:
    P15 有 protocol 吗 = false / plan_gate = false
    P16 有 protocol 吗 = true / plan_gate = true

Object.freeze + 展开 P15 的 capabilities,意味着 P16 不可能"漏掉"P15 的任何能力。前一章的东西全部继承,只加不减。

装配顺序

构建检查全部通过之后,bootstrap 才做三件事:

// 1. 给 Lead 注册两个协议工具(顺序固定,追加在末尾)
const [requestShutdownTool, reviewPlanTool] = protocolRuntime.leadToolDefinitions;
tools.register(requestShutdownTool);
tools.register(reviewPlanTool);

// 2. 双向绑定,校验共享依赖
teammateRuntime.configureProtocol(protocolRuntime);

// 3. 队友 factory 里追加 submit_plan + 挂上 plan gate 策略
teammateRuntime.configureRunnerFactory((name, role, sendDefinition) => {
  const teammateTools = standardTools.tools.subset(["shell", "read_file", "write_file"]);
  teammateTools.register(sendDefinition);
  teammateTools.register(protocolRuntime.submitPlanToolDefinition);
  return new AgentRunner({
    /* ... */
    permissionPolicy: teammatePermissionPolicy,   // ← 带 plan gate 的那份
    identity: name,                               // ← plan gate 靠它区分队友
  });
});

第 3 步里 identity: name 是个容易忽略但必需的细节。plan gate 的 #requiresPlanApproval 用 request.context.identity 去查"这个队友最新的计划"。如果 identity 没设或者设错,alice 的计划状态会被用来门控 bob 的工具。

subset(["shell", "read_file", "write_file"]) 是白名单裁剪,不是黑名单。以后给 Lead 加新工具时,队友不会自动获得——这个方向是对的,新工具默认不下放。


运行第 16 章

这一节从零开始,一步一步跑起来。第 0 到第 3 步不需要 API key,先把基线跑通再配凭证。

第 0 步:确认环境

node --version
npm --version

Node 需要 22 以上。本文实测:

v25.7.0

如果版本低于 22,npm run build 或 tsx 会因为语法不支持而失败。

第 1 步:进入代码目录

cd "${REPO_ROOT:?请先按导读从仓库根目录设置 REPO_ROOT}/code"

后面所有命令都在这个目录下执行。确认一下位置对不对:

test -f package.json && printf '%s\n' 'package.json 已找到'

应输出 package.json 已找到。

第 2 步:安装依赖

npm install

只需要做一次。如果之前跑过前面的章节,可以跳过。

第 3 步:先跑测试,确认基线是好的

npm run test:ch16

期望输出(本文实测):

 Test Files  49 passed (49)
      Tests  349 passed (349)
   Duration  5.45s

输出里会混进这么两行,这是正常的:

运行失败: CLI execution or cleanup failed
配置错误: Missing required settings: OPENAI_BASE_URL, OPENAI_API_KEY, OPENAI_MODEL

那是入口测试在故意验证"没配凭证时会明确报错",属于被断言的预期行为,不是你的环境有问题。

另外有个已知的偶发:Windows 上首次运行时,ch16-runtime.test.ts 可能报一次

Error: ENOENT: no such file or directory, lstat '.../.agent_tutorial/.mailboxes.lock'

这是临时目录清理和文件锁释放的竞争,重跑一次就好。我实测第一次失败、第二次 349 全过。它不影响你继续往下做,但确实是这套测试在 Windows 上的一个已知毛刺。

第 4 步:配置模型凭证

在 code/ 下建一个 .env:

touch .env

写入四行(换成你自己的):

OPENAI_BASE_URL=https://your-endpoint/v1
OPENAI_API_KEY=sk-xxxxxxxx
OPENAI_MODEL=your-model-name
OPENAI_FALLBACK_MODEL=your-fallback-model

P16 启用了模型恢复能力,四项都必需;缺少任何一项,启动时都会列出对应变量名。

第 5 步:真跑一次

cd "${REPO_ROOT:?请先按导读从仓库根目录设置 REPO_ROOT}/code"
npm run ch16 -- --prompt "创建 writer 队友,先提交修改 README 的计划,批准后执行并优雅关闭"

这条 prompt 是刻意设计的,它会依次触发本章全部四种协议消息:

spawn_teammate       -> 创建队友
(队友)submit_plan   -> plan_approval_request
review_plan          -> plan_approval_response
request_shutdown     -> shutdown_request
(队友)自动响应       -> shutdown_response

你应该看到什么

具体措辞取决于模型,但这几件事应该都出现:

  • Lead 调用 spawn_teammate,得到一个"已创建,不等待完成"的返回;
  • 队友的计划以 plan_approval_request 的形式回到 Lead;
  • Lead 调用 review_plan,approve 是 true;
  • 队友继续执行并交回结果;
  • Lead 调用 request_shutdown,随后收到 approved: true 的响应。

如果模型跳过了 review_plan 直接让队友干活,你会看到队友的 write_file 被 deny,reason 里带 plan-approval-gate——这恰好证明门控是真的在工作。

第 6 步:看磁盘上留下了什么

find .agent_tutorial -print

关键的两处:

.agent_tutorial/protocol/state.json          ← 协议状态真相
.agent_tutorial/mailboxes/<name>/{ready,processing,done,quarantine}/  ← 消息 transport

直接看状态文件:

cat .agent_tutorial/protocol/state.json

对照《ProtocolRequest:持久请求才是状态真相》那份 JSON 看,你应该能认出每个字段。重点看两处:

  • 每条请求的 status,以及终态请求的 resolution 里是谁、批没批;
  • requests 数组的顺序——它就是创建顺序。

第 7 步:再跑一次,看恢复

npm run ch16 -- --prompt "看一下 protocol 状态里有哪些请求"

因为 state.json 是持久的,上一轮的请求还在。这一步能直观感受到"协议状态不随进程消失"。

若想从干净状态重来,先停止 Agent,再把整个状态目录改名保存:

backup=".agent_tutorial.backup.$(date +%Y%m%d%H%M%S)"
test ! -e "$backup" && mv .agent_tutorial "$backup"

原有队友消息、协议状态、后台任务和 Cron 记录仍在备份目录中。

通用入口

固定章节入口 npm run ch16 之外,还有一个通用入口:

cd "${REPO_ROOT:?请先按导读从仓库根目录设置 REPO_ROOT}/code"
npm run agent-tutorial -- run --chapter 16 --prompt "创建 writer 队友,先提交修改 README 的计划,批准后执行并优雅关闭"

两个入口共享同一套装配和同一份 transport,只是命令行形式不同。ch16-entry.test.ts 断言了这一点。

wakeup 闭环:协议消息与 Cron 都接入 Runner

当前 CLI 在构造 Runner 后同时绑定 teammateRuntime.bindWakeup(...) 与 cronRuntime.bindWakeup(...)。队友协议消息送达 Lead 后会请求独立 event turn;Cron 仍按时间触发,两者都由同一个 Runner 的运行锁串行化。

如果你在自己的宿主里手动装配运行时,也必须保留 Teammate wakeup 绑定,否则消息虽会持久化,却只能等下一次 run_events() 或重启恢复。

常见报错排查

报错 原因 怎么解决
Missing required settings: OPENAI_BASE_URL, ... 没建 .env 或缺字段 回到第 4 步,三行都要有
protocolRuntime is required for chapter 16 or later 自己搭运行时时漏传 protocolRuntime 参考《组合根:一个 Mailbox,两种持久状态》的写法
protocolRuntime must share the teammate runtime and mailbox store new 了两个 FileMailboxStore 只 new 一个,两处传同一个对象
ProtocolStateError: Unknown or unavailable teammate: alice 队友还没 spawn 就调 submit_plan 先 spawn,等第一轮 result 之后再提交计划
ProtocolDeliveryError: Protocol message could not be delivered 目标队友已 failed/shutdown,或磁盘故障 查队友状态。pending 请求会保留,可诊断
ProtocolNotFoundError: Protocol request does not exist 用了错的 request_id 从 state.json 里拿准确的 id
ProtocolExpiredError: Protocol request has expired 超过 5 分钟才响应 重新提一个请求。旧请求保持 pending
ProtocolStorageError: Protocol state is invalid 手改坏了 state.json 对照《ProtocolRequest:持久请求才是状态真相》的字段修,或删掉整个 protocol/ 目录重来
write_file 被 deny,reason 带 plan-approval-gate 最新计划是 pending 或 rejected 这是正常行为。先 review_plan 批准
ENOENT: ... .mailboxes.lock(测试里偶发) Windows 临时目录清理竞争 重跑 npm run test:ch16
AgentRunner is closed 在 close() 之后又调用了 run 检查关闭顺序:Teammate -> Cron -> JobSupervisor

14 个动手小实验

前面所有结论都不用信我的。这一节把它们全部变成你自己机器上能跑出来的输出。

全部实验不需要 API key,因为用的是一个脚本化的假模型。

准备:先建一个探测脚本

cd "${REPO_ROOT:?请先按导读从仓库根目录设置 REPO_ROOT}/code"
touch scripts/probe-ch16.mts

把下面这段写进 scripts/probe-ch16.mts。这是所有实验共用的头部,只写一次:

// scripts/probe-ch16.mts —— 第 16 章探测脚本(临时用,跑完可删)
import { mkdtemp, rm, readdir, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { FileMailboxStore } from "../chapters/ch16/src/adapters/mailbox-json.ts";
import { JsonProtocolStore } from "../chapters/ch16/src/adapters/protocol-json.ts";
import { JsonBackgroundJobStore } from "../chapters/ch16/src/adapters/background-json.ts";
import { JsonCronStore } from "../chapters/ch16/src/adapters/cron-json.ts";
import { EventInbox } from "../chapters/ch16/src/core/events.ts";
import { AgentRunner } from "../chapters/ch16/src/core/loop.ts";
import { assistantMessage } from "../chapters/ch16/src/core/messages.ts";
import {
  PermissionDecision,
  PermissionPolicy,
  PermissionRequest,
} from "../chapters/ch16/src/core/permissions.ts";
import { ToolRegistry, toolSuccess } from "../chapters/ch16/src/core/tools.ts";
import { JobSupervisor } from "../chapters/ch16/src/features/background.ts";
import { CronRuntime } from "../chapters/ch16/src/features/cron.ts";
import {
  MailboxMessageKind,
  ProtocolMessageKind,
  createProtocolMailboxMessage,
  isProtocolMailboxMessage,
} from "../chapters/ch16/src/features/mailbox.ts";
import {
  ProtocolRequestKind,
  ProtocolRequestStatus,
  ProtocolRuntime,
} from "../chapters/ch16/src/features/protocol.ts";
import { TeammateRuntime, TeammateStatus } from "../chapters/ch16/src/features/teammates.ts";

async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
  const dir = await mkdtemp(join(tmpdir(), "ch16-probe-"));
  try { return await fn(dir); } finally { await rm(dir, { recursive: true, force: true }); }
}

// 轮询等某个条件成立,最多 5 秒;异步实验必备
async function waitFor(
  predicate: () => boolean | Promise<boolean>,
  label: string,
): Promise<void> {
  const deadline = Date.now() + 5_000;
  while (!(await predicate())) {
    if (Date.now() > deadline) throw new Error(`timeout waiting for ${label}`);
    await new Promise((resolve) => setTimeout(resolve, 5));
  }
}

// 让 UUID 可预测,输出才能对照
function seqId(start = 0x801): () => string {
  let next = start;
  return () => {
    const hex = (next++).toString(16).padStart(12, "0");
    return `00000000-0000-4000-8000-${hex}`;
  };
}

const EXPERIMENT = process.argv[2] ?? "all";
function section(name: string): boolean {
  const hit = EXPERIMENT === "all" || EXPERIMENT === name;
  if (hit) console.log(`\n===== ${name} =====`);
  return hit;
}

// 一个脚本化的假模型:按顺序返回预设回复,同时记录收到的请求
class ScriptModel {
  requests: any[] = [];
  #replies: string[];
  constructor(...replies: string[]) { this.#replies = [...replies]; }
  async complete(request: any) {
    this.requests.push(request);
    const text = this.#replies.shift();
    if (text === undefined) throw new Error("unexpected model request");
    return Object.freeze({ message: assistantMessage(text), finishReason: "stop" });
  }
}

// 打印目录树,空目录标 (空)
async function tree(dir: string, prefix = ""): Promise<void> {
  const entries = (await readdir(dir, { withFileTypes: true }))
    .sort((a, b) => a.name.localeCompare(b.name));
  if (entries.length === 0) { console.log(`${prefix}(空)`); return; }
  for (const entry of entries) {
    console.log(`${prefix}${entry.name}${entry.isDirectory() ? "/" : ""}`);
    if (entry.isDirectory()) await tree(join(dir, entry.name), `${prefix}  `);
  }
}

// 完整装配:一个 EventInbox、一个 Mailbox、Cron/Teammate/Protocol 全部共享
function makeRuntime(root: string, model: ScriptModel, options: {
  readonly protocolStore?: any;
  readonly mailboxStore?: any;
} = {}) {
  const inbox = new EventInbox();
  const supervisor = new JobSupervisor({ store: new JsonBackgroundJobStore(root), inbox });
  const cron = new CronRuntime({
    store: new JsonCronStore(root), inbox, supervisor,
    clock: { now: () => new Date("2026-07-30T08:00:00.000Z") },
  });
  const mailbox = options.mailboxStore ?? new FileMailboxStore(root);
  const teammates = new TeammateRuntime({ store: mailbox, inbox, supervisor, cronRuntime: cron });
  const protocol = new ProtocolRuntime({
    store: options.protocolStore ?? new JsonProtocolStore(root),
    team: teammates,
  });
  // 协议层与队友层必须是同一个宿主对象,configureProtocol 会校验
  teammates.configureProtocol(protocol);
  // 队友 Runner 只拿到 send_message + submit_plan,和组合根裁剪一致
  teammates.configureRunnerFactory((name, role, send) => {
    const tools = new ToolRegistry();
    tools.register(send);
    tools.register(protocol.submitPlanToolDefinition);
    return new AgentRunner({
      model, tools, systemPrompt: `You are ${name}, serving as ${role}.`,
      workspace: root, identity: name,
    });
  });
  return { inbox, supervisor, cron, mailbox, teammates, protocol };
}

async function closeRuntime(runtime: any): Promise<void> {
  await runtime.teammates.close();
  await runtime.cron.close();
  await runtime.supervisor.close();
}

// 读取 state.json 原文
async function readState(root: string): Promise<string> {
  return await readFile(join(root, ".agent_tutorial", "protocol", "state.json"), "utf8");
}

// 中文字符占两列,按显示宽度补空格,输出才对得齐
function width(text: string): number {
  let total = 0;
  for (const char of text) total += /[ -鿿＀-⦆]/.test(char) ? 2 : 1;
  return total;
}
function pad(text: string, columns: number): string {
  return text + " ".repeat(Math.max(1, columns - width(text)));
}

// 打印请求关键字段,避免整段 JSON 淹没重点
function showRequest(label: string, request: any): void {
  const indent = " ".repeat(width(label));
  console.log(`${label} id=${request.id}`);
  console.log(`${indent} kind=${request.kind} status=${request.status}` +
    ` sender=${request.sender} target=${request.target}`);
  if (request.resolution !== null) {
    console.log(`${indent} resolution.messageId=${request.resolution.messageId}` +
      ` approved=${request.resolution.approved}`);
  }
}

function errorLine(error: unknown): string {
  const code = error instanceof Error ? Reflect.get(error, "errorCode") : undefined;
  const name = error instanceof Error ? error.name : "unknown";
  return `${name}${code === undefined ? "" : `(${code})`}: ${
    error instanceof Error ? error.message : String(error)}`;
}

头部里有四个地方值得解释:

makeRuntime 是本章组合根的最小复刻。它体现了《组合根:一个 Mailbox,两种持久状态》讲的共享关系:一个 EventInbox、一个 FileMailboxStore,configureProtocol 做双向绑定,队友 factory 只给 send_message + submit_plan。

seqId 让 UUID 变成 ...0801、...0802 这种可预测的序列。真实运行时是随机 UUID,输出没法对照;注入之后你看到的 id 和本文完全一致。

ScriptModel 是假模型。它按顺序吐预设回复,同时把收到的每个请求存进 requests 数组——很多实验靠数这个数组的长度来证明"模型没被调用"。

width / pad 处理中文对齐。padEnd 数的是 UTF-16 码元,中文一个字算 1;终端里中文占两列。不修就会看到表格歪掉。

运行方式是 npx tsx scripts/probe-ch16.mts <实验名>。下面 14 个实验各自往脚本里追加一段,每段都带 section("名字") 开关,互不干扰。

实验 1(kinds):封闭集合与信封校验

追加:

// ---------- 实验 1(kinds):协议的封闭集合与信封校验 ----------
if (section("kinds")) {
  console.log("ProtocolRequestKind   =", JSON.stringify(ProtocolRequestKind));
  console.log("ProtocolRequestStatus =", JSON.stringify(ProtocolRequestStatus));
  console.log("ProtocolMessageKind   =", JSON.stringify(ProtocolMessageKind));
  console.log("\ncreateProtocolMailboxMessage 的 approved 校验:");
  const base = {
    id: "00000000-0000-4000-8000-000000000801",
    sender: "lead", recipient: "alice",
    content: "Graceful shutdown requested.",
    createdAtUtc: new Date("2026-07-30T08:00:00.000Z"),
    requestId: "00000000-0000-4000-8000-000000000901",
  };
  const cases: Array<[string, any, any]> = [
    ["shutdown_request + approved=null", ProtocolMessageKind.ShutdownRequest, null],
    ["shutdown_request + approved=true", ProtocolMessageKind.ShutdownRequest, true],
    ["shutdown_response + approved=true", ProtocolMessageKind.ShutdownResponse, true],
    ["shutdown_response + approved=null", ProtocolMessageKind.ShutdownResponse, null],
    ["plan_approval_response + false", ProtocolMessageKind.PlanApprovalResponse, false],
    ["message (not a protocol kind)", MailboxMessageKind.Message, null],
  ];
  for (const [label, kind, approved] of cases) {
    try {
      const message = createProtocolMailboxMessage({ ...base, kind, approved });
      console.log(`  ${pad(label, 34)}-> 接受 kind=${message.kind}`);
    } catch (error) {
      console.log(`  ${pad(label, 34)}-> 拒绝 ${errorLine(error)}`);
    }
  }
  const message = createProtocolMailboxMessage({
    ...base, kind: ProtocolMessageKind.ShutdownRequest, approved: null,
  });
  console.log("\n协议 payload(注意 kind 是 protocol,不是 mailbox):");
  console.log(JSON.stringify(message.toPayload(), null, 2));
  console.log("isProtocolMailboxMessage =", isProtocolMailboxMessage(message));
  console.log("eventId === id            =", message.eventId === message.id);
  console.log("idempotencyKey === id     =", message.idempotencyKey === message.id);
}

跑:

npx tsx scripts/probe-ch16.mts kinds

真实输出:

===== kinds =====
ProtocolRequestKind   = {"Shutdown":"shutdown","PlanApproval":"plan_approval"}
ProtocolRequestStatus = {"Pending":"pending","Approved":"approved","Rejected":"rejected"}
ProtocolMessageKind   = {"ShutdownRequest":"shutdown_request","ShutdownResponse":"shutdown_response","PlanApprovalRequest":"plan_approval_request","PlanApprovalResponse":"plan_approval_response"}

createProtocolMailboxMessage 的 approved 校验:
  shutdown_request + approved=null  -> 接受 kind=shutdown_request
  shutdown_request + approved=true  -> 拒绝 TypeError: Protocol response approved must be a boolean and request approved must be null
  shutdown_response + approved=true -> 接受 kind=shutdown_response
  shutdown_response + approved=null -> 拒绝 TypeError: Protocol response approved must be a boolean and request approved must be null
  plan_approval_response + false    -> 接受 kind=plan_approval_response
  message (not a protocol kind)     -> 拒绝 TypeError: ProtocolMailboxMessage kind must be a protocol kind

协议 payload(注意 kind 是 protocol,不是 mailbox):
{
  "kind": "protocol",
  "message_id": "00000000-0000-4000-8000-000000000801",
  "sender": "lead",
  "recipient": "alice",
  "protocol_kind": "shutdown_request",
  "content": "Graceful shutdown requested.",
  "created_at_utc": "2026-07-30T08:00:00.000Z",
  "request_id": "00000000-0000-4000-8000-000000000901",
  "approved": null
}
isProtocolMailboxMessage = true
eventId === id            = true
idempotencyKey === id     = true

要验证的: 三个枚举都是封闭集合;approved 的规则在构造时就强制(请求必须 null,响应必须布尔);普通消息类型不能当协议类型用;payload 外层 kind 是 protocol,protocol_kind 才是具体动作;一个对象同时是消息、事件和幂等键。

实验 2(state):一个请求在磁盘上长什么样

追加:

// ---------- 实验 2(state):一个请求在磁盘上长什么样 ----------
if (section("state")) {
  await withTempDir(async (root) => {
    const store = new JsonProtocolStore(root, {
      idGenerator: seqId(0x901),
      clock: () => new Date("2026-07-30T08:00:00.000Z"),
    });
    const request = await store.createRequest({
      kind: ProtocolRequestKind.PlanApproval,
      sender: "alice", target: "lead", content: "write the config",
    });
    showRequest("createRequest ->", request);
    console.log("createdAtUtc =", request.createdAtUtc.toISOString());
    console.log("expiresAtUtc =", request.expiresAtUtc.toISOString(),
      "(默认 TTL 300000ms = 5 分钟)");
    console.log("\n磁盘布局:");
    await tree(join(root, ".agent_tutorial"), "  ");
    console.log("\nstate.json 内容:");
    console.log(await readState(root));
  });
}

跑:

npx tsx scripts/probe-ch16.mts state

真实输出:

===== state =====
createRequest -> id=00000000-0000-4000-8000-000000000901
                 kind=plan_approval status=pending sender=alice target=lead
createdAtUtc = 2026-07-30T08:00:00.000Z
expiresAtUtc = 2026-07-30T08:05:00.000Z (默认 TTL 300000ms = 5 分钟)

磁盘布局:
  protocol/
    state.json

state.json 内容:
{
  "version": 1,
  "requests": [
    {
      "id": "00000000-0000-4000-8000-000000000901",
      "kind": "plan_approval",
      "sender": "alice",
      "target": "lead",
      "status": "pending",
      "content": "write the config",
      "created_at_utc": "2026-07-30T08:00:00.000Z",
      "expires_at_utc": "2026-07-30T08:05:00.000Z",
      "resolution": null
    }
  ]
}

要验证的: 新建请求一定是 pending 且 resolution: null;expiresAtUtc - createdAtUtc 正好 5 分钟;磁盘上是单个 state.json(不是一请求一文件);字段名是 snake_case,时间带 Z;最外层有 version: 1。

顺手改个实验:把 clock 换成 () => new Date(),再跑一次,看 TTL 是不是还是准 5 分钟。

实验 3(order):先登记,再发送

追加:

// ---------- 实验 3(order):先登记,再发送 ----------
if (section("order")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result");
    const runtime = makeRuntime(root, model, {
      protocolStore: new JsonProtocolStore(root, {
        idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
      }),
    });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      // 把投递打坏:请求已登记,消息发不出去
      const original = runtime.teammates.deliverProtocol.bind(runtime.teammates);
      (runtime.teammates as any).deliverProtocol = async () => {
        throw new Error("disk on fire");
      };
      try {
        await runtime.protocol.requestShutdown("alice");
      } catch (error) {
        console.log("requestShutdown 抛出:", errorLine(error));
      }
      console.log("\n投递失败后,请求仍然留在磁盘上:");
      const all = await runtime.protocol.store.listRequests();
      for (const item of all) showRequest("  ", item);
      console.log("\nstate.json:");
      console.log(await readState(root));
      (runtime.teammates as any).deliverProtocol = original;
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts order

真实输出:

===== order =====
requestShutdown 抛出: ProtocolDeliveryError(protocol_delivery_error): Protocol message could not be delivered

投递失败后,请求仍然留在磁盘上:
   id=00000000-0000-4000-8000-000000000901
   kind=shutdown status=pending sender=lead target=alice

state.json:
{
  "version": 1,
  "requests": [
    {
      "id": "00000000-0000-4000-8000-000000000901",
      "kind": "shutdown",
      "sender": "lead",
      "target": "alice",
      "status": "pending",
      "content": "Graceful shutdown requested.",
      "created_at_utc": "2026-07-30T08:00:00.000Z",
      "expires_at_utc": "2026-07-30T08:05:00.000Z",
      "resolution": null
    }
  ]
}

要验证的: 投递失败时抛的是有 errorCode 的 ProtocolDeliveryError,不是裸 Error;请求没有被回滚,pending 记录完整留在磁盘上;listRequests 能查到它。这就是《硬规则一:先登记,再发送》说的"发送失败保留 pending"。

实验 4(match):五种错法都被挡住

追加:

// ---------- 实验 4(match):响应必须完整匹配 ----------
if (section("match")) {
  await withTempDir(async (root) => {
    const store = new JsonProtocolStore(root, {
      idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
    });
    const request = await store.createRequest({
      kind: ProtocolRequestKind.Shutdown,
      sender: "lead", target: "alice", content: "Graceful shutdown requested.",
    });
    const good = {
      id: "00000000-0000-4000-8000-000000000801",
      sender: "alice", recipient: "lead",
      kind: ProtocolMessageKind.ShutdownResponse,
      content: "Ready to shut down.",
      createdAtUtc: new Date("2026-07-30T08:00:01.000Z"),
      requestId: request.id, approved: true,
    };
    const cases: Array<[string, any]> = [
      ["完全匹配的 shutdown_response", good],
      ["方向反了(sender=lead)", { ...good, sender: "lead", recipient: "alice" }],
      ["收件人错了(recipient=bob)", { ...good, recipient: "bob" }],
      ["请求 id 不存在", { ...good, requestId: "00000000-0000-4000-8000-000000000999" }],
      ["响应类型不配对", { ...good, kind: ProtocolMessageKind.PlanApprovalResponse }],
      ["id 不是规范 UUID", { ...good, requestId: "not-a-uuid" }],
    ];
    for (const [label, input] of cases) {
      try {
        const message = createProtocolMailboxMessage(input);
        const validated = await store.validateResponse(message);
        console.log(`${pad(label, 30)}-> 通过 status=${validated.status}`);
      } catch (error) {
        console.log(`${pad(label, 30)}-> 拒绝 ${errorLine(error)}`);
      }
    }
    console.log("\nvalidateResponse 只读,请求仍是 pending:",
      (await store.getRequest(request.id)).status);
  });
}

跑:

npx tsx scripts/probe-ch16.mts match

真实输出:

===== match =====
完全匹配的 shutdown_response  -> 通过 status=pending
方向反了(sender=lead)       -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
收件人错了(recipient=bob)   -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
请求 id 不存在                -> 拒绝 ProtocolNotFoundError(protocol_not_found): Protocol request does not exist: 00000000-0000-4000-8000-000000000999
响应类型不配对                -> 拒绝 ProtocolMismatchError(protocol_mismatch): Protocol message does not match request
id 不是规范 UUID              -> 拒绝 Error: Mailbox message id must be a canonical UUID
validateResponse 只读,请求仍是 pending: pending

要验证的: 第一行"通过"但 status=pending——校验通过不等于状态变了;错方向、错收件人、错类型都报 protocol_mismatch;不存在的 id 报 protocol_not_found(错误码不同,因为处理方式不同:mismatch 和 not_found 都进 quarantine,但诊断信息该区分开);非 UUID 在构造阶段就被 createProtocolMailboxMessage 挡了,根本没走到 store。

自己改一下:把 good 的 approved 改成 null 再跑,看是不是在构造阶段就失败。

实验 5(consume):只迁移一次,同一条幂等

追加:

// ---------- 实验 5(consume):只迁移一次,同一条响应幂等 ----------
if (section("consume")) {
  await withTempDir(async (root) => {
    const store = new JsonProtocolStore(root, {
      idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
    });
    const request = await store.createRequest({
      kind: ProtocolRequestKind.Shutdown,
      sender: "lead", target: "alice", content: "Graceful shutdown requested.",
    });
    const response = createProtocolMailboxMessage({
      id: "00000000-0000-4000-8000-000000000801",
      sender: "alice", recipient: "lead",
      kind: ProtocolMessageKind.ShutdownResponse,
      content: "Ready to shut down.",
      createdAtUtc: new Date("2026-07-30T08:00:01.000Z"),
      requestId: request.id, approved: true,
    });
    showRequest("第一次 consume ->", await store.consumeResponse(response));
    showRequest("同一条重试   ->", await store.consumeResponse(response));
    // 换一个 message id,代表“另一条响应”想再决一次
    const other = createProtocolMailboxMessage({
      ...{ id: "00000000-0000-4000-8000-000000000802",
        sender: "alice", recipient: "lead",
        kind: ProtocolMessageKind.ShutdownResponse,
        content: "Ready to shut down.",
        createdAtUtc: new Date("2026-07-30T08:00:02.000Z"),
        requestId: request.id, approved: true },
    });
    try {
      await store.consumeResponse(other);
    } catch (error) {
      console.log("另一条响应 ->", errorLine(error));
    }
    // 正文被改过,也算不上同一条
    const tampered = createProtocolMailboxMessage({
      ...response, id: response.id, content: "Ready to shut down!!!",
    });
    try {
      await store.consumeResponse(tampered);
    } catch (error) {
      console.log("同 id 改正文 ->", errorLine(error));
    }
    console.log("\nstate.json(终态带唯一 resolution):");
    console.log(await readState(root));
  });
}

跑:

npx tsx scripts/probe-ch16.mts consume

真实输出:

===== consume =====
第一次 consume -> id=00000000-0000-4000-8000-000000000901
                  kind=shutdown status=approved sender=lead target=alice
                  resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true
同一条重试   -> id=00000000-0000-4000-8000-000000000901
                kind=shutdown status=approved sender=lead target=alice
                resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true
另一条响应 -> ProtocolStateError(protocol_state_error): Protocol request is already resolved: 00000000-0000-4000-8000-000000000901
同 id 改正文 -> ProtocolStateError(protocol_state_error): Protocol request is already resolved: 00000000-0000-4000-8000-000000000901

state.json(终态带唯一 resolution):
{
  "version": 1,
  "requests": [
    {
      "id": "00000000-0000-4000-8000-000000000901",
      "kind": "shutdown",
      "sender": "lead",
      "target": "alice",
      "status": "approved",
      "content": "Graceful shutdown requested.",
      "created_at_utc": "2026-07-30T08:00:00.000Z",
      "expires_at_utc": "2026-07-30T08:05:00.000Z",
      "resolution": {
        "message_id": "00000000-0000-4000-8000-000000000801",
        "approved": true,
        "content": "Ready to shut down.",
        "resolved_at_utc": "2026-07-30T08:00:00.000Z"
      }
    }
  ]
}

要验证的: 同一条响应连消费两次,第二次幂等返回相同结果,不报错;换个 message ID 就被拒(protocol_state_error);message ID 相同但正文被改也被拒——sameResponse 检查的是 message ID + approved + content 三者;磁盘上只有一个 resolution,message_id 指向第一条。

这个实验和实验 4 一起解释了《Lead 侧:先写 history,再消费状态》那句话:ack 失败重投是安全的,因为幂等的判断依据是 message ID,而不是"这个请求处理过没有"。

实验 6(expire):过期之后状态仍是 pending

追加:

// ---------- 实验 6(expire):过期请求不能再推进 ----------
if (section("expire")) {
  await withTempDir(async (root) => {
    let now = new Date("2026-07-30T08:00:00.000Z");
    const store = new JsonProtocolStore(root, {
      idGenerator: seqId(0x901), clock: () => now, requestTtlMs: 1_000,
    });
    const request = await store.createRequest({
      kind: ProtocolRequestKind.Shutdown,
      sender: "lead", target: "alice", content: "Graceful shutdown requested.",
    });
    console.log("createdAtUtc =", request.createdAtUtc.toISOString());
    console.log("expiresAtUtc =", request.expiresAtUtc.toISOString(), "(TTL 注入成 1000ms)");
    const response = createProtocolMailboxMessage({
      id: "00000000-0000-4000-8000-000000000801",
      sender: "alice", recipient: "lead",
      kind: ProtocolMessageKind.ShutdownResponse,
      content: "Ready to shut down.",
      createdAtUtc: new Date("2026-07-30T08:00:00.500Z"),
      requestId: request.id, approved: true,
    });
    now = new Date("2026-07-30T08:00:00.500Z");
    console.log("\n时钟 +500ms(未过期):");
    showRequest("  consume ->", await store.consumeResponse(response));
    // 换一个新请求,让它真的过期
    now = new Date("2026-07-30T08:00:01.000Z");
    const second = await store.createRequest({
      kind: ProtocolRequestKind.Shutdown,
      sender: "lead", target: "bob", content: "Graceful shutdown requested.",
    });
    now = new Date("2026-07-30T08:00:02.000Z");
    const late = createProtocolMailboxMessage({
      id: "00000000-0000-4000-8000-000000000802",
      sender: "bob", recipient: "lead",
      kind: ProtocolMessageKind.ShutdownResponse,
      content: "Ready to shut down.",
      createdAtUtc: new Date("2026-07-30T08:00:02.000Z"),
      requestId: second.id, approved: true,
    });
    console.log("\n第二个请求超过 TTL 才响应:");
    try {
      await store.consumeResponse(late);
    } catch (error) {
      console.log("  consume ->", errorLine(error));
    }
    console.log("  磁盘状态仍是 =", (await store.getRequest(second.id)).status);
    console.log("  getPendingRequest ->");
    try {
      await store.getPendingRequest(second.id);
    } catch (error) {
      console.log("   ", errorLine(error));
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts expire

真实输出:

===== expire =====
createdAtUtc = 2026-07-30T08:00:00.000Z
expiresAtUtc = 2026-07-30T08:00:01.000Z (TTL 注入成 1000ms)

时钟 +500ms(未过期):
  consume -> id=00000000-0000-4000-8000-000000000901
             kind=shutdown status=approved sender=lead target=alice
             resolution.messageId=00000000-0000-4000-8000-000000000801 approved=true

第二个请求超过 TTL 才响应:
  consume -> ProtocolExpiredError(protocol_expired): Protocol request has expired: 00000000-0000-4000-8000-000000000902
  磁盘状态仍是 = pending
  getPendingRequest ->
    ProtocolExpiredError(protocol_expired): Protocol request has expired: 00000000-0000-4000-8000-000000000902

要验证的: TTL 可以注入(测试不需要真的等 5 分钟);窗口内正常消费;超时报 protocol_expired;磁盘状态仍然是 pending——过期是读取时的判断,不写磁盘;getPendingRequest 也会因为过期而失败,所以后续所有依赖它的路径都拿不到这个请求。

自己改一下:把第二个请求的响应时间改成 08:00:00.999Z(刚好在窗口内最后一毫秒),看能不能消费成功。再改成 08:00:01.000Z(正好等于过期时刻),验证《ProtocolRequest:持久请求才是状态真相》说的"左闭右开"。

实验 7(storage):坏快照一律拒绝

追加:

// ---------- 实验 7(storage):坏快照与坏 id 生成器 ----------
if (section("storage")) {
  await withTempDir(async (root) => {
    const store = new JsonProtocolStore(root, {
      idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
    });
    await store.createRequest({
      kind: ProtocolRequestKind.Shutdown,
      sender: "lead", target: "alice", content: "Graceful shutdown requested.",
    });
    const statePath = join(root, ".agent_tutorial", "protocol", "state.json");
    const original = JSON.parse(await readFile(statePath, "utf8"));
    const broken: Array<[string, unknown]> = [
      ["多一个顶层字段", { ...original, extra: true }],
      ["version 不是 1", { ...original, version: 2 }],
      ["请求少一个字段", { version: 1, requests: [{ id: original.requests[0].id }] }],
      ["请求多一个字段", { version: 1,
        requests: [{ ...original.requests[0], note: "hi" }] }],
      ["pending 却带 resolution", { version: 1, requests: [{ ...original.requests[0],
        resolution: { message_id: original.requests[0].id, approved: true,
          content: "x", resolved_at_utc: "2026-07-30T08:00:01.000Z" } }] }],
      ["requests 不是数组", { version: 1, requests: {} }],
    ];
    for (const [label, content] of broken) {
      await writeFile(statePath, JSON.stringify(content), "utf8");
      try {
        await store.listRequests();
        console.log(`${pad(label, 24)}-> 加载成功(不应该发生)`);
      } catch (error) {
        console.log(`${pad(label, 24)}-> ${errorLine(error)}`);
      }
    }
    await writeFile(statePath, JSON.stringify(original), "utf8");
    console.log("\n恢复原快照后 listRequests =", (await store.listRequests()).length, "条");
    console.log("\nid 生成器返回坏值:");
    const badStore = new JsonProtocolStore(root, { idGenerator: () => "nope" });
    try {
      await badStore.createRequest({
        kind: ProtocolRequestKind.Shutdown,
        sender: "lead", target: "alice", content: "Graceful shutdown requested.",
      });
    } catch (error) {
      console.log(" ", errorLine(error));
    }
    console.log("\ngetRequest 用非 UUID 查询:");
    try {
      await store.getRequest("not-a-uuid");
    } catch (error) {
      console.log(" ", errorLine(error));
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts storage

真实输出:

===== storage =====
多一个顶层字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
version 不是 1          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
请求少一个字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
请求多一个字段          -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid
pending 却带 resolution -> ProtocolStorageError(protocol_storage_error): Pending protocol request cannot have a resolution
requests 不是数组       -> ProtocolStorageError(protocol_storage_error): Protocol state is invalid

恢复原快照后 listRequests = 1 条

id 生成器返回坏值:
  ProtocolStorageError(protocol_storage_error): Protocol id generator returned an invalid UUID

getRequest 用非 UUID 查询:
  ProtocolNotFoundError(protocol_not_found): Protocol request id must be a canonical UUID

要验证的: 六种坏法全部拒绝,包括"多一个字段"(strictObject 的效果);pending 却带 resolution 报的是专门的错误消息,不是通用的 "state is invalid"——说明不变量校验是显式写出来的;坏快照被拒之后,恢复原文件仍能正常加载(没有污染内存缓存);连注入的 ID 生成器都要校验;查询用非 UUID 会明确说明原因。

实验 8(gate):plan gate 真的会 deny

这是本章最值得亲手跑一遍的实验。追加:

// ---------- 实验 8(gate):plan gate 是真门,不是提示 ----------
if (section("gate")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result", "plan noted");
    const runtime = makeRuntime(root, model, {
      protocolStore: new JsonProtocolStore(root, {
        idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
      }),
    });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      // 组合根就是这么加的:只往队友策略上追加 plan gate
      const base = new PermissionPolicy();
      const policy = base.withRules([runtime.protocol.planGateRule]);
      console.log("withRules 返回新对象 =", policy !== base);
      // 造出四个代表性工具,effect 与组合根裁剪后的队友工具面一致
      const tools = new ToolRegistry();
      for (const [name, effect] of [
        ["read_file", "read"], ["write_file", "write"],
        ["send_message", "external"], ["submit_plan", "external"],
      ] as const) {
        tools.register({
          name, description: name, inputSchema: (await import("zod")).z.strictObject({}),
          effect, handler: async () => toolSuccess("ok"),
        });
      }
      async function decide(name: string): Promise<string> {
        const prepared = tools.prepare({ id: "call-1", name, arguments: "{}" });
        const decision = await policy.decide(new PermissionRequest({
          prepared, context: Object.freeze({ workspace: root, identity: "alice" }),
        }));
        return `${decision.behavior.padEnd(5)} source=${decision.source}`;
      }
      const names = ["read_file", "write_file", "send_message", "submit_plan"];
      console.log("\n(1) 队友从没提交过计划:latestPlanRequest = undefined");
      console.log("    planAllowsEffectful =", await runtime.protocol.planAllowsEffectful("alice"));
      for (const name of names) console.log(`    ${pad(name, 14)}-> ${await decide(name)}`);

      const request = await runtime.protocol.submitPlan("alice", "write the config");
      console.log("\n(2) 刚提交计划,还没批:status =", request.status);
      console.log("    planAllowsEffectful =", await runtime.protocol.planAllowsEffectful("alice"));
      for (const name of names) console.log(`    ${pad(name, 14)}-> ${await decide(name)}`);

      // reviewPlan 只负责“投递响应信封”,pending -> approved 的迁移发生在
      // 队友 worker 里(routeTeammateMessage -> consumeResponse),所以要等一下
      await runtime.protocol.reviewPlan(request.id, true);
      console.log("\n(3) reviewPlan 返回时,状态还没变:status =",
        (await runtime.protocol.store.getRequest(request.id)).status);
      await waitFor(
        async () =>
          (await runtime.protocol.store.getRequest(request.id)).status !==
          ProtocolRequestStatus.Pending,
        "worker 消费 plan_approval_response",
      );
      console.log("\n(3') 队友 worker 消费响应之后:status =",
        (await runtime.protocol.store.getRequest(request.id)).status);
      console.log("    planAllowsEffectful =", await runtime.protocol.planAllowsEffectful("alice"));
      for (const name of names) console.log(`    ${pad(name, 14)}-> ${await decide(name)}`);
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts gate

真实输出:

===== gate =====
withRules 返回新对象 = true

(1) 队友从没提交过计划:latestPlanRequest = undefined
    planAllowsEffectful = true
    read_file     -> allow source=default
    write_file    -> allow source=default
    send_message  -> allow source=default
    submit_plan   -> allow source=default

(2) 刚提交计划,还没批:status = pending
    planAllowsEffectful = false
    read_file     -> allow source=default
    write_file    -> deny  source=plan-approval-gate
    send_message  -> allow source=default
    submit_plan   -> allow source=default

(3) reviewPlan 返回时,状态还没变:status = pending

(3') 队友 worker 消费响应之后:status = approved
    planAllowsEffectful = true
    read_file     -> allow source=default
    write_file    -> allow source=default
    send_message  -> allow source=default
    submit_plan   -> allow source=default

要验证的:

  • withRules 返回新对象,原策略不被修改;
  • (1) 没提交过计划时全放行——规则 1;
  • (2) pending 时只有 write_file 被 deny,且 source 明确是 plan-approval-gate;
  • (2) 里 read_file/send_message/submit_plan 仍然 allow——三条豁免;
  • (3) 到 (3') 之间需要 waitFor,因为 reviewPlan 只投递响应,迁移在队友 worker 里;
  • (3') 批准后 write_file 恢复 allow,source 回到 default。

如果你把这个实验里的 waitFor 删掉,会看到 (3') 打出 pending / false / deny——那正是《计划审批:状态先变,Runner 后恢复》讲的的另一面:调用方看到的状态不会凭空更新,得等消费者真的处理完。

一个常见的坑: 这个实验里必须先 spawn alice,否则 submitPlan 会报

ProtocolStateError: Unknown or unavailable teammate: alice

因为 submitPlan 内部要把请求投给一个已注册且可接收的参与方。《运行第 16 章》的排查表里也有这条。

自己改一下:把 reviewPlan(request.id, true) 改成 false,看 (3') 是不是 rejected 且 write_file 仍然 deny。

实验 9(shutdown):一次完整的优雅关闭轨迹

这个实验把《shutdown:先干完手头的活,再确定性路由》那条轨迹重跑一遍,并且数模型调用次数。追加:

// ---------- 实验 9(shutdown):一次完整的优雅关闭轨迹 ----------
if (section("shutdown")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result");
    const runtime = makeRuntime(root, model, {
      protocolStore: new JsonProtocolStore(root, {
        idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
      }),
    });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      const initial = await runtime.teammates.waitForEvents(1);
      console.log("[1] 队友干完第一轮,Lead 收到 result:",
        JSON.stringify(initial[0]?.toPayload().content));
      console.log("    模型调用次数 =", model.requests.length);
      await runtime.teammates.acknowledgeEvents(initial);
      console.log("    队友状态 =", runtime.teammates.state("alice").status);

      const request = await runtime.protocol.requestShutdown("alice");
      console.log("\n[2] request_shutdown 登记了请求:");
      showRequest("   ", request);

      const responseEvents = await runtime.teammates.waitForEvents(1);
      const response = responseEvents[0];
      console.log("\n[3] Lead 收到的下一条事件:");
      console.log("    isProtocolMailboxMessage =", isProtocolMailboxMessage(response as any));
      console.log("    payload =", JSON.stringify((response as any).toPayload(), null, 2)
        .split("\n").join("\n    "));
      console.log("    队友状态 =", runtime.teammates.state("alice").status);
      console.log("    模型调用次数 =", model.requests.length, "(关闭没有多花一次模型调用)");
      console.log("    ack 之前,请求状态 =",
        (await runtime.protocol.store.getRequest(request.id)).status);

      await runtime.teammates.acknowledgeEvents(responseEvents);
      console.log("\n[4] ack 之后:");
      showRequest("   ", await runtime.protocol.store.getRequest(request.id));
      console.log("\n[5] Mailbox 目录:");
      await tree(join(root, ".agent_tutorial", "mailboxes"), "    ");
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts shutdown

真实输出:

===== shutdown =====
[1] 队友干完第一轮,Lead 收到 result: "initial result"
    模型调用次数 = 1
    队友状态 = idle

[2] request_shutdown 登记了请求:
    id=00000000-0000-4000-8000-000000000901
    kind=shutdown status=pending sender=lead target=alice

[3] Lead 收到的下一条事件:
    isProtocolMailboxMessage = true
    payload = {
      "kind": "protocol",
      "message_id": "e52a0630-9594-489b-ac26-a6fca66102f9",
      "sender": "alice",
      "recipient": "lead",
      "protocol_kind": "shutdown_response",
      "content": "Ready to shut down.",
      "created_at_utc": "2026-08-30T13:08:20.697Z",
      "request_id": "00000000-0000-4000-8000-000000000901",
      "approved": true
    }
    队友状态 = shutdown
    模型调用次数 = 1 (关闭没有多花一次模型调用)
    ack 之前,请求状态 = pending

[4] ack 之后:
    id=00000000-0000-4000-8000-000000000901
    kind=shutdown status=approved sender=lead target=alice
    resolution.messageId=e52a0630-9594-489b-ac26-a6fca66102f9 approved=true

[5] Mailbox 目录:
    alice/
      done/
        51ca6220-cbfe-4867-bd7c-8f192932cf61.json
        f7881f8b-6351-46ab-849d-18bb413f25a7.json
      processing/
        (空)
      quarantine/
        (空)
      ready/
        (空)
    lead/
      done/
        94b62c85-90f3-4b3f-a50d-c243eb747480.json
        e52a0630-9594-489b-ac26-a6fca66102f9.json
      processing/
        (空)
      quarantine/
        (空)
      ready/
        (空)

要验证的:

  • [1] 到 [3],模型调用次数始终是 1。关机请求是确定性路由,没进模型——这是《shutdown:先干完手头的活,再确定性路由》最重要的那句话的实测证据;
  • payload.kind 是 "protocol" 而不是 "mailbox",protocol_kind 是 shutdown_response,approved: true;
  • content 是运行时生成的固定文案 "Ready to shut down.",不是模型写的;
  • [3] 里 ack 之前请求还是 pending,[4] ack 之后才是 approved——history-before-ack;
  • resolution.messageId 正好等于 [3] 里那条信封的 message_id;
  • [5] 两边的 ready/processing/quarantine 全空,四条消息都在 done——没有漏掉、也没有卡住的信。

created_at_utc 是真实时钟(2026-08-30T13:08:20.697Z),所以你跑出来的这一行和上面不一样,这是正常的。而 id=...0901 是我们用 seqId(0x901) 固定住的,这一项应该完全一致。

自己改一下:把 spawn 后的 waitForEvents(1) 和它的 acknowledgeEvents 删掉,直接 requestShutdown。你会看到 [3] 里 Lead 收到的第一条事件仍然是 result,shutdown_response 排在它后面——也就是"先干完手头的活"。

实验 10(plan):批准后复用同一个 Runner

追加:

// ---------- 实验 10(plan):计划批准后复用同一个 Runner ----------
if (section("plan")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result", "approved work result");
    const runtime = makeRuntime(root, model, {
      protocolStore: new JsonProtocolStore(root, {
        idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
      }),
    });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      console.log("[1] 第一轮之后,模型调用次数 =", model.requests.length);

      const request = await runtime.protocol.submitPlan("alice", "write the config");
      console.log("\n[2] 队友提交计划:");
      showRequest("   ", request);
      const planEvents = await runtime.teammates.waitForEvents(1);
      console.log("    Lead 侧收到 protocol_kind =",
        (planEvents[0] as any).toPayload().protocol_kind);
      await runtime.teammates.acknowledgeEvents(planEvents);
      console.log("    ack 之后请求状态 =",
        (await runtime.protocol.store.getRequest(request.id)).status,
        "(请求方向的 ack 不迁移状态)");

      await runtime.protocol.reviewPlan(request.id, true);
      console.log("\n[3] Lead 批准,队友被唤醒;等它交回结果:");
      const resultEvents = await runtime.teammates.waitForEvents(1);
      console.log("    result =", JSON.stringify(resultEvents[0]?.toPayload().content));
      console.log("    模型调用次数 =", model.requests.length);
      console.log("\n[4] 第二次模型请求收到的 prompt:");
      const last = model.requests.at(-1);
      const lastUser = [...last.messages].reverse().find((m: any) => m.role === "user");
      console.log("   ", JSON.stringify(lastUser?.content));
      console.log("    system =", JSON.stringify(last.messages[0]?.content));
      console.log("    历史里保留了第一轮吗 =",
        last.messages.some((m: any) => m.content === "draft"));
      showRequest("\n[5] 请求终态 ->", await runtime.protocol.store.getRequest(request.id));
      await runtime.teammates.acknowledgeEvents(resultEvents);
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts plan

真实输出:

===== plan =====
[1] 第一轮之后,模型调用次数 = 1

[2] 队友提交计划:
    id=00000000-0000-4000-8000-000000000901
    kind=plan_approval status=pending sender=alice target=lead
    Lead 侧收到 protocol_kind = plan_approval_request
    ack 之后请求状态 = pending (请求方向的 ack 不迁移状态)

[3] Lead 批准,队友被唤醒;等它交回结果:
    result = "approved work result"
    模型调用次数 = 2

[4] 第二次模型请求收到的 prompt:
    "Plan approved (00000000-0000-4000-8000-000000000901). Proceed with the approved plan."
    system = "You are alice, serving as writer."
    历史里保留了第一轮吗 = true

[5] 请求终态 -> id=00000000-0000-4000-8000-000000000901
                 kind=plan_approval status=approved sender=alice target=lead
                 resolution.messageId=0a1073b2-64fc-494f-bca0-cf28f96256b3 approved=true

要验证的:

  • [2] 的 sender=alice target=lead——计划审批的方向和关机正好相反;
  • [2] 最后一行:Lead ack 掉 plan_approval_request 之后,状态仍然是 pending。ack 请求不是回应请求,只有 plan_approval_response 才能迁移状态;
  • [3] 模型调用次数从 1 变成 2:批准确实多花了一次模型调用(和关机不同,关机是 1→1);
  • [4] 那句 prompt 是运行时拼的确定性文本,带着 request id;
  • [4] system 还是 "You are alice, serving as writer.",历史里保留了第一轮吗 = true——同一个 AgentRunner,不是新建一个。这就是《计划审批:状态先变,Runner 后恢复》里"复用"的含义;
  • [5] 终态 approved,resolution 指向那条响应信封。

实验 11(reject):拒绝也是一次确定性迁移

追加:

// ---------- 实验 11(reject):拒绝也是一次确定性迁移 ----------
if (section("reject")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result", "revised plan result");
    const runtime = makeRuntime(root, model, {
      protocolStore: new JsonProtocolStore(root, {
        idGenerator: seqId(0x901), clock: () => new Date("2026-07-30T08:00:00.000Z"),
      }),
    });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      const request = await runtime.protocol.submitPlan("alice", "delete the database");
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      await runtime.protocol.reviewPlan(request.id, false, "太危险,换个方案");
      const resultEvents = await runtime.teammates.waitForEvents(1);
      console.log("result =", JSON.stringify(resultEvents[0]?.toPayload().content));
      const last = model.requests.at(-1);
      const lastUser = [...last.messages].reverse().find((m: any) => m.role === "user");
      console.log("被拒绝后队友收到的 prompt =", JSON.stringify(lastUser?.content));
      showRequest("请求终态 ->", await runtime.protocol.store.getRequest(request.id));
      console.log("\n拒绝后 planAllowsEffectful =",
        await runtime.protocol.planAllowsEffectful("alice"), "(拒绝不等于放行)");
      await runtime.teammates.acknowledgeEvents(resultEvents);
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts reject

真实输出:

===== reject =====
result = "revised plan result"
被拒绝后队友收到的 prompt = "Plan rejected (00000000-0000-4000-8000-000000000901). Feedback: 太危险,换个方案"
请求终态 -> id=00000000-0000-4000-8000-000000000901
            kind=plan_approval status=rejected sender=alice target=lead
            resolution.messageId=daed8edd-f8fe-4e86-b045-c4550edf41b1 approved=false

拒绝后 planAllowsEffectful = false (拒绝不等于放行)

要验证的:

  • 拒绝不是把队友杀掉。它照样被唤醒、照样跑一轮、照样交回 result("revised plan result")。区别只在 prompt 里那句 Plan rejected ... Feedback: ...;
  • reviewPlan 的第三个参数(反馈)会原样进 prompt,中文也不会被转义坏;
  • 终态是 rejected,approved=false;
  • 最后一行最关键:planAllowsEffectful = false。被拒绝之后队友仍然写不了文件,它只能改计划再交一次 submit_plan。《plan_gate:Prompt 不能授予执行权限》里 planAllowsEffectful 的判定是 latest === undefined || latest.status === Approved——rejected 两个条件都不满足。

这条也顺手解释了一个可能让你困惑的设计:为什么"从没提交过计划"是放行的,而"提交过但被拒了"是拦住的?因为前者说明这个队友不在计划审批的工作流里(比如它只是个只读的检索员),后者说明它明确进入了工作流但没拿到许可。

实验 12(quarantine):协议错误进隔离区,队友不死

这是《shutdown:先干完手头的活,再确定性路由》那张失败分类表里"隔离"那一行的实测。追加:

// ---------- 实验 12(quarantine):协议错误进隔离区,队友不死 ----------
if (section("quarantine")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result", "second result");
    const mailbox = new FileMailboxStore(root);
    const runtime = makeRuntime(root, model, { mailboxStore: mailbox });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));

      // 绕过运行时,直接往 alice 的 ready 里塞一条 request_id 根本不存在的响应。
      // 这模拟“外部写坏了信封”,协议层会判定 protocol_not_found。
      await mailbox.sendProtocol(
        "lead", "alice", "approved", ProtocolMessageKind.PlanApprovalResponse,
        { requestId: "00000000-0000-4000-8000-0000000009ff", approved: true },
      );
      // 直接写 store 不会唤醒 idle 的 worker,用一条普通消息把它叫起来。
      // worker 按时间顺序取信,会先撞上那条坏信封。
      await runtime.teammates.send({ sender: "lead", to: "alice", content: "keep going" });
      const quarantineDir = join(root, ".agent_tutorial", "mailboxes", "alice", "quarantine");
      await waitFor(async () => (await readdir(quarantineDir)).length > 0, "协议错误进隔离区");
      console.log("[1] alice/quarantine 里的文件数 =", (await readdir(quarantineDir)).length);
      console.log("    队友状态 =", runtime.teammates.state("alice").status, "(没被标 failed)");

      // 队友还活着:那条普通消息照样被处理完
      const events = await runtime.teammates.waitForEvents(1);
      console.log("\n[2] 坏信封被隔离后,普通消息照样跑完 ->",
        JSON.stringify(events[0]?.toPayload().content));
      console.log("    模型调用次数 =", model.requests.length, "(坏信封没有进模型)");
      await runtime.teammates.acknowledgeEvents(events);
      console.log("\n[3] 隔离区里的信封长这样:");
      const [file] = await readdir(quarantineDir);
      const raw = JSON.parse(await readFile(join(quarantineDir, file!), "utf8"));
      console.log("    ", JSON.stringify(raw).slice(0, 200));
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts quarantine

真实输出:

===== quarantine =====
[1] alice/quarantine 里的文件数 = 1
    队友状态 = running (没被标 failed)

[2] 坏信封被隔离后,普通消息照样跑完 -> "second result"
    模型调用次数 = 2 (坏信封没有进模型)

[3] 隔离区里的信封长这样:
     {"id":"b933d509-8704-424b-b5c1-76a92eef3a0d","sender":"lead","recipient":"alice","kind":"plan_approval_response","content":"approved","created_at_utc":"2026-08-30T13:12:33.673Z","request_id":"00000000

要验证的:

  • 一条 request_id 不存在的响应触发 protocol_not_found,信封进隔离区;
  • 队友状态是 running,不是 failed。协议内容错误是"这封信有问题",不是"这个队友坏了";
  • [2] 后面那条普通消息照样跑完并交回 "second result"——坏信封没有堵死队列;
  • 模型调用次数是 2(第一轮 + 那条普通消息),坏信封没有进模型。这一点很重要:协议校验发生在模型之前,坏协议不会浪费一次模型调用,也不会让模型看到半截协议状态而胡乱推测;
  • [3] 隔离区里保留的是完整原始信封,request_id 那串 ...09ff 还在。你可以拿它去排查是谁写坏的。

这里有个操作上的细节值得单独记住,因为它会绊倒很多人:直接调 mailbox.sendProtocol 写进 store,不会唤醒一个 idle 的队友。 唤醒逻辑在 TeammateRuntime.send/deliverProtocol 里(《idle 不等于轮询》那段代码),store 层完全不知道谁在等信。所以这个实验必须再补一条 runtime.teammates.send(...) 把 worker 叫起来。第一次写这个实验时我就在这里超时了 5 秒。

自己改一下:把 requestId 换成一个真实存在的请求 id,但把 approved 从 true 改成 false,看看还会不会进隔离区(会——sameResponse 比对不上,判 protocol_mismatch;同样是隔离,队友同样不死)。

实验 13(release):投递失败要 release,不能吞

同一张表里"释放 + 标记 failed"那一行。追加:

// ---------- 实验 13(release):投递失败要 release,不能吞 ----------
if (section("release")) {
  await withTempDir(async (root) => {
    const model = new ScriptModel("initial result");
    // 包一层 store:只让“队友回给 Lead 的 shutdown_response”这一次投递失败,
    // 模拟磁盘或传输故障。其余调用全部原样转发。
    const real = new FileMailboxStore(root);
    const flaky = {
      send: (...a: any[]) => (real as any).send(...a),
      claim: (...a: any[]) => (real as any).claim(...a),
      ack: (...a: any[]) => (real as any).ack(...a),
      release: (...a: any[]) => (real as any).release(...a),
      quarantine: (...a: any[]) => (real as any).quarantine(...a),
      recoverProcessing: (...a: any[]) => (real as any).recoverProcessing(...a),
      sendProtocol: (...a: any[]) => {
        if (a[3] === ProtocolMessageKind.ShutdownResponse) {
          throw new Error("disk is on fire");
        }
        return (real as any).sendProtocol(...a);
      },
    } as any;
    const runtime = makeRuntime(root, model, { mailboxStore: flaky });
    try {
      await runtime.teammates.start();
      await runtime.teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      await runtime.teammates.acknowledgeEvents(await runtime.teammates.waitForEvents(1));
      const request = await runtime.protocol.requestShutdown("alice");
      await waitFor(
        () => runtime.teammates.state("alice").status === TeammateStatus.Failed,
        "队友被标记 failed",
      );
      console.log("[1] 投递响应失败后:");
      console.log("    队友状态 =", runtime.teammates.state("alice").status);
      console.log("    请求状态 =", (await runtime.protocol.store.getRequest(request.id)).status,
        "(没有被误判成 approved)");
      const dirs = ["ready", "processing", "quarantine"] as const;
      for (const name of dirs) {
        const files = await readdir(join(root, ".agent_tutorial", "mailboxes", "alice", name));
        console.log(`    alice/${pad(name + ":", 12)}${files.length} 个文件`);
      }
      console.log("\n[2] 结论:请求信封回到 ready(release),等下次重投;");
      console.log("    状态机停在 pending,宁可重试一次,也不谎报已关闭。");
    } finally {
      await closeRuntime(runtime);
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts release

真实输出:

===== release =====
[1] 投递响应失败后:
    队友状态 = failed
    请求状态 = pending (没有被误判成 approved)
    alice/ready:      1 个文件
    alice/processing: 0 个文件
    alice/quarantine: 0 个文件

[2] 结论:请求信封回到 ready(release),等下次重投;
    状态机停在 pending,宁可重试一次,也不谎报已关闭。

要验证的:

  • 和实验 12 对比着看:同一个队友,两种失败,两种处置。协议内容错 → 隔离 + 活着;投递/存储故障 → 释放 + failed;
  • 请求状态停在 pending。这是整章最该守住的一条:投递失败绝不能让状态机变成 approved。否则 Lead 会以为队友已经确认关闭,而队友其实什么都不知道;
  • ready 里有 1 个文件、processing 是 0——那条 shutdown_request 被 release 放回去了,等下一次 claim 重投。这就是"至少一次"的具体样子;
  • quarantine 是 0:故障不是内容错误,不该进隔离区。隔离区应该只装"人能去查的坏数据"。

这个实验里的 flaky 包装写成了一个显式转发的对象字面量,而不是 Object.create(real)。原因是 FileMailboxStore 内部用了 # 私有字段,原型继承出来的对象过不了品牌检查(会抛 TypeError: Cannot read private member)。踩过一次,写在这里省你一次。

实验 14(tools):Lead 和队友的工具面差在哪

最后一个实验,回到《公开差量:只有三个工具》那张工具面对照。这次直接用真正的组合根 buildAgent。追加:

// ---------- 实验 14(tools):Lead 和队友的工具面差在哪 ----------
if (section("tools")) {
  await withTempDir(async (root) => {
    const { buildAgent } = await import("../chapters/ch16/src/bootstrap.ts");
    const { P15, P16 } = await import("../chapters/ch16/src/core/profiles.ts");
    const { RecoveryConfig } = await import("../chapters/ch16/src/features/recovery.ts");
    const { JsonTaskStore } = await import("../chapters/ch16/src/adapters/task-json.ts");

    console.log("[1] 能力位差异:");
    console.log("    P15 有 protocol 吗 =", P15.capabilities.has("protocol"),
      "/ plan_gate =", P15.capabilities.has("plan_gate"));
    console.log("    P16 有 protocol 吗 =", P16.capabilities.has("protocol"),
      "/ plan_gate =", P16.capabilities.has("plan_gate"));

    const inbox = new EventInbox();
    const supervisor = new JobSupervisor({ store: new JsonBackgroundJobStore(root), inbox });
    const cron = new CronRuntime({
      store: new JsonCronStore(root), inbox, supervisor,
      clock: { now: () => new Date("2026-07-30T08:00:00.000Z") },
    });
    const teammates = new TeammateRuntime({
      store: new FileMailboxStore(root), inbox, supervisor, cronRuntime: cron,
    });
    const protocol = new ProtocolRuntime({ store: new JsonProtocolStore(root), team: teammates });
    const model = new ScriptModel("lead done", "teammate done");
    const common = {
      workspace: root,
      recoveryConfig: new RecoveryConfig({ primaryModel: "primary", fallbackModel: "fallback" }),
      backgroundSupervisor: supervisor,
      cronRuntime: cron,
      taskStore: new JsonTaskStore(root),
      teammateRuntime: teammates,
      model: model as any,
      approvalProvider: { decide: async () => new PermissionDecision("allow", "probe", "probe") },
      auditSink: { record: async () => {} },
    };
    try {
      console.log("\n[2] 少给 protocolRuntime 会怎样:");
      try { buildAgent(P16, { ...common }); }
      catch (error) { console.log("   ", errorLine(error)); }

      const runner = buildAgent(P16, { ...common, protocolRuntime: protocol });
      await teammates.start();
      await runner.run("inspect");
      const leadTools: string[] = model.requests[0].tools.map((t: any) => t.function.name);
      console.log("\n[3] Lead 看到的工具面(共", leadTools.length, "个),最后四个:");
      console.log("    ", JSON.stringify(leadTools.slice(-4)));
      console.log("    Lead 有 submit_plan 吗 =", leadTools.includes("submit_plan"));

      await teammates.spawn({ name: "alice", role: "writer", prompt: "draft", sender: "lead" });
      const events = await teammates.waitForEvents(1);
      console.log("    模型一共收到", model.requests.length, "次请求;每次的工具数 =",
        JSON.stringify(model.requests.map((r: any) => r.tools?.length ?? 0)),
        "(0 那次是压缩摘要,不带工具)");
      const mateRequest = model.requests.find((r: any) =>
        r.tools?.some((t: any) => t.function.name === "submit_plan"));
      const mateTools: string[] = mateRequest.tools.map((t: any) => t.function.name);
      console.log("\n[4] 队友看到的工具面(共", mateTools.length, "个):");
      console.log("    ", JSON.stringify(mateTools));
      console.log("    队友有 request_shutdown 吗 =", mateTools.includes("request_shutdown"));
      console.log("    队友有 review_plan 吗 =", mateTools.includes("review_plan"));
      await teammates.acknowledgeEvents(events);
      await runner.close();
    } finally {
      await teammates.close();
      await cron.close();
      await supervisor.close();
    }
  });
}

跑:

npx tsx scripts/probe-ch16.mts tools

真实输出:

===== tools =====
[1] 能力位差异:
    P15 有 protocol 吗 = false / plan_gate = false
    P16 有 protocol 吗 = true / plan_gate = true

[2] 少给 protocolRuntime 会怎样:
    Error: protocolRuntime is required for chapter 16 or later

[3] Lead 看到的工具面(共 20 个),最后四个:
     ["spawn_teammate","send_message","request_shutdown","review_plan"]
    Lead 有 submit_plan 吗 = false
    模型一共收到 3 次请求;每次的工具数 = [20,0,5] (0 那次是压缩摘要,不带工具)

[4] 队友看到的工具面(共 5 个):
     ["shell","read_file","write_file","send_message","submit_plan"]
    队友有 request_shutdown 吗 = false
    队友有 review_plan 吗 = false

要验证的:

  • [1] P16 就是 P15 加两个能力位,别的什么都没动;
  • [2] 组合根用显式检查挡住"能力位开了但依赖没给"这种半装配状态,报错文本直接说明缺什么;
  • [3] Lead 20 个工具,最后四个是 spawn_teammate / send_message / request_shutdown / review_plan。Lead 没有 submit_plan——Lead 不向谁申请计划;
  • [4] 队友 5 个工具,没有 request_shutdown,也没有 review_plan。队友不能命令别人关机,也不能批自己的计划。这就是《公开差量:只有三个工具》说的"能力按角色裁剪,而不是靠 prompt 约束";
  • 两边都有 send_message:普通协作消息是双向的,只有协议动作是单向的。

[3] 里那个 [20,0,5] 值得多看一眼。中间那次工具数是 0,因为它是压缩摘要请求(第 8 章的内容),不带工具。这也是为什么脚本里不能写 model.requests[1].tools,得用 find 去找"包含 submit_plan 的那次请求"。我第一次就是写死了下标,结果打出 0 个工具,白排查了几分钟。

实验完成后清理

这个探测脚本只是学习用的临时文件,不属于仓库内容。跑完删掉:

rm -- scripts/probe-ch16.mts

确认一下工作区是干净的:

git status --short

应该没有任何输出。如果你在实验过程中改动了 chapters/ch16/ 下面的文件,这里会显示出来——照《运行第 16 章》排查表的方式还原它们,再跑一遍第 3 步的测试。


这章刻意没有做什么

写到这里,你大概能猜到接下来"顺手"能加什么。但本章刻意停在这条线上,因为再往前一步就会碰到下一章要解决的问题。列清楚,你读代码时就不会到处找这些东西:

没有 request_plan 这个工具。 原版教材的 Lead 工具表里同时列了 request_shutdown、request_plan、review_plan 三个。我们把 request_plan 去掉了,因为它没有状态迁移,也没有响应方——Lead 发一句"请提交计划",队友照做还是不照做完全靠模型自觉。那不是协议,是提示词。真正需要的是队友自己 submit_plan,Lead review_plan,两端都落到同一个 ProtocolRequest 上。这是《公开差量:只有三个工具》里"说清一处历史遗留"那段的完整理由。

没有轮询线程、没有 daemon、没有 sleep。 队友干完这轮就结束 worker task,靠新消息唤醒。《idle 不等于轮询》和实验 12 都验证过这一点。

没有任务板扫描、任务窃取、claim token、lease。 目前是 Lead 点对点派活,队友不会自己去找活干。这是第 17 章的内容。

没有把发送失败悄悄改成另一个请求。 实验 13 验证过:投递失败就是失败,请求停在 pending,release 回去等重投。不会"帮你"新建一个请求来掩盖它。

没有 worktree 隔离、没有 MCP 动态工具池。 队友共享同一个工作目录,工具面在组合根里写死。

协议状态幂等不是端到端恰好一次。 Mailbox 是至少一次投递,协议层用响应 message ID 做到"同一个请求的状态只迁移一次"。但如果队友在关机响应发出前已经执行过一次外部副作用(比如发了封邮件),重投不会帮你去重那封邮件。副作用去重是业务层的事。

这些不做项不是"以后补上"的 TODO,而是本章边界的一部分。第 16 章要守住的最小闭环只有四个词:固定团队、持久请求、严格匹配、硬门控。


与 Claude Code 的差异

参照外部仓库 shareAI-lab/learn-claude-code 的 s16_team_protocols/README.md 里对 CC 源码的分析,本章的实现在几个地方和真实的 Claude Code 不一样。分清"我们简化了"和"我们比教学版更严"这两类差异,对理解设计取舍很有帮助。

我们简化了的地方

关机响应只有一种消息。 我们用统一的 shutdown_response 带 approved: true/false 完成握手。CC 真实源码拆成 shutdown_approved 和 shutdown_rejected 两种独立消息;确认之后还会广播 teammate_terminated 通知相关方,清理 tmux/iTerm2 窗格,解除任务认领,从团队配置里移除成员。我们的 shutdown 只结束队友的消息循环,Runner 资源由组合根统一关闭。

计划审批的触发点更朴素。 我们让队友显式调 submit_plan。CC 里主要由 ExitPlanModeV2Tool 在"要求计划模式的队友退出计划模式时"自动产生审批请求,useInboxPoller 会自动回写 approval 并把请求作为普通上下文交给 Lead,同时保留显式 approve/reject 的能力。CC 的审批还能附带 permissionMode,比如"批准,但继续以 plan mode 运行";我们只实现 approve / reject / feedback 三要素。

idle 时不通知 Lead。 CC 真实源码在队友空闲时会发 idle_notification,让 Lead 感知到"这个人闲着"。我们的队友进入 idle 是静默的,Lead 不知道,直到下次派活。

字段命名统一了。 我们的 ProtocolMailboxMessage 固定用 request_id。CC 真实源码的协议消息也是结构化 JSON 并用 Zod 校验,但命名没统一:permission 消息用 request_id,shutdown 和 plan approval 用 requestId。我们用统一命名换可读性,CC 保留了不同模块的真实演进痕迹。

我们比教学版更严的地方

这几条是反过来的——CC 的教学版 s16 没做,我们做了:

plan gate 是真门。 教学版 s16 只演示计划审批的消息流转,没有在未批准时拦住 shell 或 write_file。我们把它实现成 PermissionRule,pending/rejected 时 effectful 工具在 handler 执行前就被 deny(实验 8 的实测)。CC 真实源码的队友有完整的 permission gating,所以这里是我们向生产语义靠拢,而不是超出 CC。

协议状态持久化。 教学版 s16 的 ProtocolState 是进程内的 pending_requests 字典,用 req_xxx 短 ID 和 float 时间戳,进程一重启全没了。我们写进 .agent_tutorial/protocol/state.json,规范 UUID,aware UTC,.protocol.lock 保护跨进程并发。

投递语义更明确。 教学版沿用"读完就 unlink"的消费方式,进程在"读取后、处理前"崩溃就丢消息,是至多一次。我们是至少一次投递加协议层幂等:先登记再发送,发送失败保留 pending。

一句话总结这张对照:CC 真实源码比我们完整,CC 教学版比我们松。 我们挑的是"能在离线测试里被断言住的最小严格集合"。


从 ai-agent-book 学到什么:控制平面与优雅终止

ai-agent-book 第 10 章和本章主题几乎正对:它把"不共享上下文的多 Agent 协作"拆成数据平面和控制平面,用结构化信封、状态获取、优雅终止和任务生命周期,去解决那句我们开篇就说过的话——消息已经送达,但协作尚未完成。配套实验 10-4 的说明见外部仓库 bojieli/ai-agent-book 的 chapter10/parallel-web-research/README.md,总线实现见同目录的 message_bus.py。

它是怎么设计的

先说它的两个平面:

平面 承载什么 用什么实现
数据平面 产物交换(谁写了什么文件) 共享文件系统
控制平面 消息传递、状态查询、执行终止、资源调度 消息总线

它特别强调两点,都值得抄:

第一,状态获取应该是主动上报,不是无界轮询。 更自然的做法是子 Agent 主动发 status_update,或者往约定好的进度文件里写,而不是让 Manager 每秒问一遍"你干完了吗"。

第二,执行终止应该以优雅终止为首选。 顺序是 terminate → 子 Agent 在安全点清理资源 → ack → 退出。强制终止只作兜底。你会发现这和本章那条 shutdown 轨迹是同一个形状。

它的 message_bus.py 把每条消息封成 Envelope,带 sender_id、target、type、payload、seq、ts;消息类型有 task_assigned、status_update、result、terminate、ack。MessageBus 按订阅关系转发,既支持点对点,也支持 BROADCAST="*" 广播。history 留完整消息流,short() 打出带时间戳和全局序号的紧凑日志——让实验"看得见"每条协作事件。这个"可观测优先"的取向和我们那 14 个实验是同一个思路。

实验 10-4 把控制平面落到真实的并行搜索上:Manager 动态启动多个同构 worker,每个 worker 用独立的 Playwright browser context。第一个 target_found 在 asyncio.Lock 下结算,只允许一次 terminate 广播,后续迟到的命中只记录、不重复结算。输家收到 terminate 后在安全点取消、发 ack、关掉自己的 browser context。README 用三样东西做验收证据:context 创建/关闭计数、串行基线的 wall-clock 对比、provenance 事件流。

它还有一句话我觉得该单独摘出来:模型可以提出"完成",但不能批准自己的"完成"。 完成结论必须经过独立验证或 harness 门控。这正是我们 plan gate 的核心——队友可以 submit_plan,但批准权在 Lead 手里,而且不是靠 prompt 请求,是靠 PermissionRule 硬拦。

管理者模式那部分还提醒了两件事:Manager 是单点瓶颈,计划质量就是整个系统的上限;A2A 协议进一步把任务生命周期标准化为 submitted / working / needs input / completed / failed,让协作双方不用靠自由文本猜任务状态。

我们的对照与取舍

本章没有照搬中心化的 Message Bus,而是把它的控制平面原则落到"固定拓扑 + 持久 Mailbox + request/response 状态机"上。一条条对:

它的做法 本章的做法 为什么这么选
中心 MessageBus,支持订阅和广播 持久 Mailbox,点对点 我们的拓扑固定为 Lead + 多个平级队友,不需要动态 peer 集,也就不需要订阅和 BROADCAST
Envelope:sender_id/target/type/payload ProtocolMailboxMessage:多了 request_id、approved 让模型不必从自由文本里猜"这条回复对应哪个请求、是否已批准"
terminate / ack 通用取消 request_shutdown 结构化关闭 先干完当前消息,再在模型调用前确定性路由,回结构化响应,然后结束 worker
status_update 或进度文件代替轮询 请求本身持久化为状态真相 不引入轮询,也不引入上报;pending/approved/rejected 就是可查询、可恢复的状态
Manager 计划质量决定上限 plan gate 是 PermissionRule 不把计划状态只交给模型记忆,在真正的执行边界硬拦
A2A 五态生命周期 只有两类请求、三种状态 我们是同一团队内的封闭协议,不需要 Agent Card、流式进度、跨组织发现
真实浏览器 + 真实 wall-clock 做证据 注入 UUID / UTC clock / 模型替身,离线可重复 我们要的是"每次跑结果都一样"的断言,而不是性能数字

它做了而我们明确不做的: 中心 MessageBus、订阅过滤、BROADCAST、status_update、跨组织 A2A、动态 peer 发现。

广播和开放协议适合"Agent 数量不固定、需要自主发现与互操作"的场景。本章先守住那四个词——固定团队、持久请求、严格匹配、硬门控。下一章再让队友基于共享任务板主动发现并认领工作,那时候才需要处理"多个人同时想认领同一件事"。


配套代码索引

本章代码全部在 code/chapters/ch16/ 下。行数是给你估工作量用的——看到 715 行不用慌,protocol-json.ts 里一大半是错误分类和 JSON schema 校验。

新增或本章重点改动的文件:

文件 行数 本章负责什么
src/features/protocol.ts 463 ProtocolRequest 领域模型、ProtocolRuntime(requestShutdown / submitPlan / reviewPlan / planAllowsEffectful)、planGateRule
src/adapters/protocol-json.ts 715 JsonProtocolStore:单快照读写、两把锁、原子替换、consumeResponse 的严格匹配与幂等
src/features/mailbox.ts 461 typed 协议信封 ProtocolMailboxMessage、ProtocolMessageKind、isProtocolMailboxMessage
src/adapters/mailbox-json.ts 635 FileMailboxStore 增加 sendProtocol;ready/processing/done/quarantine 四目录语义
src/features/teammates.ts 768 deliverProtocol、协议路由(模型调用之前)、idle 唤醒、失败分类(release / quarantine / failed)
src/core/permissions.ts 415 PermissionPolicy.withRules()、PermissionRule、PermissionDecision 的 behavior/reason/source
src/bootstrap.ts 410 组合根:共享 store 校验、Lead / 队友工具面裁剪、plan gate 只挂到队友策略
src/core/loop.ts 714 事件消费边界;协议事件为什么不走 mailbox 的暂存与半状态分支
src/core/profiles.ts 304 P16 = P15 + protocol + plan_gate
src/core/events.ts 77 事件基类,看 toPayload() 就够
src/cli.ts 331 两个入口的参数解析、两类 wakeup 绑定和资源关闭
src/chapters/ch16.ts 5 固定章节入口,只有 5 行

测试:

文件 行数 断言什么
tests/ch16-protocol.test.ts 162 先登记后发送、严格匹配、只迁移一次、过期判定、时钟倒退失败、原子替换
tests/ch16-plan-gate.test.ts 63 pending/rejected 时 effectful handler 零调用,approved 后恢复
tests/ch16-runtime.test.ts 264 协议路由不进模型、busy 队友先干完活、失败分类三条路径
tests/ch16-bootstrap.test.ts 137 P15/P16 能力增量、共享 store 校验、两侧工具面精确相等
tests/ch16-entry.test.ts 28 两个入口共享同一 transport 并关掉全部资源

读代码的建议顺序

不要从 715 行的 protocol-json.ts 开始。按这个顺序读,每一步都能接着上一步的疑问:

  1. src/core/profiles.ts —— 先确认差量真的只有两个能力位。十几行,一分钟。
  2. src/features/protocol.ts 的 ProtocolRequest 部分 —— 九个字段、两条状态边。这是整章的地基,读透它后面都好办。
  3. src/features/mailbox.ts 的 ProtocolMailboxMessage —— 看 kind: "protocol" 和"请求必须 approved: null、响应必须是 boolean"这个构造期约束。
  4. src/features/protocol.ts 的 requestShutdown —— 只有十几行,但把"先登记,再发送"这条硬规则完整演示了一遍。
  5. src/adapters/protocol-json.ts 的 consumeResponse —— 现在再来看严格匹配的五个条件和幂等判定,你已经知道每个条件在防什么了。
  6. src/features/teammates.ts 的 deliverProtocol 和协议路由 —— 重点看两件事:协议判定在模型调用之前;失败分类的三条分支。
  7. src/features/protocol.ts 的 planGateRule —— 配合 src/core/permissions.ts 的 withRules 一起看,二十行代码。
  8. src/bootstrap.ts 的第 119-132 行和第 160-270 行 —— 校验在前,装配在后。看清楚 plan gate 为什么只挂在队友那一侧。
  9. src/core/loop.ts 的第 636-690 行 —— 最后再读这段。它解释的是"协议事件为什么不享受 mailbox 的暂存和半状态待遇",属于收尾的细节,一开始读只会分散注意力。

跳过 mailbox-json.ts 和 cli.ts 的大部分——前者是第 15 章的内容加一个 sendProtocol,后者是参数解析。


运行与验证

五道门,按顺序过。全部在 code/ 下执行:

cd "${REPO_ROOT:?请先按导读从仓库根目录设置 REPO_ROOT}/code"
npm run test:ch16
npm run typecheck
npm run lint
npm run format:check
npm run build

我这边的实测结果:

Test Files  49 passed (49)
      Tests  349 passed (349)

test:ch16 会连带跑前面所有章节的测试,所以是 49 个文件、349 个测试,不是只有 ch16 那 5 个文件。这是有意的——第 16 章的一个要求就是不能破坏 P15 及以前的行为,特别是"P15 普通消息的枚举和序列化 schema 完全不变"这一条。

本章测试全部注入了确定 UUID、UTC clock、模型替身和故障边界,不依赖真实 OpenAI、不依赖网络、没有真实 sleep。所以它们跑得快,而且每次结果一样。如果某个测试在你机器上偶发失败,先看《运行第 16 章》排查表里的 .mailboxes.lock 那一行。

关键断言都是具体的业务结果,不是"没抛异常"这种填充式断言:

  • P16 capability 严格等于 P15 加 protocol、plan_gate——多一个少一个都算失败;
  • P15 普通消息枚举和序列化 schema 完全不变;
  • 请求先持久登记,发送失败仍保留 pending;
  • ID 碰撞、坏状态、原子替换失败都不覆盖旧字节;
  • request ID、类型、双方、pending、有效期必须全部匹配;
  • 截止时刻已过期;同 clock 的多个请求按创建顺序判定最新;时钟倒退明确失败;
  • 不同响应并发时只有一个完成迁移,同 transport 重试幂等,另一个 message ID 被拒绝;
  • pending/rejected 计划让 effectful handler 零调用,approved 后仍保留原有的 approval 和 audit 行为;
  • busy 队友完成当前消息之后才 shutdown,协议请求不进入模型;
  • ack、取消、投递、协议存储四种故障都保留可恢复的 transport;只有无效协议消息才 quarantine;
  • P16 Lead 与队友的工具集合精确相等(20 / 5),两个 CLI 入口共享同一 transport 并关闭全部资源。

本章小结

三句话版本

第一,协议层的全部价值,是把隐式约定变成可验证状态。"请关机""计划批了"如果只存在于聊天记录里,它就只是语气;写进 ProtocolRequest 之后,它才是能查询、能恢复、能并发校验的事实。

第二,状态真相必须在发送之前就落盘。先登记再发送,投递失败保留 pending——宁可重投一次,也不谎报已完成。

第三,权限必须在真正的执行边界生效。plan gate 是 PermissionRule,不是提示词里的一句"请先等批准"。

一定要记住的七条

  1. 请求先登记,再发送。 规范 UUID、aware UTC、持久单快照。发送失败不回滚状态(实验 2、13)。
  2. 协议有自己的 typed 信封。 kind: "protocol",不污染 P15 普通消息的 schema;请求 approved: null,响应必须是 boolean(实验 1、4)。
  3. 响应要六个条件全中才算数。 请求存在、类型配对、sender、recipient、仍是 pending、未过期——缺一项就拒(实验 4、6)。
  4. 只迁移一次。 并发响应只有一个成功,同 transport 重试幂等,另一个 message ID 被拒(实验 5)。
  5. Lead 先写 history,再消费状态,最后 ack transport。 顺序反了就会出现"状态已消费但 Lead 不知道"(实验 9 的 [3]/[4])。
  6. shutdown 不进模型。 先干完当前消息,然后在模型调用前确定性路由。模型调用次数 1→1(实验 9)。
  7. 失败分三类,不是一类。 内容错 → 隔离,队友活着;投递/存储故障 → 释放 + failed;取消/关闭 → 释放(实验 12、13)。

一张图回顾整条链路

  ① 登记                      Lead 的工具                 队友的工具
  ────────                    request_shutdown            submit_plan
                              review_plan
                                     │
                                     ▼
                        ┌────────────────────────┐
                        │     ProtocolRuntime    │
                        └────────────┬───────────┘
                                     │  先写状态,再发消息
                                     ▼
              ┌──────────────────────────────────────────┐
              │  .agent_tutorial/protocol/state.json     │
              │  ProtocolRequest = 状态真相              │
              │                                          │
              │      pending ──approve──▶ approved       │
              │            └──reject───▶ rejected        │
              └──────────────────────────────────────────┘
                                     │
  ② 发送                             ▼
  ────────      ┌──────────────────────────────────────────┐
                │  .agent_tutorial/mailboxes/<name>/       │
                │  ready ──▶ processing ──▶ done           │
                │                    └────▶ quarantine     │
                │  信封 kind = "protocol"(不是 "mailbox") │
                └──────────────────────────────────────────┘
                                     │
  ③ 路由                             ▼
  ────────      ┌──────────────────────────────────────────┐
                │  队友 worker:先判类型,再决定要不要问模型 │
                │                                          │
                │  shutdown   ──▶ 不进模型,回结构化响应    │
                │  plan 响应  ──▶ 状态先变,再复用原 Runner │
                │  普通消息   ──▶ 才交给模型                │
                └──────────────────────────────────────────┘
                                     │
  ④ 门控                             ▼
  ────────      ┌──────────────────────────────────────────┐
                │  plan_gate(一条 PermissionRule)        │
                │                                          │
                │  没提交过计划       ──▶ allow             │
                │  最新计划 approved  ──▶ allow             │
                │  pending / rejected ──▶ deny(effectful) │
                │  豁免:read / send_message / submit_plan  │
                └──────────────────────────────────────────┘
                                     │
  ⑤ 消费                             ▼
  ────────      ┌──────────────────────────────────────────┐
                │  consumeResponse:六项全中才迁移,只一次  │
                │  Lead 侧顺序:history ──▶ 消费 ──▶ ack    │
                └──────────────────────────────────────────┘

五个编号就是本章五条硬规则的位置:① 先登记 ② 再发送 ③ 模型之前路由 ④ 权限边界门控 ⑤ 严格匹配只消费一次。

检查你是否真的读懂了

不看前文,试着回答。答不上来的,括号里是对应小节:

  1. ProtocolRequest 的九个持久字段分别是什么?为什么 resolution 要单独存,不能只看 status?(《ProtocolRequest》)
  2. 为什么协议状态是一个 state.json 单快照,而不是一个请求一个文件?(《ProtocolRequest》)
  3. 两把锁分别解决什么问题?只留一把会出什么错?(《ProtocolRequest》)
  4. "最新的计划请求"是按 UUID 大小、时间戳、还是数组顺序判定的?(《ProtocolRequest》)
  5. 响应窗口 [created_at_utc, expires_at_utc) 为什么右边是开区间?(《ProtocolRequest》、实验 6)
  6. 为什么请求方向的 ack 不迁移状态,只有响应才能迁移?(实验 10 的 [2])
  7. plan gate 的三条豁免是哪三个?如果不豁免 send_message 会发生什么?(《plan_gate》)
  8. "从没提交过计划"放行,"提交过但被拒"拦住——这个区别的理由是什么?(实验 11)
  9. 协议事件在 Lead 侧为什么不享受 mailbox 事件的暂存和半状态保留?(《Lead 侧》)
  10. 为什么 shutdown 不进模型,而 plan_approval_response 会多花一次模型调用?(《shutdown》《计划审批》)
  11. 直接往 store 里写一条消息,能唤醒 idle 的队友吗?为什么?(《idle 不等于轮询》、实验 12)
  12. 本章承诺的是 exactly-once 还是 at-least-once?"响应只消费一次"和"全局 exactly-once"差在哪?(《Lead 侧》里的"这不是恰好一次"、《这章刻意没有做什么》)

做到这些之后,"请关机""计划已批准"不再是两个 Agent 之间靠语气猜测的聊天,而是可以持久恢复、严格匹配、并发验证、失败重试的运行时契约。

下一章我们撤掉 Lead 手动派活这根拐杖:让队友基于共享任务板主动发现并认领工作。到那时"两个人同时想认领同一件事"会成为首要问题,而本章的持久状态机正是解决它的前提。