Skip to content

TypeBox 作为协议的唯一事实来源

最后更新:2026-01-10

TypeBox 是一个 TypeScript 优先的 schema 库。我们用它来定义 Gateway WebSocket 协议 (握手、请求/响应、服务端事件)。这些 schema 驱动 运行时校验JSON Schema 导出,以及 macOS app 的 Swift 代码生成(codegen)。一处事实来源;其余全部由它生成。

如果你需要更高层的协议背景,建议先看 Gateway architecture

心智模型(30 秒)

每条 Gateway WS 消息都属于三种 frame 之一:

  • Request{ type: "req", id, method, params }
  • Response{ type: "res", id, ok, payload | error }
  • Event{ type: "event", event, payload, seq?, stateVersion? }

第一条 frame 必须connect 请求。之后,client 可以调用 methods(例如 healthsendchat.send),并订阅 events(例如 presencetickagent)。

连接流程(最小集):

Client                    Gateway
  |---- req:connect -------->|
  |<---- res:hello-ok --------|
  |<---- event:tick ----------|
  |---- req:health ---------->|
  |<---- res:health ----------|

常见 methods + events:

CategoryExamplesNotes
Coreconnect, health, statusconnect must be first
Messagingsend, poll, agent, agent.waitside-effects need idempotencyKey
Chatchat.history, chat.send, chat.abort, chat.injectWebChat uses these
Sessionssessions.list, sessions.patch, sessions.deletesession admin
Nodesnode.list, node.invoke, node.pair.*Gateway WS + node actions
Eventstick, presence, agent, chat, health, shutdownserver push

权威列表在 src/gateway/server.tsMETHODSEVENTS)。

Schemas 在哪里

  • Source:src/gateway/protocol/schema.ts
  • 运行时校验器(AJV):src/gateway/protocol/index.ts
  • Server 握手 + method 分发:src/gateway/server.ts
  • Node client:src/gateway/client.ts
  • 生成的 JSON Schema:dist/protocol.schema.json
  • 生成的 Swift models:apps/macos/Sources/MoltbotProtocol/GatewayModels.swift

当前流水线(pipeline)

  • pnpm protocol:gen
    • 写入 JSON Schema(draft‑07)到 dist/protocol.schema.json
  • pnpm protocol:gen:swift
    • 生成 Swift gateway models
  • pnpm protocol:check
    • 同时运行两个生成器,并校验输出是否已提交

Schemas 在运行时如何使用

  • Server 端:每个入站 frame 都会用 AJV 校验。握手阶段只接受 params 匹配 ConnectParamsconnect 请求。
  • Client 端:JS client 在使用 event 与 response frames 之前会先校验。
  • Method surface:Gateway 会在 hello-ok 中声明支持的 methodsevents

示例 frames

Connect(第一条消息):

json
{
  "type": "req",
  "id": "c1",
  "method": "connect",
  "params": {
    "minProtocol": 2,
    "maxProtocol": 2,
    "client": {
      "id": "moltbot-macos",
      "displayName": "macos",
      "version": "1.0.0",
      "platform": "macos 15.1",
      "mode": "ui",
      "instanceId": "A1B2"
    }
  }
}

Hello-ok response:

json
{
  "type": "res",
  "id": "c1",
  "ok": true,
  "payload": {
    "type": "hello-ok",
    "protocol": 2,
    "server": { "version": "dev", "connId": "ws-1" },
    "features": { "methods": ["health"], "events": ["tick"] },
    "snapshot": { "presence": [], "health": {}, "stateVersion": { "presence": 0, "health": 0 }, "uptimeMs": 0 },
    "policy": { "maxPayload": 1048576, "maxBufferedBytes": 1048576, "tickIntervalMs": 30000 }
  }
}

Request + response:

json
{ "type": "req", "id": "r1", "method": "health" }
json
{ "type": "res", "id": "r1", "ok": true, "payload": { "ok": true } }

Event:

