Appearance
TypeBox 作为协议的单一事实来源
最后更新:2026-01-10
TypeBox 是一个 TypeScript 优先的 Schema 库。我们用它来定义 Gateway WebSocket 协议(握手、请求/响应、服务端事件)。这些 Schema 驱动运行时校验、JSON Schema 导出和 macOS 应用的 Swift 代码生成。一个事实来源,其余全部生成。
如需了解更高层次的协议背景,请先阅读 Gateway 架构。
心智模型(30 秒)
每条 Gateway WS 消息都是以下三种帧之一:
- Request:
{ type: "req", id, method, params } - Response:
{ type: "res", id, ok, payload | error } - Event:
{ type: "event", event, payload, seq?, stateVersion? }
第一帧必须是 connect 请求。之后客户端可以调用方法(如 health、send、chat.send)并订阅事件(如 presence、tick、agent)。
连接流程(最简):
Client Gateway
|---- req:connect -------->|
|<---- res:hello-ok --------|
|<---- event:tick ----------|
|---- req:health ---------->|
|<---- res:health ----------|常用方法和事件:
| 类别 | 示例 | 说明 |
|---|---|---|
| 核心 | connect, health, status | connect 必须是第一个 |
| 消息 | send, poll, agent, agent.wait | 有副作用的方法需要 idempotencyKey |
| Chat | chat.history, chat.send, chat.abort, chat.inject | WebChat 使用这些 |
| Sessions | sessions.list, sessions.patch, sessions.delete | 会话管理 |
| Nodes | node.list, node.invoke, node.pair.* | Gateway WS + 节点操作 |
| 事件 | tick, presence, agent, chat, health, shutdown | 服务端推送 |
权威列表位于 src/gateway/server.ts(METHODS、EVENTS)。
Schema 所在位置
- 源码:
src/gateway/protocol/schema.ts - 运行时校验器(AJV):
src/gateway/protocol/index.ts - 服务端握手 + 方法分发:
src/gateway/server.ts - 节点客户端:
src/gateway/client.ts - 生成的 JSON Schema:
dist/protocol.schema.json - 生成的 Swift 模型:
apps/macos/Sources/OpenClawProtocol/GatewayModels.swift
当前流水线
pnpm protocol:gen- 将 JSON Schema(draft-07)写入
dist/protocol.schema.json
- 将 JSON Schema(draft-07)写入
pnpm protocol:gen:swift- 生成 Swift Gateway 模型
pnpm protocol:check- 运行两个生成器并验证输出已提交
运行时如何使用 Schema
- 服务端:每个入站帧都用 AJV 校验。握手只接受参数匹配
ConnectParams的connect请求。 - 客户端:JS 客户端在使用前校验事件和响应帧。
- 方法面:Gateway 在
hello-ok中通告支持的methods和events。
示例帧
Connect(第一条消息):
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"
}
}
}Hello-ok 响应:
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 }最简客户端(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();
}
});完整示例:端到端添加一个方法
示例:添加一个返回 { ok: true, text } 的 system.echo 请求。
- 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>;- 校验
在 src/gateway/protocol/index.ts 中导出 AJV 校验器:
ts
export const validateSystemEchoParams = ajv.compile<SystemEchoParams>(SystemEchoParamsSchema);- 服务端行为
在 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" 加入 src/gateway/server.ts 的 METHODS。
- 重新生成
bash
pnpm protocol:check- 测试 + 文档
在 src/gateway/server.*.test.ts 中添加服务端测试,并在文档中记录该方法。
Swift 代码生成行为
Swift 生成器输出:
- 带
req、res、event、unknown分支的GatewayFrame枚举 - 强类型载荷结构体/枚举
ErrorCode值和GATEWAY_PROTOCOL_VERSION
未知帧类型保留为原始载荷,以兼容未来版本。
版本控制与兼容性
PROTOCOL_VERSION位于src/gateway/protocol/schema.ts。- 客户端发送
minProtocol+maxProtocol;服务端拒绝不匹配的版本。 - Swift 模型保留未知帧类型,避免旧客户端崩溃。
Schema 模式与约定
- 大多数对象使用
additionalProperties: false以保证严格的载荷格式。 NonEmptyString是 ID 及方法/事件名称的默认类型。- 顶层
GatewayFrame在type字段使用鉴别器(discriminator)。 - 有副作用的方法通常要求参数中包含
idempotencyKey(如send、poll、agent、chat.send)。 agent接受可选的internalEvents,用于运行时生成的编排上下文(如子代理/cron 任务完成交接);视为内部 API 面。
实时 Schema JSON
生成的 JSON Schema 位于仓库 dist/protocol.schema.json。已发布的原始文件通常可在以下地址获取:
修改 Schema 时
- 更新 TypeBox Schema。
- 运行
pnpm protocol:check。 - 提交重新生成的 Schema + Swift 模型。