docs/concepts/typebox.md
TypeBox is a TypeScript-first schema library. OpenClaw uses it to define the Gateway WebSocket protocol (handshake, request/response, server events). Those schemas drive runtime validation (AJV), JSON Schema export, and Swift codegen for the macOS app. One source of truth; everything else is generated.
For the higher-level protocol context, start with Gateway architecture.
Every Gateway WS message is one of three frames:
{ type: "req", id, method, params }{ type: "res", id, ok, payload | error }{ type: "event", event, payload, seq?, stateVersion? }The first frame must be a connect request. After that, clients call methods (e.g. health, send, chat.send) and subscribe to events (e.g. presence, tick, agent).
Connection flow (minimal):
Client Gateway
|---- req:connect -------->|
|<---- res:hello-ok --------|
|<---- event:tick ----------|
|---- req:health ---------->|
|<---- res:health ----------|
Common methods and events:
| Category | Examples | Notes |
|---|---|---|
| Core | connect, health, status | connect must be first |
| Messaging | send, agent, agent.wait, system-event, logs.tail | side-effecting methods need idempotencyKey |
| Chat | chat.history, chat.send, chat.abort | WebChat uses these |
| Sessions | sessions.list, sessions.patch, sessions.delete | session admin |
| Automation | wake, cron.list, cron.run, cron.runs | wake and cron control |
| Nodes | node.list, node.invoke, node.pair.* | Gateway WS plus node actions |
| Events | tick, presence, agent, chat, health, shutdown | server push |
The authoritative advertised discovery inventory lives in src/gateway/server-methods-list.ts (listGatewayMethods, GATEWAY_EVENTS).
packages/gateway-protocol/src/schema.ts re-exports domain modules under packages/gateway-protocol/src/schema/*.ts (frames.ts for the top-level envelopes and handshake, agent.ts, sessions.ts, cron.ts, etc. per feature area). protocol-schemas.ts is the central ProtocolSchemas registry mapping schema names to their TypeBox definitions.packages/gateway-protocol/src/index.tssrc/gateway/server-methods-list.tssrc/gateway/server.impl.tssrc/gateway/client.tsdist/protocol.schema.json (build output, not committed)apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swiftpnpm protocol:gen writes JSON Schema (draft-07) to dist/protocol.schema.json.pnpm protocol:gen:swift generates the Swift gateway models.pnpm protocol:check runs both generators and verifies the Swift output is committed (the JSON Schema output is a gitignored build artifact).connect request whose params match ConnectParams.features.methods and features.events list in hello-ok, from listGatewayMethods() and GATEWAY_EVENTS.coreGatewayHandlers; some helper RPCs are implemented in src/gateway/server-methods/*.ts without being enumerated in the advertised feature list.Connect (first message):
{
"type": "req",
"id": "c1",
"method": "connect",
"params": {
"minProtocol": 3,
"maxProtocol": 4,
"client": {
"id": "openclaw-macos",
"displayName": "macos",
"version": "1.0.0",
"platform": "macos 15.1",
"mode": "ui",
"instanceId": "A1B2"
}
}
}
Hello-ok response:
{
"type": "res",
"id": "c1",
"ok": true,
"payload": {
"type": "hello-ok",
"protocol": 4,
"server": { "version": "dev", "connId": "ws-1" },
"features": { "methods": ["health"], "events": ["tick"] },
"snapshot": {
"presence": [],
"health": {},
"stateVersion": { "presence": 0, "health": 0 },
"uptimeMs": 0
},
"auth": { "role": "operator", "scopes": ["operator.read"] },
"policy": { "maxPayload": 1048576, "maxBufferedBytes": 1048576, "tickIntervalMs": 30000 }
}
}
Request and response:
{ "type": "req", "id": "r1", "method": "health" }
{ "type": "res", "id": "r1", "ok": true, "payload": { "ok": true } }
Event:
{ "type": "event", "event": "tick", "payload": { "ts": 1730000000 }, "seq": 12 }
Smallest useful flow: connect + health.
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: 4,
maxProtocol: 4,
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();
}
});
Example: add a new system.echo request that returns { ok: true, text }.
Add to packages/gateway-protocol/src/schema/system.ts (or the closest matching feature module):
export const SystemEchoParamsSchema = Type.Object(
{ text: NonEmptyString },
{ additionalProperties: false },
);
export const SystemEchoResultSchema = Type.Object(
{ ok: Type.Boolean(), text: NonEmptyString },
{ additionalProperties: false },
);
Import both into packages/gateway-protocol/src/schema/protocol-schemas.ts, add them to the ProtocolSchemas registry, and export the derived types:
SystemEchoParams: SystemEchoParamsSchema,
SystemEchoResult: SystemEchoResultSchema,
export type SystemEchoParams = Static<typeof SystemEchoParamsSchema>;
export type SystemEchoResult = Static<typeof SystemEchoResultSchema>;
In packages/gateway-protocol/src/index.ts, export an AJV validator:
export const validateSystemEchoParams = ajv.compile(SystemEchoParamsSchema);
Add a handler in src/gateway/server-methods/system.ts:
export const systemHandlers: GatewayRequestHandlers = {
"system.echo": ({ params, respond }) => {
const text = String(params.text ?? "");
respond(true, { ok: true, text });
},
};
Register it in src/gateway/server-methods.ts (already merges systemHandlers), then add "system.echo" to the listGatewayMethods input in src/gateway/server-methods-list.ts.
If the method is callable by operator or node clients, also classify it in src/gateway/method-scopes.ts so scope enforcement and hello-ok feature advertising stay aligned.
pnpm protocol:check
Add a server test in src/gateway/server.*.test.ts and note the method in docs.
The Swift generator emits:
GatewayFrame enum with req, res, event, and unknown casesErrorCode values, GATEWAY_PROTOCOL_VERSION, and GATEWAY_MIN_PROTOCOL_VERSIONUnknown frame types are preserved as raw payloads for forward compatibility.
PROTOCOL_VERSION lives in packages/gateway-protocol/src/version.ts (current value: 4).minProtocol and maxProtocol; the server rejects ranges that do not include its current protocol.additionalProperties: false for strict payloads.NonEmptyString (Type.String({ minLength: 1 })) is the default for IDs and method/event names.GatewayFrame uses a discriminator on type.idempotencyKey in params (example: send, poll, agent, chat.send).agent accepts optional internalEvents for runtime-generated orchestration context (for example subagent/cron task completion handoff); treat this as internal API surface.Generated JSON Schema is a build artifact, not committed to the repo. The published raw file is typically available at:
packages/gateway-protocol/src/schema/*.ts module and register them in protocol-schemas.ts.src/gateway/server-methods-list.ts.src/gateway/method-scopes.ts when the new RPC needs operator or node scope classification.pnpm protocol:check.