> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch12-gateway-protocol-and-type-system/12.2-typebox-type-schema.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 12.2 TypeBox Type Schema

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~200,000 tokens, Output \~15,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous section, we saw Schema definitions of protocol frames, such as `RequestFrameSchema`, `EventFrameSchema`, etc. You may have noticed that these definitions use syntax like `Type.Object()`, `Type.String()`—this is exactly the API provided by the TypeBox library. This section will deeply explore how OpenClaw leverages TypeBox to build a "define once, use everywhere" protocol type system.

## 12.2.1 Protocol Schema Definition

### What is TypeBox?

> **Sidebar**: TypeBox is a TypeScript library (`@sinclair/typebox`) whose core idea is: **define JSON Schema using TypeScript code, while automatically obtaining the corresponding TypeScript types**.
>
> In traditional development, you typically need to maintain two separate definitions:
>
> * One TypeScript interface for compile-time type checking
> * One JSON Schema or Zod Schema for runtime data validation
>
> These two definitions easily become inconsistent. TypeBox uses clever type gymnastics to let you write one piece of code and get both.

Let's look at a simple example:

```typescript
import { Type, type Static } from "@sinclair/typebox";

// Define Schema (both a JSON Schema value and a source of TypeScript types)
const UserSchema = Type.Object({
  name: Type.String({ minLength: 1 }),
  age: Type.Integer({ minimum: 0 }),
  email: Type.Optional(Type.String({ format: "email" })),
});

// Extract TypeScript type from Schema
type User = Static<typeof UserSchema>;
// Equivalent to:
// type User = {
//   name: string;
//   age: number;
//   email?: string;
// }
```

At runtime, the value of `UserSchema` is a standard JSON Schema object:

```json
{
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "age"]
}
```

### OpenClaw's Schema Organization Structure

OpenClaw's protocol Schema definitions are located in the `src/gateway/protocol/schema/` directory, divided into multiple files by functional domain:

```
src/gateway/protocol/schema/
├── primitives.ts          # Basic types (NonEmptyString, etc.)
├── frames.ts              # Frame types (RequestFrame, ResponseFrame, EventFrame)
├── agent.ts               # Agent-related (AgentParams, SendParams, etc.)
├── sessions.ts            # Session management (SessionsList, SessionsPatch, etc.)
├── snapshot.ts            # State snapshots (Presence, Health, StateVersion)
├── config.ts              # Configuration operations (ConfigGet, ConfigSet, etc.)
├── channels.ts            # Channel operations (ChannelsStatus, TalkMode, etc.)
├── devices.ts             # Device pairing (DevicePair-related)
├── nodes.ts               # Node operations (NodePair, NodeInvoke, etc.)
├── cron.ts                # Scheduled tasks (CronAdd, CronRemove, etc.)
├── exec-approvals.ts      # Execution approvals
├── agents-models-skills.ts # Agent/model/skill lists
├── logs-chat.ts           # Logs and WebChat
├── wizard.ts              # Onboarding wizard
├── error-codes.ts         # Error code definitions
├── types.ts               # Type exports (Static<> extraction)
└── protocol-schemas.ts    # Schema registry
```

All files are unified through the `schema.ts` barrel file:

```typescript
// src/gateway/protocol/schema.ts
export * from "./schema/agent.js";
export * from "./schema/agents-models-skills.js";
export * from "./schema/channels.js";
export * from "./schema/config.js";
// ...16 exports total
export * from "./schema/wizard.js";
```

### Basic Types (Primitives)

All Schemas are built on a few basic types:

