> 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/ch11-gateway-server-architecture/11.3-websocket-server-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 11.3 WebSocket Server Implementation

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

***

WebSocket is the core transport protocol of Gateway. All real-time communication—client control, Agent event streams, node commands—happens through WebSocket. This section provides an in-depth analysis of its implementation.

## 11.3.1 WebSocket Transport Layer: Using and Configuring the `ws` Library

OpenClaw uses the [ws](https://github.com/websockets/ws) library as its WebSocket server implementation. `ws` is the most mature WebSocket library in the Node.js ecosystem, known for high performance and low overhead.

The WebSocket server is created in `noServer` mode—meaning it doesn't listen on a port itself, but is mounted on the HTTP server and establishes connections through HTTP Upgrade requests:

```typescript
// Conceptual illustration (src/gateway/server.impl.ts)
import { WebSocketServer } from "ws";
import { createServer as createHttpServer } from "node:http";

const httpServer = createHttpServer();
const wss = new WebSocketServer({ noServer: true });

// HTTP Upgrade requests are forwarded by the HTTP server to the WebSocket server
httpServer.on("upgrade", (request, socket, head) => {
  // Decide whether to upgrade to WebSocket based on URL path
  // - / → Gateway WS
  // - /canvas → Canvas WS
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit("connection", ws, request);
  });
});
```

The benefit of `noServer` mode is that HTTP and WebSocket can share the same port. HTTP paths like `/v1/chat/completions` are handled by HTTP handlers, while WebSocket Upgrade requests to the root path `/` are passed to the WebSocket server.

## 11.3.2 WebSocket Runtime Management

`src/gateway/server-ws-runtime.ts` is the entry point for WebSocket runtime:

```typescript
export function attachGatewayWsHandlers(params: {
  wss: WebSocketServer;
  clients: Set<GatewayWsClient>;
  port: number;
  resolvedAuth: ResolvedGatewayAuth;
  gatewayMethods: string[];
  events: string[];
  extraHandlers: GatewayRequestHandlers;
  broadcast: (event: string, payload: unknown, opts?) => void;
  context: GatewayRequestContext;
  // ... loggers
}) {
  attachGatewayWsConnectionHandler({ ...params });
}
```

This function binds the WebSocket connection handler to the WebSocket server. `clients` is a `Set<GatewayWsClient>` that holds all active client connections. The `GatewayWsClient` type is defined in `src/gateway/server/ws-types.ts` and represents an authenticated WebSocket connection, containing identity information, permissions, event subscriptions, and other metadata.

## 11.3.3 Connection Lifecycle

Each WebSocket connection goes through the following lifecycle:

### Phase 1: Connection Establishment

After a client establishes a WebSocket connection, **the first frame must be a `connect` request**. This is a mandatory requirement of the Gateway protocol:

```json
{
  "type": "req",
  "id": "1",
  "method": "connect",
  "params": {
    "auth": { "token": "my-gateway-token" },
    "clientInfo": {
      "name": "OpenClaw macOS",
      "version": "2026.2.6",
      "platform": "macos"
    }
  }
}
```

Gateway performs authentication checks upon receiving `connect`. If authentication fails, it immediately closes the connection and returns an error.

### Phase 2: Handshake Success

After authentication passes, Gateway returns a `hello-ok` response containing a snapshot of the current state:

```json
{
  "type": "res",
  "id": "1",
  "ok": true,
  "payload": {
    "type": "hello-ok",
    "presence": { /* presence status snapshot */ },
    "health": { /* health status snapshot */ }
  }
}
```

After receiving `hello-ok`, the client enters a ready state and can send requests and receive events.

### Phase 3: Normal Communication

During the active connection period, communication occurs in three modes:

**Request-Response** (Client → Gateway → Client):

```
Client:  {"type":"req", "id":"42", "method":"status", "params":{}}
Gateway: {"type":"res", "id":"42", "ok":true, "payload":{...}}
```

**Server-Pushed Events** (Gateway → Client):

```
Gateway: {"type":"event", "event":"agent", "payload":{...}, "seq":1}
Gateway: {"type":"event", "event":"presence", "payload":{...}}
Gateway: {"type":"event", "event":"tick", "payload":{...}}
```

**Agent Streaming Events** (Special multi-frame response):

```
Client:  {"type":"req", "id":"99", "method":"agent", "params":{"message":"Hello"}}
Gateway: {"type":"res", "id":"99", "ok":true, "payload":{"runId":"abc","status":"accepted"}}
Gateway: {"type":"event", "event":"agent", "payload":{"stream":"lifecycle","phase":"start"}}
Gateway: {"type":"event", "event":"agent", "payload":{"stream":"assistant","delta":"Hi "}}
Gateway: {"type":"event", "event":"agent", "payload":{"stream":"assistant","delta":"there!"}}
Gateway: {"type":"event", "event":"agent", "payload":{"stream":"lifecycle","phase":"end"}}
```

### Phase 4: Connection Closure

A connection may close for various reasons:

* Client actively disconnects
* Network interruption
* Authentication expiration
* Gateway shutdown/restart
* Heartbeat timeout (prolonged inactivity)

Gateway cleans up all subscriptions and state for that client when the connection closes, and updates the Presence information. The `createGatewayCloseHandler` in `src/gateway/server-close.ts` handles graceful shutdown logic.

## 11.3.4 Frame Protocol Format

Gateway's WebSocket frame protocol is based on JSON text frames. Three frame types:

### Request Frame

```typescript
type RequestFrame = {
  type: "req";
  id: string;           // Request ID (generated by client, used to match responses)
  method: string;        // Method name
  params?: unknown;      // Method parameters
  idempotencyKey?: string; // Idempotency key (prevents duplicates)
};
```

### Response Frame

```typescript
type ResponseFrame = {
  type: "res";
  id: string;           // ID of the corresponding request
  ok: boolean;          // Whether successful
  payload?: unknown;    // Payload on success
  error?: {             // Error on failure
    code: string;
    message: string;
  };
};
```

### Event Frame

```typescript
type EventFrame = {
  type: "event";
  event: string;         // Event name
  payload: unknown;      // Event payload
  seq?: number;          // Sequence number (for ordered events)
  stateVersion?: {       // State version (for incremental updates)
    presence?: number;
    health?: number;
  };
};
```

**Idempotency Key** is an important safety mechanism. For operations with side effects (such as `send`, `agent`), clients must provide a unique idempotency key. Gateway maintains a short-term deduplication cache—if a request with the same idempotency key is sent twice (for example due to network retries), the second time will directly return the result of the first, without re-executing.

**Frame Validation**: Gateway performs JSON Schema validation on every frame received. Non-JSON frames or frames with incorrect format result in immediate connection closure. The first frame must be `connect`, otherwise it's also a hard close. These are all invariants declared in `docs/concepts/architecture.md`.

**Node Connections**: Nodes (macOS/iOS/Android devices) use the same WebSocket protocol, but include `role: "node"` in the `connect` request along with device capability declarations (which commands are supported, permission status, etc.).
