OpenClawSkills
GitHub
核心概念 • 5 分钟阅读

TypeBox

将 TypeBox 模式作为 Gateway 协议的唯一真实来源(SSOT)。

最后更新: 2026-01-10

TypeBox 是一个 TypeScript 优先的模式库。我们用它来定义 **Gateway

WebSocket 协议**(握手、请求/响应、服务器事件)。那些模式

驱动运行时验证、JSON 模式导出和Swift codegen

macOS 应用程序。真理的一个来源;其他一切都会生成。

如果您想要更高级别的协议上下文,请从

''网关架构''。

Tutorial.step

心智模型(30 秒)

每个网关 WS 消息都是以下三个帧之一:

- ''请求'':''{ type: "req", id, method, params }''

- ''回复'':''{ type: "res", id, ok, payload | error }''

- ''活动'':''{ type: "event", event, payload, seq?, stateVersion? }''

第一帧''必须''是 ''connect'' 请求。之后,客户可以致电

方法(例如 ''health''、''send''、''chat.send'')并订阅事件(例如

''presence''、''tick''、''agent'')。

连接流量(最小):

Terminal
Client                    Gateway
  |- res:hello-ok --|
  |<-|
  |->|
  |<-|

常用方法+事件:

|类别 |示例 |笔记|

-

|核心| ''connect''、''health''、''status'' | ''connect'' 必须是第一个 |

|消息 | ''send''、''poll''、''agent''、''agent.wait'' |副作用需要 ''idempotencyKey'' |

|聊天 | ''chat.history''、''chat.send''、''chat.abort''、''chat.inject'' | WebChat 使用这些 |

|会议 | ''sessions.list''、''sessions.patch''、''sessions.delete'' |会话管理|

|节点| ''node.list''、''node.invoke''、''node.pair.*'' |网关 WS + 节点操作 |

|活动 | ''tick''、''presence''、''agent''、''chat''、''health''、''shutdown'' |服务器推送|

权威列表位于 ''src/gateway/server.ts''(''METHODS''、''EVENTS'')。

Tutorial.step

模式所在的位置

- 来源:''src/gateway/protocol/schema.ts''

- 运行时验证器 (AJV):''src/gateway/protocol/index.ts''

- 服务器握手+方法调度:''src/gateway/server.ts''

- 节点客户端:''src/gateway/client.ts''

- 生成的 JSON 架构:''dist/protocol.schema.json''

- 生成的 Swift 模型:''apps/macos/Sources/OpenClawProtocol/GatewayModels.swift''

Tutorial.step

当前管道

- ''pnpm protocol:gen''

- 将 JSON 架构(草案 07)写入 ''dist/protocol.schema.json''

- ''pnpm protocol:gen:swift''

- 生成 Swift 网关模型

- ''pnpm protocol:check''

- 运行两个生成器并验证输出是否已提交

Tutorial.step

运行时如何使用模式

- 服务器端:每个入站帧都通过 AJV 进行验证。仅握手

接受参数与 ''ConnectParams'' 匹配的 ''ConnectParams'' 请求。

- 客户端:JS 客户端在之前验证事件和响应帧

使用它们。

- ''方法表面'':网关通告支持的 ''methods'' 和

''events'' 在 ''hello-ok''。

Tutorial.step

示例框架

连接(第一条消息):

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

你好-好的回复:

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 }
  }
}

请求+响应:

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

活动:

Json
{ "type": "event", "event": "tick", "payload": { "ts": 1730000000 }, "seq": 12 }
Tutorial.step

最小客户端 (Node.js)

最小有用流量:连接+健康。

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();
  }
});
Tutorial.step

工作示例:添加一个端到端的方法

示例:添加一个返回 ''{ ok: true, text }'' 的新 ''{ ok: true, text }'' 请求。

1. 架构(事实来源)

添加到 ''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>;

2. 验证

在 ''src/gateway/protocol/index.ts'' 中,导出 AJV 验证器:

Ts
export const validateSystemEchoParams = ajv.compile<SystemEchoParams>(SystemEchoParamsSchema);

3. 服务器行为

在 ''src/gateway/server-methods/system.ts'' 中添加一个处理程序:

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"'' 添加到 ''METHODS'' 在 ''src/gateway/server.ts'' 中。

4. 再生

Bash
pnpm protocol:check

5. 测试+文档

在 ''src/gateway/server.*.test.ts'' 中添加服务器测试并记下文档中的方法。

Tutorial.step

Swift 代码生成行为

Swift 生成器发出:

- ''GatewayFrame'' 枚举,包含 ''req''、''res''、''event'' 和 ''unknown'' 情况

- 强类型有效负载结构/枚举

- ''ErrorCode'' 值和 ''GATEWAY_PROTOCOL_VERSION''

未知的帧类型被保留为原始有效负载以实现前向兼容性。

Tutorial.step

版本控制+兼容性

- ''PROTOCOL_VERSION'' 住在 ''src/gateway/protocol/schema.ts''。

- 客户端发送''minProtocol'' + ''maxProtocol'';服务器拒绝不匹配。

- Swift 模型保留未知的帧类型,以避免破坏旧客户端。

Tutorial.step

模式模式和约定

- 大多数对象使用 ''additionalProperties: false'' 来实现严格的有效负载。

- ''NonEmptyString'' 是 ID 和方法/事件名称的默认值。

- 顶级 ''GatewayFrame'' 在 ''type'' 上使用 ''鉴别器''。

- 有副作用的方法通常需要在参数中添加 ''idempotencyKey''

(例如:''send''、''poll''、''agent''、''chat.send'')。

Tutorial.step

实时模式 JSON

生成的 JSON 架构位于 ''dist/protocol.schema.json'' 的存储库中。

发布的原始文件通常可在以下位置获得:

- https://raw.githubusercontent.com/openclaw/openclaw/main/dist/protocol.schema.json

Tutorial.step

当你改变模式时

1. 更新 TypeBox 架构。

2. 运行''pnpm protocol:check''。

3. 提交重新生成的架构+Swift 模型。