```typescript
// src/gateway/protocol/schema/primitives.ts
import { Type } from "@sinclair/typebox";
import { SESSION_LABEL_MAX_LENGTH } from "../../../sessions/session-label.js";
import { GATEWAY_CLIENT_IDS, GATEWAY_CLIENT_MODES } from "../client-info.js";

// Non-empty string — the most commonly used basic type in the protocol
export const NonEmptyString = Type.String({ minLength: 1 });

// Session label string (with maximum length limit)
export const SessionLabelString = Type.String({
  minLength: 1,
  maxLength: SESSION_LABEL_MAX_LENGTH,
});

// Client ID enum (built via Type.Union + Type.Literal)
export const GatewayClientIdSchema = Type.Union(
  Object.values(GATEWAY_CLIENT_IDS).map((value) => Type.Literal(value)),
);

// Client mode enum
export const GatewayClientModeSchema = Type.Union(
  Object.values(GATEWAY_CLIENT_MODES).map((value) => Type.Literal(value)),
);
```

There's a clever design here: `GatewayClientIdSchema` is not manually listing all possible values, but dynamically generated from the constant object `GATEWAY_CLIENT_IDS`. This means when you add a new client type in `client-info.ts`, the Schema automatically includes it, **without manual synchronization**.

`GATEWAY_CLIENT_IDS` defines all client types supported by OpenClaw:

```typescript
// src/gateway/protocol/client-info.ts
export const GATEWAY_CLIENT_IDS = {
  WEBCHAT_UI: "webchat-ui",        // WebChat UI
  CONTROL_UI: "openclaw-control-ui", // Web control console
  WEBCHAT: "webchat",              // Embedded WebChat
  CLI: "cli",                      // Command-line tool
  GATEWAY_CLIENT: "gateway-client", // Generic Gateway client
  MACOS_APP: "openclaw-macos",     // macOS application
  IOS_APP: "openclaw-ios",         // iOS application
  ANDROID_APP: "openclaw-android", // Android application
  NODE_HOST: "node-host",          // Node host
  TEST: "test",                    // Test client
  FINGERPRINT: "fingerprint",      // Fingerprint
  PROBE: "openclaw-probe",         // Probe
} as const;
```

### Type Extraction Pattern

The `types.ts` file uses TypeBox's `Static<>` utility type to extract the corresponding TypeScript type from each Schema:

```typescript
// src/gateway/protocol/schema/types.ts
import type { Static } from "@sinclair/typebox";
import type { ConnectParamsSchema, HelloOkSchema, /* ... */ } from "./frames.js";

export type ConnectParams = Static<typeof ConnectParamsSchema>;
export type HelloOk = Static<typeof HelloOkSchema>;
export type RequestFrame = Static<typeof RequestFrameSchema>;
export type ResponseFrame = Static<typeof ResponseFrameSchema>;
// ... 90+ type exports total
```

The `Static<typeof XxxSchema>` pattern is used extensively throughout OpenClaw. It ensures that the types seen by the TypeScript compiler and the Schema used for runtime validation are always consistent—because they are essentially **two perspectives of the same definition**.

### Runtime Validation (AJV Compilation)

With Schema definitions in place, OpenClaw uses the AJV (Another JSON Validator) library to compile them into efficient validation functions:

```typescript
// src/gateway/protocol/index.ts
import AjvPkg from "ajv";

const ajv = new AjvPkg({
  allErrors: true,    // Collect all errors, not just the first one
  strict: false,      // Disable strict mode (compatible with TypeBox output)
  removeAdditional: false, // Don't automatically remove extra fields
});

// Compile a validation function for each Schema
export const validateConnectParams = ajv.compile<ConnectParams>(ConnectParamsSchema);
export const validateRequestFrame = ajv.compile<RequestFrame>(RequestFrameSchema);
export const validateResponseFrame = ajv.compile<ResponseFrame>(ResponseFrameSchema);
export const validateEventFrame = ajv.compile<EventFrame>(EventFrameSchema);
// ... 70+ validation functions total
```

> **Sidebar**: AJV (Another JSON Validator) is currently the best-performing JSON Schema validation library in the JavaScript ecosystem. Its core optimization strategy is **pre-compilation**—when you call `ajv.compile(schema)`, AJV compiles the JSON Schema into an optimized piece of JavaScript code, and subsequent validation calls essentially just execute this code, making it extremely fast. This is similar to the "compile first, then match" concept of regular expressions.

