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

# Appendix B: Gateway WebSocket Protocol Reference

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~360,000 tokens, Output \~10,000 tokens **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`) **Sources of truth**: `src/gateway/protocol/schema/frames.ts`, `protocol-schemas.ts`, `src/gateway/server-methods-list.ts` — every item below was checked against them

***

Read alongside: **Chapter 12** (protocol and type system), **§12.5** (source deep dive: three frames, handshake, four auth layers), **Appendix G** (network model and deployment reference).

## B.1 Protocol Version

```
PROTOCOL_VERSION = 3        // src/gateway/protocol/schema/protocol-schemas.ts:301
```

At handshake the client declares the range it accepts via `minProtocol` / `maxProtocol`, and the server returns the negotiated result in `hello-ok`.

## B.2 Frame Format

There are exactly **three frame types**, all with `additionalProperties: false` (unknown fields are rejected outright).

```jsonc
// Request frame (client → Gateway)
{ "type": "req", "id": "req-001", "method": "chat.send", "params": { } }

// Response frame (Gateway → client)
{ "type": "res", "id": "req-001", "ok": true,  "payload": { } }
{ "type": "res", "id": "req-001", "ok": false, "error": { } }

// Event frame (Gateway → client, server push)
{ "type": "event", "event": "chat", "payload": { }, "seq": 42, "stateVersion": { } }
```

> **Note the response frame uses `ok` + `payload`, not `result`.** This is commonly gotten wrong — `ok` is a required boolean, with `payload` on success and `error` on failure.

### Error shape (`ErrorShapeSchema`)

```typescript
{
  code: string;            // required
  message: string;         // required
  details?: unknown;       // structured detail, e.g. { code: "SIGNATURE_EXPIRED", reason: "..." }
  retryable?: boolean;
  retryAfterMs?: number;
}
```

On device-authentication failures, `details` additionally carries `recommendedNextStep` (e.g. `retry_with_device_token`) — **errors as navigation**, see §12.5.3.

### Reliability semantics

| Mechanism           | Rule                                                                                                              |
| ------------------- | ----------------------------------------------------------------------------------------------------------------- |
| **Idempotency key** | **Required** on side-effecting methods (`send`, `agent`, `chat.send`); the server keeps a short-lived dedup cache |
| **No event replay** | On a `seq` gap the client **must proactively refresh its snapshot**; the server does not resend                   |
| `stateVersion`      | Two monotonic version numbers (presence / health) for deciding whether a local snapshot is stale                  |

**Reads rely on snapshots, writes rely on idempotency** — the correctness basis for reconnecting over a flaky network.

## B.3 Handshake: `connect` (not `hello`)

**The server pushes a challenge first; the client then handshakes.** If the first frame isn't `connect`, or isn't JSON, the connection is closed with 1008.

```jsonc
// ① Gateway pushes immediately on connection
{ "type": "event", "event": "connect.challenge",
  "payload": { "nonce": "…", "ts": 1737264000000 } }

// ② Client handshake (must be the first req frame)
{ "type": "req", "id": "c1", "method": "connect", "params": {
    "minProtocol": 3,
    "maxProtocol": 3,
    "client":  { "id": "openclaw-control-ui", "version": "…",
                 "platform": "web", "mode": "webchat" },
    "role":    "operator",
    "scopes":  ["operator.read", "operator.write"],
    "device":  { "id": "…", "publicKey": "…", "signature": "…",
                 "signedAt": 1737264001000, "nonce": "…" },
    "auth":    { "token": "…" } } }

// ③ Handshake success
{ "type": "res", "id": "c1", "ok": true, "payload": {
    "type": "hello-ok",
    "protocol": 3,
    "auth":   { "deviceToken": "…", "role": "operator", "scopes": ["…"] },
    "policy": { "maxPayload": …, "maxBufferedBytes": …, "tickIntervalMs": 15000 } } }