json
{ "type": "event", "event": "tick", "payload": { "ts": 1730000000 }, "seq": 12 }

最简 client(Node.js)

最小可用流程:connect + health。

ts
import { WebSocket } from "ws";

const ws = new WebSocket("ws://127.0.0.1:18789");

ws.on("open", () => {
  ws.send(JSON.stringify({
    type: "req",
    id: "c1",
    method: "connect",
    params: {
      minProtocol: 3,
      maxProtocol: 3,
      client: {
        id: "cli",
        displayName: "example",
        version: "dev",
        platform: "node",
        mode: "cli"
      }
    }
  }));
});

ws.on("message", (data) => {
  const msg = JSON.parse(String(data));
  if (msg.type === "res" && msg.id === "c1" && msg.ok) {
    ws.send(JSON.stringify({ type: "req", id: "h1", method: "health" }));
  }
  if (msg.type === "res" && msg.id === "h1") {
    console.log("health:", msg.payload);
    ws.close();
  }
});

Worked example:端到端新增一个 method

示例:新增一个 system.echo 请求,返回 { ok: true, text }

  1. Schema(唯一事实来源)

src/gateway/protocol/schema.ts 中新增:

ts
export const SystemEchoParamsSchema = Type.Object(
  { text: NonEmptyString },
  { additionalProperties: false },
);

export const SystemEchoResultSchema = Type.Object(
  { ok: Type.Boolean(), text: NonEmptyString },
  { additionalProperties: false },
);

把二者加入 ProtocolSchemas 并导出类型:

ts
  SystemEchoParams: SystemEchoParamsSchema,
  SystemEchoResult: SystemEchoResultSchema,
ts
export type SystemEchoParams = Static<typeof SystemEchoParamsSchema>;
export type SystemEchoResult = Static<typeof SystemEchoResultSchema>;
  1. 校验(Validation)

src/gateway/protocol/index.ts 中导出一个 AJV 校验器:

ts
export const validateSystemEchoParams =
  ajv.compile<SystemEchoParams>(SystemEchoParamsSchema);
  1. 服务端行为(Server behavior)

src/gateway/server-methods/system.ts 增加 handler:

ts
export const systemHandlers: GatewayRequestHandlers = {
  "system.echo": ({ params, respond }) => {
    const text = String(params.text ?? "");
    respond(true, { ok: true, text });
  },
};

src/gateway/server-methods.ts 中注册(已合并 systemHandlers), 然后把 "system.echo" 加到 src/gateway/server.tsMETHODS

  1. 重新生成(Regenerate)
bash
pnpm protocol:check
  1. Tests + docs

src/gateway/server.*.test.ts 增加服务端测试,并在文档里记录这个 method。

Swift codegen 行为

Swift 生成器会输出:

  • GatewayFrame enum:包含 reqreseventunknown 分支
  • 强类型的 payload structs/enums
  • ErrorCode 值与 GATEWAY_PROTOCOL_VERSION

未知 frame 类型会以 raw payload 形式保留,以实现前向兼容。

版本(Versioning)+ 兼容性

  • PROTOCOL_VERSION 位于 src/gateway/protocol/schema.ts
  • Clients 发送 minProtocol + maxProtocol;server 会拒绝不匹配的版本。
  • Swift models 会保留未知 frame 类型,从而避免破坏旧 client。

Schema 模式与约定

  • 大多数对象使用 additionalProperties: false,以保证 payload 严格。
  • NonEmptyString 是 IDs 与 method/event 名称的默认类型。
  • 顶层 GatewayFrame 通过 type 字段作为 discriminator
  • 具有副作用的 methods 通常要求 params 包含 idempotencyKey (例如:sendpollagentchat.send)。

Live schema JSON

生成的 JSON Schema 在仓库的 dist/protocol.schema.json。通常发布后的 raw 文件会在这里:

当你修改 schemas 时

  1. 更新 TypeBox schemas。
  2. 运行 pnpm protocol:check
  3. 提交重新生成的 schema + Swift models。