These compiled validation functions are used in Gateway for:

1. **Inbound message validation**: After WebSocket receives a message, first validate if the frame format is legal
2. **Method parameter validation**: For each method call, validate if `params` matches the expected format
3. **Outbound message validation**: (optional) In development mode, validate messages sent by the server

### Validation Error Formatting

When validation fails, AJV returns an `ErrorObject[]` array. OpenClaw provides a specialized formatting function to convert it into human-readable error messages:

```typescript
// src/gateway/protocol/index.ts
export function formatValidationErrors(errors: ErrorObject[] | null | undefined) {
  if (!errors?.length) {
    return "unknown validation error";
  }
  const parts: string[] = [];
  for (const err of errors) {
    if (err.keyword === "additionalProperties") {
      // Special handling: tell the user which field is extra
      const where = err.instancePath ? `at ${err.instancePath}` : "at root";
      parts.push(`${where}: unexpected property '${additionalProperty}'`);
      continue;
    }
    // Generic handling
    const where = err.instancePath ? `at ${err.instancePath}: ` : "";
    parts.push(`${where}${err.message}`);
  }
  // Deduplicate and concatenate
  return Array.from(new Set(parts)).join("; ");
}
```

This function specially handles `additionalProperties` errors—not just saying "validation failed," but explicitly telling developers "you sent an extra field `token`." This kind of friendly error message is very helpful for debugging protocol interactions.

## 12.2.2 Generating JSON Schema from TypeBox

TypeBox definitions themselves are JavaScript representations of JSON Schema. However, OpenClaw also needs to export them as **independent JSON Schema files**, for two reasons:

1. **For non-TypeScript clients**: Swift (iOS/macOS) and Kotlin (Android) clients cannot directly use TypeBox definitions
2. **Protocol documentation**: JSON Schema can be rendered into readable documentation by tools

The `scripts/protocol-gen.ts` script handles this conversion:

```typescript
// scripts/protocol-gen.ts
import { ProtocolSchemas } from "../src/gateway/protocol/schema.js";

async function writeJsonSchema() {
  const definitions: Record<string, unknown> = {};
  for (const [name, schema] of Object.entries(ProtocolSchemas)) {
    definitions[name] = schema;
  }

  const rootSchema = {
    $schema: "http://json-schema.org/draft-07/schema#",
    $id: "https://openclaw.ai/protocol.schema.json",
    title: "OpenClaw Gateway Protocol",
    description: "Handshake, request/response, and event frames for the Gateway WebSocket.",
    oneOf: [
      { $ref: "#/definitions/RequestFrame" },
      { $ref: "#/definitions/ResponseFrame" },
      { $ref: "#/definitions/EventFrame" },
    ],
    discriminator: {
      propertyName: "type",
      mapping: {
        req: "#/definitions/RequestFrame",
        res: "#/definitions/ResponseFrame",
        event: "#/definitions/EventFrame",
      },
    },
    definitions,
  };

  const jsonSchemaPath = path.join(repoRoot, "dist", "protocol.schema.json");
  await fs.writeFile(jsonSchemaPath, JSON.stringify(rootSchema, null, 2));
}
```

`ProtocolSchemas` is a registry that consolidates all Schemas into a single `Record<string, TSchema>`:

```typescript
// src/gateway/protocol/schema/protocol-schemas.ts
import type { TSchema } from "@sinclair/typebox";

export const ProtocolSchemas: Record<string, TSchema> = {
  ConnectParams: ConnectParamsSchema,
  HelloOk: HelloOkSchema,
  RequestFrame: RequestFrameSchema,
  ResponseFrame: ResponseFrameSchema,
  EventFrame: EventFrameSchema,
  GatewayFrame: GatewayFrameSchema,
  // ... 80+ Schemas total
  ChatEvent: ChatEventSchema,
  TickEvent: TickEventSchema,
  ShutdownEvent: ShutdownEventSchema,
};

export const PROTOCOL_VERSION = 3 as const;
```