```

`hello-ok` **does three jobs in one frame**: capability negotiation (full `features.methods` / `events` list) + state snapshot (presence, health, `stateVersion`) + credential rotation (new device token).

### `auth` is one of three

```
{ "token": "…" }  |  { "deviceToken": "…" }  |  { "password": "…" }
```

### How node handshakes differ

```jsonc
"role": "node",
"caps": ["system", "camera", "canvas", "screen"],
"commands": ["system.run", "system.run.prepare", "system.which"],
"permissions": { "camera.capture": true }
```

**`caps` / `commands` / `permissions` are claims only** — the server filters against a per-platform allowlist (§11.5.3).

## B.4 Request Method Reference

There are **110** methods (`BASE_METHODS` in `src/gateway/server-methods-list.ts`; channel plugins may contribute more). Grouped by domain:

### Sessions and chat

| Method                                                    | Purpose                                                     |
| --------------------------------------------------------- | ----------------------------------------------------------- |
| `chat.send`                                               | Send a message to the agent (**requires `idempotencyKey`**) |
| `chat.abort`                                              | Abort the current run                                       |
| `chat.history`                                            | Fetch session history                                       |
| `sessions.list` / `sessions.preview`                      | List / preview sessions                                     |
| `sessions.patch`                                          | Modify session properties (model, thinkingLevel, label…)    |
| `sessions.reset` / `sessions.delete` / `sessions.compact` | Reset / delete / compact                                    |

### Agents

| Method                                         | Purpose                                                     |
| ---------------------------------------------- | ----------------------------------------------------------- |
| `agent`                                        | Start an agent run directly (**requires `idempotencyKey`**) |
| `agent.wait`                                   | Wait for a run to complete                                  |
| `agent.identity.get`                           | Read agent identity                                         |
| `agents.list` / `create` / `update` / `delete` | Agent management                                            |
| `agents.files.list` / `get` / `set`            | Read/write workspace bootstrap files                        |

### Channels and sending

`channels.status`, `channels.logout`, `send`, `talk.config`, `talk.mode`, `tts.convert` / `enable` / `disable` / `providers` / `setProvider` / `status`

### Nodes

`node.list`, `node.describe`, `node.invoke`, `node.rename`, `node.event`, `node.canvas.capability.refresh` `node.pair.request` / `approve` / `reject` / `list` / `verify` `node.pending.pull` / `ack` / `drain` / `enqueue`

### Device admission

`device.pair.list` / `approve` / `reject` / `remove`, `device.token.rotate` / `revoke`

### Exec approvals

`exec.approval.request` / `resolve` / `waitDecision`, `exec.approvals.get` / `set`, `exec.approvals.node.get` / `set`

### Config and operations

| Method                                                              | Purpose                                                                  |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `config.get` / `set` / `patch` / `apply`                            | Read/write config (**`apply` / `patch` are budget-limited: 3 per 60 s**) |
| `config.schema` / `config.schema.lookup`                            | Config schema queries                                                    |
| `secrets.resolve` / `secrets.reload`                                | Secret resolution and reload                                             |
| `update.run`                                                        | Trigger an update (**also budget-limited**)                              |
| `logs.tail`, `health`, `status`, `presence`, `doctor.memory.status` | Diagnostics                                                              |
| `usage.status` / `usage.cost`                                       | Usage and cost                                                           |
| `shutdown`                                                          | Shut the gateway down                                                    |

### Scheduling and wake

`cron`, `cron.add` / `list` / `update` / `remove` / `run` / `runs` / `status`, `wake`, `heartbeat`, `tick`

### Other

`models.list`, `tools.catalog`, `browser.request`, `skills.status` / `install` / `update` / `bins`, `voicewake.get` / `set`, `wizard.start` / `next` / `cancel` / `status`

> **Names that are easy to get wrong** (earlier editions of this book had them wrong; now corrected):

| Common mistake     | Actual method                                                        |
| ------------------ | -------------------------------------------------------------------- |
| `sessions.history` | **`chat.history`**                                                   |
| `config.reload`    | **`config.apply`** / `config.patch` (secrets use `secrets.reload`)   |
| `skills.list`      | **`skills.status`**                                                  |
| `sessions.resolve` | Does not exist                                                       |
| `events.subscribe` | Does not exist — **events are pushed; there is no subscribe method** |

That last one deserves emphasis: once connected and handshaken, **you automatically receive every event visible to your role**. There is no subscribe/unsubscribe concept; filtering happens server-side by role and scope.

## B.5 Event Types

The full list (`GATEWAY_EVENTS`, `server-methods-list.ts:112`):

| Event                                                | Purpose                                                                 |
| ---------------------------------------------------- | ----------------------------------------------------------------------- |
| `connect.challenge`                                  | **Pre-handshake**, delivers the nonce                                   |
| `chat`                                               | Chat state changes (delta / final / aborted / error)                    |
| `agent`                                              | Agent activity stream (`stream: "tool" \| "lifecycle" \| "thinking"`)   |
| `presence`                                           | Presence changes                                                        |
| `health`                                             | Health state changes                                                    |
| `tick`                                               | Heartbeat tick (interval given by `hello-ok`'s `policy.tickIntervalMs`) |
| `heartbeat`                                          | Heartbeat turn events                                                   |
| `cron`                                               | Scheduled job events                                                    |
| `talk.mode`                                          | Voice mode changes                                                      |
| `shutdown`                                           | Gateway shutdown notice                                                 |
| `node.pair.requested` / `node.pair.resolved`         | Node pairing request / outcome                                          |
| `node.invoke.request`                                | **Reverse RPC**: Gateway calling a node (§27.4)                         |
| `device.pair.requested` / `device.pair.resolved`     | Device pairing request / outcome                                        |
| `exec.approval.requested` / `exec.approval.resolved` | Exec approval request / outcome                                         |
| `voicewake.changed`                                  | Voice-wake state change                                                 |
| `update.available`                                   | A new version is available                                              |

## B.6 Device Authentication Error Codes

Six failures, each with structured `details.code` / `details.reason` and a `recommendedNextStep`:

```
DEVICE_AUTH_NONCE_REQUIRED
DEVICE_AUTH_NONCE_MISMATCH
DEVICE_AUTH_SIGNATURE_INVALID
DEVICE_AUTH_SIGNATURE_EXPIRED
DEVICE_AUTH_DEVICE_ID_MISMATCH
DEVICE_AUTH_PUBLIC_KEY_INVALID
```

Plus `AUTH_TOKEN_MISMATCH`: a trusted client may make exactly **one** bounded retry using its cached device token (anti-reconnect-storm).

## B.7 Scopes

**Two roles**: `operator` (control plane) and `node` (capability host) — **bidirectionally isolated**: nodes can only call node methods, and operators conversely cannot call them.

**Five operator scopes**:

```
operator.read
operator.write
operator.admin
operator.approvals
operator.pairing
```

> The docs stress **"Method scope is only the first gate"** — slash commands inside `chat.send` face stricter command-level checks (e.g. `/config set` requires `operator.admin`).
>
> A connection with no device-identity binding has **its self-declared scopes cleared outright** (deny by default).

***

## Appendix Summary

1. **Protocol version 3**; three frames; responses use **`ok` + `payload`** (not `result`); unknown fields rejected.
2. **The handshake is `connect`, not `hello`**, and **the server pushes `connect.challenge` first**; `hello-ok` does capability negotiation + state snapshot + credential rotation in one frame.
3. **Reads rely on snapshots, writes rely on idempotency**: no event replay (refresh on a seq gap), idempotency keys required on side-effecting methods.
4. 110 methods grouped by domain; watch the four common misspellings (`chat.history` / `config.apply` / `skills.status`), and note **there is no `events.subscribe` — events are pushed**.
5. 19 event types; `node.invoke.request` carries reverse RPC.
6. **Roles are bidirectionally isolated**, operators have five scopes, and **method-level scope is only the first gate**.
