> 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.1-protocol-design-philosophy.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 12.1 Protocol Design Philosophy

> **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 Chapter 11, we saw how Gateway launches WebSocket and HTTP servers. However, there is a vast gap between "having a WebSocket connection" and "client and server can communicate effectively." This section will deeply analyze how OpenClaw designed a complete application-layer protocol on top of WebSocket, and the tradeoffs behind these design decisions.

> **Terminology Note**: The term "client" (Client) used frequently in this chapter specifically refers to **programs that connect to Gateway via WebSocket** in the Gateway protocol context—including the macOS menu bar app, CLI terminal, Web console, iOS/Android node devices, etc. These are monitoring and control tools used by the OpenClaw **operator** (the person who deploys and manages OpenClaw). Please distinguish this from "message channels" (Channels): channels are message entry points for end users (e.g., WhatsApp, Telegram), they are embedded within the Gateway process, and communicate with Gateway via in-process function calls rather than WebSocket. See the Connection Management section in Section 11.1.1 for details.

## 12.1.1 Why Choose WebSocket Over REST

Before discussing OpenClaw's protocol design, let's revisit a fundamental question: why use WebSocket?

### Limitations of REST

REST (Representational State Transfer) is the most common API design style in web applications. In REST architecture, the client initiates an HTTP request, the server returns a response, and then the connection closes. This "request-response" model is simple, stateless, easy to cache and scale, and is very suitable for CRUD (Create, Read, Update, Delete) operations.

However, for AI assistant applications like this, REST has several fundamental limitations:

**1. Cannot implement server-initiated push**

When an Agent is running, it produces a series of intermediate events—tool invocation started, the model returned a text chunk, tool execution completed. These events need to be **pushed to the client in real-time**. In the REST model, the client can only retrieve these events through polling (Polling), which is inefficient and has high latency.

> **Sidebar**: Polling (Polling) is a method where the client periodically sends requests to the server to check if there is new data. Although HTTP long polling (Long Polling) and Server-Sent Events (SSE) can partially solve this problem, the former still requires frequent connection establishment, and the latter only supports one-way communication from server to client.

**2. Request-response model doesn't match AI interaction patterns**

A single AI conversation may last for several minutes (an Agent may need to execute multiple tool calls, wait for approvals, etc.). In the REST model, this means either maintaining an extremely long HTTP connection waiting for a response, or splitting into "start task" and "query result" two interfaces.

**3. Multiplexing requirements**

OpenClaw needs to simultaneously perform on the same connection: initiate Agent conversations, query session lists, manage configurations, receive status events... If using REST, each operation would require an independent HTTP request.

### Advantages of WebSocket

WebSocket is a full-duplex communication protocol defined by the HTML5 standard. After an HTTP upgrade handshake, it establishes a persistent TCP connection where both parties can actively send messages at any time.

```
┌─────────┐                    ┌─────────┐
│  Client  │ ── HTTP Upgrade ──▶│  Server  │
│          │◀── 101 Switching ──│          │
│          │                    │          │
│          │◀──── Bidirectional Messages ────▶│          │
│          │                    │          │
└─────────┘                    └─────────┘
```

For OpenClaw, the core advantages of WebSocket are:

| Feature                 | REST                                       | WebSocket                       |
| ----------------------- | ------------------------------------------ | ------------------------------- |
| Connection Mode         | New connection per request                 | Persistent long connection      |
| Communication Direction | Client→Server                              | Bidirectional                   |
| Server Push             | Requires polling or SSE                    | Native support                  |
| Multiplexing            | Not supported (requires multiple requests) | Single connection multiplexing  |
| Connection Overhead     | HTTP headers every time                    | Minimal after initial handshake |

### OpenClaw's Choice: WebSocket + HTTP Complementary

OpenClaw hasn't completely abandoned HTTP. As mentioned in Section 11.4, Gateway simultaneously provides HTTP endpoints for:

* **OpenAI Compatible API** (`/v1/chat/completions`): For compatibility with existing toolchains
* **Webhook Callbacks** (`/hook/`): Some channels (like Slack) require HTTP callbacks
* **Health Checks** (`/health`): Standard operations requirement

This is a pragmatic design—use WebSocket for **stateful, real-time** interactions, and HTTP for **stateless, compatibility** needs.

## 12.1.2 Hybrid Mode of Request-Response + Server Push Events

The WebSocket protocol itself only defines the ability to "send messages" and doesn't have a built-in concept of "request-response." OpenClaw designed a set of application-layer frame (Frame) protocols on top of WebSocket to solve this problem.