Note that `PROTOCOL_VERSION = 3` is also defined here—this is the protocol version number, used for version negotiation during client connection handshake.

The generated `dist/protocol.schema.json` file has the following structure:

```json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://openclaw.ai/protocol.schema.json",
  "title": "OpenClaw Gateway Protocol",
  "oneOf": [
    { "$ref": "#/definitions/RequestFrame" },
    { "$ref": "#/definitions/ResponseFrame" },
    { "$ref": "#/definitions/EventFrame" }
  ],
  "definitions": {
    "ConnectParams": { "type": "object", "properties": { ... } },
    "HelloOk": { "type": "object", "properties": { ... } },
    "RequestFrame": { "type": "object", "properties": { ... } },
    // ... 80+ definitions
  }
}
```

## 12.2.3 Generating Swift Models from JSON Schema

OpenClaw not only has TypeScript clients but also native macOS and iOS applications (written in Swift). To ensure that the Swift side and TypeScript side use exactly the same protocol definitions, OpenClaw provides a Swift code generation script.

The core logic of `scripts/protocol-gen-swift.ts` is: iterate through `ProtocolSchemas` and convert each JSON Schema object into a Swift `struct` definition:

```typescript
// scripts/protocol-gen-swift.ts (core generation logic, simplified)

// 1. Generate ErrorCode enum
const header = `
import Foundation

public let GATEWAY_PROTOCOL_VERSION = ${PROTOCOL_VERSION}

public enum ErrorCode: String, Codable, Sendable {
    case notLinked = "NOT_LINKED"
    case notPaired = "NOT_PAIRED"
    case agentTimeout = "AGENT_TIMEOUT"
    case invalidRequest = "INVALID_REQUEST"
    case unavailable = "UNAVAILABLE"
}
`;

// 2. Map JSON Schema type to Swift type
function swiftType(schema: JsonSchema, required: boolean): string {
  if (schema.type === "string") return required ? "String" : "String?";
  if (schema.type === "integer") return required ? "Int" : "Int?";
  if (schema.type === "boolean") return required ? "Bool" : "Bool?";
  if (schema.type === "array") return `[${swiftType(schema.items, true)}]`;
  return required ? "AnyCodable" : "AnyCodable?";
}

// 3. Generate a Swift struct for each Schema
function emitStruct(name: string, schema: JsonSchema): string {
  // Generate property declarations and CodingKeys
  return `public struct ${name}: Codable, Sendable { ... }`;
}
```

The generated Swift code is written to two locations:

```typescript
const outPaths = [
  // macOS application
  "apps/macos/Sources/OpenClawProtocol/GatewayModels.swift",
  // Cross-platform shared library
  "apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift",
];
```

Taking `ConnectParams` as an example, the generated Swift code looks roughly like this:

```swift
// Generated by scripts/protocol-gen-swift.ts — do not edit by hand
import Foundation

public struct ConnectParams: Codable, Sendable {
    public let minProtocol: Int
    public let maxProtocol: Int
    public let client: Client     // Nested struct
    public let caps: [String]?
    public let commands: [String]?
    public let permissions: [String: Bool]?
    public let device: Device?    // Nested struct
    public let auth: Auth?        // Nested struct

    // ... init and CodingKeys omitted
}
```

### Special Handling of GatewayFrame Union Type

Swift doesn't have union types like TypeScript, but has enums that can achieve similar effects. `GatewayFrameSchema` is specially handled as a Swift enum:

```swift
public enum GatewayFrame: Codable, Sendable {
    case req(RequestFrame)
    case res(ResponseFrame)
    case event(EventFrame)
    case unknown(type: String, raw: [String: AnyCodable])

    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        let type = try typeContainer.decode(String.self, forKey: .type)
        switch type {
        case "req":   self = .req(try RequestFrame(from: decoder))
        case "res":   self = .res(try ResponseFrame(from: decoder))
        case "event": self = .event(try EventFrame(from: decoder))
        default:
            let raw = try decoder.singleValueContainer()
                .decode([String: AnyCodable].self)
            self = .unknown(type: type, raw: raw)
        }
    }
}
```

