TypeBox 作为协议真相源
最后更新:2026-01-10 TypeBox 是 TypeScript 优先的 schema 库。我们用它定义 Gateway WebSocket 协议(握手、请求/响应、服务器事件)。这些 schemas 驱动运行时校验、JSON Schema 导出以及 macOS app 的 Swift 代码生成。单一事实来源,其它都由它生成。 如需更高层协议背景,先看 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? }
connect 请求。之后客户端可调用方法(如 health、send、chat.send)并订阅事件(如 presence、tick、agent)。
连接流程(最小):
| Category | Examples | Notes |
|---|---|---|
| Core | connect, health, status | connect 必须是第一条 |
| Messaging | 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 + node 操作 |
| Events | tick, presence, agent, chat, health, shutdown | 服务器推送 |
src/gateway/server.ts(METHODS, EVENTS)。
Schemas 位置
- Source:
src/gateway/protocol/schema.ts - Runtime validators(AJV):
src/gateway/protocol/index.ts - Server 握手 + 方法分发:
src/gateway/server.ts - Node client:
src/gateway/client.ts - 生成的 JSON Schema:
dist/protocol.schema.json - 生成的 Swift models:
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 models
pnpm protocol:check- 运行两者并验证输出已提交
运行时如何使用 schemas
- Server 侧:每个入站 frame 都用 AJV 校验。握手只接受 params 匹配
ConnectParams的connect请求。 - Client 侧:JS client 在使用前校验事件与响应 frame。
- 方法面:Gateway 在
hello-ok中公布支持的methods与events。
示例 frames
Connect(第一条消息):最小客户端(Node.js)
最小可用流程:connect + health。Worked example:端到端新增方法
示例:新增system.echo 请求,返回 { ok: true, text }。
- Schema(事实来源)
src/gateway/protocol/schema.ts 中添加:
ProtocolSchemas 并导出类型:
- Validation
src/gateway/protocol/index.ts 中导出 AJV 校验器:
- Server 行为
src/gateway/server-methods/system.ts 添加 handler:
src/gateway/server-methods.ts 中注册(已合并 systemHandlers),然后在 src/gateway/server.ts 的 METHODS 中加入 "system.echo"。
- 重新生成
- Tests + docs
src/gateway/server.*.test.ts 添加 server test,并在文档中注明该方法。
Swift codegen 行为
Swift 生成器会输出:GatewayFrameenum,包含req、res、event与unknown分支- 强类型 payload structs/enums
ErrorCode值与GATEWAY_PROTOCOL_VERSION
版本与兼容
PROTOCOL_VERSION位于src/gateway/protocol/schema.ts。- 客户端发送
minProtocol+maxProtocol;服务端拒绝不匹配。 - Swift models 保留未知 frame 类型以避免破坏旧客户端。
Schema 约定与模式
- 大多数对象使用
additionalProperties: false保持严格 payload。 NonEmptyString用于 ID 与方法/事件名。- 顶层
GatewayFrame使用type作为判别字段。 - 有副作用的方法通常需要 params 中的
idempotencyKey(例如send、poll、agent、chat.send)。
Live schema JSON
生成的 JSON Schema 位于仓库dist/protocol.schema.json。发布的原始文件通常可在以下地址获取:
当你修改 schemas
- 更新 TypeBox schemas。
- 运行
pnpm protocol:check。 - 提交重新生成的 schema + Swift models。