### Three Frame Types

OpenClaw protocol defines three top-level frame types, distinguished by the `type` field:

```typescript
// src/gateway/protocol/schema/frames.ts

// Request Frame: Client → Server
export const RequestFrameSchema = Type.Object({
  type: Type.Literal("req"),    // Frame type identifier
  id: NonEmptyString,           // Request ID (for associating responses)
  method: NonEmptyString,       // Method name (e.g., "agent", "sessions.list")
  params: Type.Optional(Type.Unknown()),  // Parameters
}, { additionalProperties: false });

// Response Frame: Server → Client
export const ResponseFrameSchema = Type.Object({
  type: Type.Literal("res"),    // Frame type identifier
  id: NonEmptyString,           // Corresponding request ID
  ok: Type.Boolean(),           // Success or not
  payload: Type.Optional(Type.Unknown()),  // Return data on success
  error: Type.Optional(ErrorShapeSchema),  // Error info on failure
}, { additionalProperties: false });

// Event Frame: Server → Client (no request needed to trigger)
export const EventFrameSchema = Type.Object({
  type: Type.Literal("event"),  // Frame type identifier
  event: NonEmptyString,        // Event name
  payload: Type.Optional(Type.Unknown()),  // Event data
  seq: Type.Optional(Type.Integer({ minimum: 0 })),  // Sequence number
  stateVersion: Type.Optional(StateVersionSchema),    // State version
}, { additionalProperties: false });
```

> **Sidebar**: A frame (Frame) in communication protocols refers to a complete unit of data. WebSocket itself has the concept of frames (text frames, binary frames, etc.), but OpenClaw defines application-layer frames on top of that. This layered design is common in network protocols—TCP has its own frames, HTTP has its own message format on top of TCP, and OpenClaw defines its own message format on top of WebSocket.

These three frame types constitute a **hybrid communication mode**:

```
┌──────────┐                      ┌──────────┐
│          │ ─── req(id=1) ──────▶│          │
│          │◀── res(id=1) ────────│          │
│  Client  │                      │  Server  │
│          │ ─── req(id=2) ──────▶│          │
│          │◀── event(agent) ─────│          │  ← Server-initiated push
│          │◀── event(agent) ─────│          │  ← Server-initiated push
│          │◀── res(id=2) ────────│          │
│          │◀── event(presence) ──│          │  ← Server-initiated push
└──────────┘                      └──────────┘
```

### Request-Response Association

Requests and responses are associated through the `id` field. When the client sends a request, it specifies a unique ID, and the server echoes the same ID in the response. This allows the client to **simultaneously initiate multiple requests** on the same connection and correctly associate responses with requests.

> **Sidebar**: This pattern in protocol design is called **Multiplexing** (Multiplexing). HTTP/2 also uses a similar design (Stream ID) to handle multiple requests concurrently on a single TCP connection. In contrast, HTTP/1.1 processes requests sequentially (Head-of-line Blocking), or achieves concurrency by opening multiple connections.

### Union Frame Types and Discriminators

OpenClaw combines the three frame types into a union type (Union Type) and uses the `type` field as a discriminator (Discriminator):

```typescript
// src/gateway/protocol/schema/frames.ts
export const GatewayFrameSchema = Type.Union(
  [RequestFrameSchema, ResponseFrameSchema, EventFrameSchema],
  { discriminator: "type" },
);
```

The purpose of the discriminator is to allow downstream code generation tools (like quicktype, Swift codegen) to generate precise types, rather than generating a large structure with "all fields optional." This will be discussed in detail in Section 12.2.3 on Swift code generation.

### Error Format

When a request fails, the `error` field of the response frame contains standardized error information:

```typescript
// src/gateway/protocol/schema/frames.ts
export const ErrorShapeSchema = Type.Object({
  code: NonEmptyString,           // Error code, e.g., "INVALID_REQUEST"
  message: NonEmptyString,        // Human-readable error description
  details: Type.Optional(Type.Unknown()),   // Additional error details
  retryable: Type.Optional(Type.Boolean()), // Whether retryable
  retryAfterMs: Type.Optional(Type.Integer({ minimum: 0 })), // Retry interval
}, { additionalProperties: false });
```

Error codes are defined in `src/gateway/protocol/schema/error-codes.ts`:

```typescript
export const ErrorCodes = {
  NOT_LINKED: "NOT_LINKED",       // Channel not connected
  NOT_PAIRED: "NOT_PAIRED",       // Device not paired
  AGENT_TIMEOUT: "AGENT_TIMEOUT", // Agent execution timeout
  INVALID_REQUEST: "INVALID_REQUEST", // Request format error
  UNAVAILABLE: "UNAVAILABLE",     // Service unavailable
} as const;
```