Note the `.unknown` branch—when receiving a frame type not defined in the protocol version, it doesn't crash but stores it as a raw dictionary. This is a **forward compatibility** design: older clients can safely ignore new frame types introduced by newer servers.

## 12.2.4 Protocol Consistency Verification

When TypeBox definitions, JSON Schema files, and Swift models exist independently, they can become inconsistent if developers forget to run code generation. OpenClaw prevents this through the `pnpm protocol:check` command.

The basic flow of this check is:

1. Re-run `protocol-gen.ts` to generate the latest JSON Schema
2. Perform a **byte-by-byte comparison** of the newly generated JSON Schema with the version already committed in the repository
3. If inconsistent, report the differences and require developers to re-run code generation

This check is typically integrated into the CI (Continuous Integration) pipeline to ensure that protocol definitions are synchronized with each code commit.

### Complete Type Flow Closure

Let's summarize the complete type flow of OpenClaw's protocol type system in a diagram:

```
┌─────────────────────────────────────────────────────────────────┐
│                     TypeBox Schema Definition                    │
│          src/gateway/protocol/schema/*.ts                        │
│                                                                 │
│  Type.Object({ message: Type.String(), ... })                   │
└───────────────────────┬────────────────────┬────────────────────┘
                        │                    │
              ┌─────────▼──────┐    ┌───────▼────────────┐
              │  Static<typeof>│    │   AJV.compile()    │
              │  Compile-time  │    │  Runtime validation│
              │  type extraction│    │  function compilation│
              └───────┬────────┘    └───────┬────────────┘
                      │                     │
              ┌───────▼────────┐    ┌───────▼────────────┐
              │ TypeScript type │    │  Validation function│
              │ ConnectParams  │    │ validateConnect()  │
              │ RequestFrame   │    │ validateRequest()  │
              └────────────────┘    └────────────────────┘
                        │
              ┌─────────▼──────────────────┐
              │   protocol-gen.ts          │
              │   Export JSON Schema file   │
              └─────────┬──────────────────┘
                        │
              ┌─────────▼──────────────────┐
              │   protocol-gen-swift.ts    │
              │   Generate Swift Codable   │
              │   models                   │
              └─────────┬──────────────────┘
                        │
              ┌─────────▼──────────────────┐
              │   GatewayModels.swift      │
              │   macOS / iOS native       │
              │   clients                  │
              └────────────────────────────┘
```

This flow closure ensures:

* **TypeScript server** and **TypeScript client** share compile-time types and runtime validation
* **Swift client** uses auto-generated models, staying synchronized with server definitions
* **CI checks** prevent any inconsistencies from entering the codebase

This "single source of truth" design is very important in projects with frequent protocol evolution. Adding a new method parameter only requires modifying one TypeBox definition file and then running the code generation script—TypeScript types, runtime validation, JSON Schema, and Swift models will automatically stay synchronized.

***

## Summary of This Section

OpenClaw's TypeBox type system embodies the philosophy of **type-driven development**:

1. **Single definition, multi-platform reuse**: TypeBox Schema provides both compile-time types and runtime validation, eliminating the burden of manual synchronization
2. **Code generation bridges multiple languages**: Through `protocol-gen.ts` and `protocol-gen-swift.ts`, the same protocol definition is translated into JSON Schema and Swift models
3. **CI guards consistency**: The `protocol:check` command ensures that generated artifacts always stay synchronized with source definitions
4. **Forward compatibility design**: The `.unknown` branch in Swift's `GatewayFrame` enum ensures that older clients can safely handle new frame types

In the next section, we will descend from the Schema definition level to the actual method and event level, seeing what core operational capabilities Gateway provides.