Note the `retryable` and `retryAfterMs` fields—this is a **protocol-level backoff guidance** (Backoff Guidance). The server can tell the client: "This error is temporary, you can retry after N milliseconds." This is more precise than letting the client guess the retry strategy.

## 12.1.3 Idempotency Key Mechanism to Prevent Duplicate Operations

A classic problem in distributed systems is **duplicate delivery**: network glitches cause the client to be uncertain whether the request has been processed by the server, so it resends the request, resulting in the operation being executed twice. For AI assistants, this means potentially sending two identical reply messages, which is very undesirable.

> **Sidebar**: Idempotency (Idempotency) refers to the property that an operation has the same effect whether executed once or multiple times. For example, HTTP GET requests are naturally idempotent (fetching the same resource multiple times yields the same result), while POST requests are usually not idempotent (each POST may create a new resource). An idempotency key is a technical means to make non-idempotent operations idempotent.

### OpenClaw's Idempotency Key Design

In the OpenClaw protocol, operations involving **side effects** (sending messages, initiating Agent conversations, creating polls, etc.) all require the client to provide an `idempotencyKey` field:

```typescript
// src/gateway/protocol/schema/agent.ts

export const SendParamsSchema = Type.Object({
  to: NonEmptyString,              // Send target
  message: NonEmptyString,         // Message content
  mediaUrl: Type.Optional(Type.String()),
  // ...other fields omitted
  idempotencyKey: NonEmptyString,  // ← Idempotency key (required)
}, { additionalProperties: false });

export const AgentParamsSchema = Type.Object({
  message: NonEmptyString,         // User message
  agentId: Type.Optional(NonEmptyString),
  // ...other fields omitted
  idempotencyKey: NonEmptyString,  // ← Idempotency key (required)
}, { additionalProperties: false });

export const PollParamsSchema = Type.Object({
  to: NonEmptyString,
  question: NonEmptyString,
  options: Type.Array(NonEmptyString, { minItems: 2, maxItems: 12 }),
  // ...other fields omitted
  idempotencyKey: NonEmptyString,  // ← Idempotency key (required)
}, { additionalProperties: false });
```

The workflow of the idempotency key is as follows:

```
Sequence 1: Normal request
Client ─── req(method="send", idempotencyKey="abc123") ──▶ Server
       ◀── res(ok=true) ────────────────────────────────── Server
       (Server remembers "abc123" has been processed)

Sequence 2: Duplicate request (because Client didn't receive res, or resent after network reconnection)
Client ─── req(method="send", idempotencyKey="abc123") ──▶ Server
       ◀── res(ok=true) ────────────────────────────────── Server
       (Server finds "abc123" already processed, directly returns previous result, doesn't re-execute)
```

### Why Not Use Request ID for Deduplication?

You might ask: the request frame already has an `id` field, why need a separate idempotency key?

The reason is that **the lifecycle of request ID differs from the idempotency key**. The request ID is an identifier within a single WebSocket session—when the WebSocket disconnects and reconnects, the client generates a new request ID. But the idempotency key is pre-generated by the client and persisted; even after reconnection, the same idempotency key can be used to identify "this is the same business operation."

This design is very common in payment APIs like Stripe—they also require providing an `Idempotency-Key` HTTP header when creating payment requests to prevent duplicate charges due to network issues.

### Idempotency Key Generation Strategy

OpenClaw doesn't enforce a specific format for idempotency keys, only that they be non-empty strings. In practice, clients typically use UUID v4 or similar random unique identifiers. The key points are:

1. **The same business operation** should use the **same** idempotency key on retry
2. **Different business operations** should use **different** idempotency keys
3. Idempotency keys should not repeat within a **reasonable time window**

***

## Summary of This Section

OpenClaw's protocol design embodies several core principles:

1. **Choose the appropriate transport layer**: WebSocket's full-duplex capability naturally suits the real-time interaction needs of AI assistants, while preserving HTTP endpoints for compatibility.
2. **Build application protocol on top of transport layer**: Three frame types (request, response, event) constitute a flexible hybrid communication mode that supports both classic request-response and server-initiated push.
3. **Design for reliability**: The idempotency key mechanism ensures operation safety when the network is unstable, and retry guidance in error formats allows clients to make smarter decisions.

In the next section, we will see how these frame types are defined using TypeBox, a Schema system, and how OpenClaw simultaneously obtains TypeScript type safety and runtime validation from a single definition.
