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

# 12.3 Core Methods and Events

> **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 two sections, we understood the protocol's design philosophy and type system. Now let's see concretely: what can clients do through this protocol? What events will the server push? This section will analyze the core methods and events provided by Gateway one by one.

## 12.3.1 Overview of Request Methods

All request methods supported by Gateway are defined in `src/gateway/server-methods-list.ts`:

```typescript
// src/gateway/server-methods-list.ts
const BASE_METHODS = [
  // ─── System and Operations ───
  "health",              // Health check
  "status",              // System status
  "logs.tail",           // Real-time logs

  // ─── Channel Management ───
  "channels.status",     // Channel connection status
  "channels.logout",     // Logout from channel

  // ─── Configuration Operations ───
  "config.get",          // Get configuration
  "config.set",          // Set configuration
  "config.apply",        // Apply configuration changes
  "config.patch",        // Partial configuration update
  "config.schema",       // Get configuration Schema

  // ─── Execution Approvals ───
  "exec.approvals.get",  // Get approval policy
  "exec.approvals.set",  // Set approval policy
  "exec.approval.request",  // Request approval
  "exec.approval.resolve",  // Approve/reject

  // ─── Onboarding Wizard ───
  "wizard.start",        // Start onboarding wizard
  "wizard.next",         // Next step
  "wizard.cancel",       // Cancel wizard
  "wizard.status",       // Wizard status

  // ─── AI Conversation ───
  "agent",               // Initiate Agent conversation
  "agent.identity.get",  // Get Agent identity info
  "agent.wait",          // Wait for Agent execution to complete
  "send",                // Send message to channel
  "wake",                // Wake up Agent

  // ─── Models and Skills ───
  "models.list",         // List available models
  "agents.list",         // List Agent configurations
  "agents.files.list",   // List Agent files
  "agents.files.get",    // Read Agent file
  "agents.files.set",    // Write Agent file
  "skills.status",       // Skill status
  "skills.bins",         // Skill binaries
  "skills.install",      // Install skill
  "skills.update",       // Update skill

  // ─── Session Management ───
  "sessions.list",       // List sessions
  "sessions.preview",    // Preview session content
  "sessions.patch",      // Modify session properties
  "sessions.reset",      // Reset session
  "sessions.delete",     // Delete session
  "sessions.compact",    // Compact session

  // ─── Node Operations ───
  "node.pair.request",   // Request node pairing
  "node.pair.list",      // List pairing requests
  "node.pair.approve",   // Approve pairing
  "node.pair.reject",    // Reject pairing
  "node.pair.verify",    // Verify pairing
  "node.rename",         // Rename node
  "node.list",           // List nodes
  "node.describe",       // Describe node
  "node.invoke",         // Invoke node
  "node.invoke.result",  // Return node invocation result
  "node.event",          // Node event

  // ─── Device Management ───
  "device.pair.list",    // List device pairing requests
  "device.pair.approve", // Approve device pairing
  "device.pair.reject",  // Reject device pairing
  "device.token.rotate", // Rotate device token
  "device.token.revoke", // Revoke device token

  // ─── Scheduled Tasks ───
  "cron.list",           // List scheduled tasks
  "cron.status",         // Task status
  "cron.add",            // Add task
  "cron.update",         // Update task
  "cron.remove",         // Remove task
  "cron.run",            // Manually run task
  "cron.runs",           // Run history

  // ─── Heartbeat and Presence ───
  "last-heartbeat",      // Last heartbeat
  "set-heartbeats",      // Set heartbeats
  "system-presence",     // System presence info
  "system-event",        // System event

  // ─── TTS (Text-to-Speech) ───
  "tts.status",          // TTS status
  "tts.providers",       // TTS provider list
  "tts.enable",          // Enable TTS
  "tts.disable",         // Disable TTS
  "tts.convert",         // Text-to-speech conversion
  "tts.setProvider",     // Set provider

  // ─── WebChat Methods ───
  "chat.history",        // Chat history
  "chat.send",           // Send chat message
  "chat.abort",          // Abort chat

  // ─── Others ───
  "usage.status",        // Usage statistics
  "usage.cost",          // Cost statistics
  "update.run",          // Run update
  "talk.mode",           // Talk mode switching
  "voicewake.get",       // Voice wake settings
  "voicewake.set",       // Voice wake settings
  "browser.request",     // Browser operation request
];
```

The method list is not static. The `listGatewayMethods()` function dynamically merges additional methods registered by channel plugins:

```typescript
export function listGatewayMethods(): string[] {
  const channelMethods = listChannelPlugins()
    .flatMap((plugin) => plugin.gatewayMethods ?? []);
  return Array.from(new Set([...BASE_METHODS, ...channelMethods]));
}
```

> **Sidebar**: This **plugin extension** design pattern is very common in web frameworks. For example, Express.js middleware can register new routes, and Webpack plugins can register new lifecycle hooks. OpenClaw's channel plugins can also register new methods with Gateway—for example, a Slack extension might register a `slack.interactivity` method to handle Slack's interactive message callbacks.

Methods use **dot-separated namespacing** (Dot-separated Namespace), which is a clear organizational approach:

| Namespace    | Meaning                  | Examples                           |
| ------------ | ------------------------ | ---------------------------------- |
| `config.*`   | Configuration operations | `config.get`, `config.set`         |
| `sessions.*` | Session management       | `sessions.list`, `sessions.delete` |
| `node.*`     | Node operations          | `node.invoke`, `node.list`         |
| `device.*`   | Device management        | `device.pair.approve`              |
| `cron.*`     | Scheduled tasks          | `cron.add`, `cron.remove`          |
| `skills.*`   | Skill management         | `skills.install`, `skills.status`  |
| `exec.*`     | Execution approvals      | `exec.approval.request`            |
| `chat.*`     | WebChat                  | `chat.send`, `chat.history`        |

This design is also key for **feature negotiation** during connection handshake—the `features.methods` array in the `HelloOk` response tells the client which methods the current Gateway supports.

## 12.3.2 `connect` — Handshake and Authentication

`connect` is the first step for a client to establish communication with Gateway. Strictly speaking, `connect` is not a standard request method (it's sent by the client immediately after the WebSocket connection is established, not invoked through a `req` frame), but it follows a similar request-response pattern.

### Connection Request (ConnectParams)

```typescript
// src/gateway/protocol/schema/frames.ts
export const ConnectParamsSchema = Type.Object({
  // Protocol version negotiation
  minProtocol: Type.Integer({ minimum: 1 }),  // Minimum protocol version supported by client
  maxProtocol: Type.Integer({ minimum: 1 }),  // Maximum protocol version supported by client

  // Client identity information
  client: Type.Object({
    id: GatewayClientIdSchema,          // Client type (e.g., "cli", "openclaw-macos")
    displayName: Type.Optional(NonEmptyString),
    version: NonEmptyString,             // Client version number
    platform: NonEmptyString,            // Runtime platform (e.g., "darwin", "win32")
    deviceFamily: Type.Optional(NonEmptyString),   // Device family
    modelIdentifier: Type.Optional(NonEmptyString),// Hardware model
    mode: GatewayClientModeSchema,       // Client mode (e.g., "cli", "ui")
    instanceId: Type.Optional(NonEmptyString),     // Instance ID
  }),

  // Capability declaration
  caps: Type.Optional(Type.Array(NonEmptyString)),
  commands: Type.Optional(Type.Array(NonEmptyString)),
  permissions: Type.Optional(Type.Record(NonEmptyString, Type.Boolean())),

  // Authentication information
  auth: Type.Optional(Type.Object({
    token: Type.Optional(Type.String()),    // Token authentication
    password: Type.Optional(Type.String()), // Password authentication
  })),

  // Device authentication (asymmetric key signature)
  device: Type.Optional(Type.Object({
    id: NonEmptyString,
    publicKey: NonEmptyString,
    signature: NonEmptyString,     // Signature
    signedAt: Type.Integer(),      // Signature timestamp
    nonce: Type.Optional(NonEmptyString), // Nonce (v2)
  })),

  // Others
  role: Type.Optional(NonEmptyString),
  scopes: Type.Optional(Type.Array(NonEmptyString)),
  locale: Type.Optional(Type.String()),
  userAgent: Type.Optional(Type.String()),
  pathEnv: Type.Optional(Type.String()),
});
```

This structure carries a lot of information. Let's parse it by groups:

**Protocol Version Negotiation**: `minProtocol` and `maxProtocol` allow the client and server to negotiate using a protocol version that both support. The current protocol version is 3. If the server doesn't support the version range required by the client, the connection will be rejected.

**Client Identity**: The `client` field identifies "who is connecting." This is not only used for logging but also affects Gateway's behavior—for example, clients with `mode: "cli"` and `mode: "ui"` may have different permissions and capabilities.

**Capability Declaration**: `caps` (Capabilities) let the client declare additional capabilities it supports. Currently defined capabilities include:

```typescript
export const GATEWAY_CLIENT_CAPS = {
  TOOL_EVENTS: "tool-events",  // Client supports receiving tool events
} as const;
```

### Connection Response (HelloOk)

After successful connection, Gateway returns a `HelloOk` message:

```typescript
export const HelloOkSchema = Type.Object({
  type: Type.Literal("hello-ok"),
  // Negotiation result
  protocol: Type.Integer({ minimum: 1 }),  // Protocol version agreed upon by both parties

  // Server information
  server: Type.Object({
    version: NonEmptyString,    // Gateway version number
    commit: Type.Optional(NonEmptyString),   // Git commit
    host: Type.Optional(NonEmptyString),     // Hostname
    connId: NonEmptyString,     // Connection ID (uniquely identifies this connection)
  }),

  // Feature list
  features: Type.Object({
    methods: Type.Array(NonEmptyString),  // List of supported methods
    events: Type.Array(NonEmptyString),   // List of supported events
  }),

  // Current state snapshot
  snapshot: SnapshotSchema,

  // Connection policy
  policy: Type.Object({
    maxPayload: Type.Integer({ minimum: 1 }),      // Maximum message size (bytes)
    maxBufferedBytes: Type.Integer({ minimum: 1 }), // Maximum buffer size
    tickIntervalMs: Type.Integer({ minimum: 1 }),   // Heartbeat interval (milliseconds)
  }),

  // Authentication result
  auth: Type.Optional(Type.Object({
    deviceToken: NonEmptyString,  // Assigned device token
    role: NonEmptyString,         // Assigned role
    scopes: Type.Array(NonEmptyString), // Permission scopes
    issuedAtMs: Type.Optional(Type.Integer()),
  })),

  canvasHostUrl: Type.Optional(NonEmptyString),
});
```

A few key points:

1. **`features.methods`** and **`features.events`** tell the client which operations the current Gateway supports. This implements **runtime feature discovery**—clients don't need to hardcode a method list but dynamically obtain it at connection time.
2. **`snapshot`** contains the system state at the moment of connection (online users, health status, etc.), which clients can use to initialize the UI without needing additional requests.
3. **`policy`** informs the client of connection limit parameters. `maxPayload` prevents clients from sending oversized messages, and `tickIntervalMs` tells the client the heartbeat frequency.

## 12.3.3 `agent` / `agent.wait` — Initiate AI Conversation

The `agent` method is the most core operation in OpenClaw—it allows clients to initiate an AI conversation.

### agent Method Parameters

```typescript
// src/gateway/protocol/schema/agent.ts
export const AgentParamsSchema = Type.Object({
  // Required parameters
  message: NonEmptyString,           // User message
  idempotencyKey: NonEmptyString,    // Idempotency key

  // Agent selection
  agentId: Type.Optional(NonEmptyString),  // Specify Agent (leave empty to use default)

  // Session selection
  sessionId: Type.Optional(Type.String()),   // Session ID
  sessionKey: Type.Optional(Type.String()),  // Session key
  label: Type.Optional(SessionLabelString),  // Session label

  // Message routing
  to: Type.Optional(Type.String()),          // Send target
  replyTo: Type.Optional(Type.String()),     // Reply target
  channel: Type.Optional(Type.String()),     // Channel
  replyChannel: Type.Optional(Type.String()),// Reply channel
  accountId: Type.Optional(Type.String()),   // Account ID
  replyAccountId: Type.Optional(Type.String()),
  threadId: Type.Optional(Type.String()),    // Thread ID (e.g., Slack thread)
  groupId: Type.Optional(Type.String()),     // Group ID
  groupChannel: Type.Optional(Type.String()),
  groupSpace: Type.Optional(Type.String()),

  // Behavior control
  thinking: Type.Optional(Type.String()),     // Thinking level
  deliver: Type.Optional(Type.Boolean()),     // Whether to deliver reply
  timeout: Type.Optional(Type.Integer()),     // Timeout (milliseconds)
  lane: Type.Optional(Type.String()),         // Execution lane (concurrency control)
  extraSystemPrompt: Type.Optional(Type.String()), // Extra system prompt

  // Attachments
  attachments: Type.Optional(Type.Array(Type.Unknown())),

  // Sub-agent tracking
  spawnedBy: Type.Optional(Type.String()),
});
```

This is one of the most complex parameter structures in the entire protocol. The reason for many fields is that the `agent` method needs to handle messages from multiple channels simultaneously—a message from CLI might only need `message` and `idempotencyKey`, while a message from a Slack group also needs routing information like `threadId`, `groupId`, and `channel`.

### agent.wait — Wait for Execution to Complete

The `agent` method is **asynchronous**—it immediately returns a `runId`, and the actual Agent execution happens in the background, with results pushed through events. However, some scenarios need **synchronous waiting** for results, such as CLI executing `openclaw ask "What is OpenClaw?"`.

The `agent.wait` method satisfies this need:

```typescript
export const AgentWaitParamsSchema = Type.Object({
  runId: NonEmptyString,                            // Run ID to wait for
  timeoutMs: Type.Optional(Type.Integer({ minimum: 0 })), // Wait timeout
});
```

Call flow:

```
Client ─── req(method="agent", params={message:"Hello"}) ──▶ Server
       ◀── res(payload={runId:"run_abc"}) ──────────────── Server
       ── req(method="agent.wait", params={runId:"run_abc"}) ──▶ Server
       ◀── event(agent, payload={stream:"text", data:...}) ── Server
       ◀── event(agent, payload={stream:"text", data:...}) ── Server
       ◀── res(payload={...final result...}) ──────────────── Server
```

## 12.3.4 `send` — Send Message to Channel

The `send` method allows an Agent or client to send a message to a specific channel:

```typescript
export const SendParamsSchema = Type.Object({
  to: NonEmptyString,              // Send target (user ID, group ID, etc.)
  message: NonEmptyString,         // Message content
  mediaUrl: Type.Optional(Type.String()),   // Single media URL
  mediaUrls: Type.Optional(Type.Array(Type.String())), // Multiple media URLs
  gifPlayback: Type.Optional(Type.Boolean()),  // GIF playback flag
  channel: Type.Optional(Type.String()),       // Specify channel
  accountId: Type.Optional(Type.String()),     // Specify account
  sessionKey: Type.Optional(Type.String()),    // Associate session
  idempotencyKey: NonEmptyString,  // Idempotency key
});
```

The difference between `send` and `agent` is: `agent` is "ask AI to process this message," while `send` is "directly send this message to the target channel." `send` is typically used by Agent in tool calls (for example, an Agent decides to send a notification to a Slack channel).

`PollParamsSchema` is a variant of `send`, used for sending polls:

```typescript
export const PollParamsSchema = Type.Object({
  to: NonEmptyString,
  question: NonEmptyString,
  options: Type.Array(NonEmptyString, { minItems: 2, maxItems: 12 }),
  maxSelections: Type.Optional(Type.Integer({ minimum: 1, maximum: 12 })),
  durationHours: Type.Optional(Type.Integer({ minimum: 1 })),
  channel: Type.Optional(Type.String()),
  accountId: Type.Optional(Type.String()),
  idempotencyKey: NonEmptyString,
});
```

Poll options are limited to 2–12, and the maximum number of selections is limited to 12—these constraints are directly expressed through TypeBox Schema constraints.

## 12.3.5 `sessions.*` — Session Management Method Family

Sessions are context containers for AI conversations in OpenClaw. The `sessions.*` method family provides complete CRUD operations for sessions:

| Method             | Function                  | Parameter Features                                                         |
| ------------------ | ------------------------- | -------------------------------------------------------------------------- |
| `sessions.list`    | List sessions             | Supports filtering: `limit`, `activeMinutes`, `label`, `agentId`, `search` |
| `sessions.preview` | Preview session content   | Supports batch preview of multiple sessions, can limit character count     |
| `sessions.resolve` | Resolve session           | Locate session through multiple methods: `key`, `sessionId`, `label`, etc. |
| `sessions.patch`   | Modify session properties | Can modify `label`, `model`, `thinkingLevel`, `execSecurity`, etc.         |
| `sessions.reset`   | Reset session             | Clear conversation history, preserve session key                           |
| `sessions.delete`  | Delete session            | Optionally delete transcript files simultaneously                          |
| `sessions.compact` | Compact session           | Call LLM to summarize old messages, reduce context length                  |

The parameters of `sessions.patch` are particularly rich, reflecting the configurability of sessions:

```typescript
export const SessionsPatchParamsSchema = Type.Object({
  key: NonEmptyString,
  label: Type.Optional(Type.Union([SessionLabelString, Type.Null()])),
  thinkingLevel: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
  reasoningLevel: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
  model: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
  execHost: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
  execSecurity: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
  sendPolicy: Type.Optional(Type.Union([
    Type.Literal("allow"),
    Type.Literal("deny"),
    Type.Null(),
  ])),
  // ... more configurable fields
});
```

Note a design pattern: almost all fields are `Type.Union([SomeType, Type.Null()])` — pass a value to set, pass `null` to reset to default, don't pass to keep unchanged. This is an elegant **three-state update** pattern.

## 12.3.6 Event Types

In addition to request methods, Gateway also actively pushes events. All event types are defined in the `GATEWAY_EVENTS` array:

```typescript
// src/gateway/server-methods-list.ts
export const GATEWAY_EVENTS = [
  "connect.challenge",      // Connection challenge (device authentication)
  "agent",                  // Agent execution event (streaming output)
  "chat",                   // WebChat message event
  "presence",               // Presence change
  "tick",                   // Heartbeat
  "talk.mode",              // Talk mode change
  "shutdown",               // Server shutdown notification
  "health",                 // Health status change
  "heartbeat",              // Heartbeat event
  "cron",                   // Scheduled task trigger
  "node.pair.requested",    // Node pairing request
  "node.pair.resolved",     // Node pairing result
  "node.invoke.request",    // Node invocation request
  "device.pair.requested",  // Device pairing request
  "device.pair.resolved",   // Device pairing result
  "voicewake.changed",      // Voice wake setting change
  "exec.approval.requested",// Execution approval request
  "exec.approval.resolved", // Execution approval result
];
```

### agent Event

The `agent` event is the most core event type, carrying all streaming output during Agent execution:

```typescript
export const AgentEventSchema = Type.Object({
  runId: NonEmptyString,    // Run ID (associated with which agent call)
  seq: Type.Integer({ minimum: 0 }),  // Sequence number (ensures event order)
  stream: NonEmptyString,   // Stream name (e.g., "text", "tool-call", "tool-result")
  ts: Type.Integer({ minimum: 0 }),   // Timestamp
  data: Type.Record(Type.String(), Type.Unknown()), // Event data
});
```

The `stream` field distinguishes different types of event data:

* `"text"` — Text chunks generated by the model
* `"tool-call"` — Model decides to call a tool
* `"tool-result"` — Tool execution result
* `"thinking"` — Model's thinking process
* `"error"` — Runtime error

The `seq` sequence number ensures that even if event arrival order is scrambled (extremely rare at the network layer, but theoretically possible in multiplexing scenarios), the client can correctly reorder them.

### tick Event

`tick` is a simple heartbeat event:

```typescript
export const TickEventSchema = Type.Object({
  ts: Type.Integer({ minimum: 0 }),  // Server timestamp
});
```

Gateway sends `tick` events at intervals specified by `policy.tickIntervalMs`. Clients use this to:

1. Confirm the connection is still active
2. Synchronize clock difference with the server

### shutdown Event

When Gateway is about to shut down, it sends a `shutdown` event to all connected clients:

```typescript
export const ShutdownEventSchema = Type.Object({
  reason: NonEmptyString,  // Shutdown reason (e.g., "upgrade", "manual")
  restartExpectedMs: Type.Optional(Type.Integer({ minimum: 0 })),
  // Expected restart time (if any)
});
```

`restartExpectedMs` is a thoughtful design—if Gateway restarts due to an upgrade, the client knows approximately when it can try to reconnect, rather than blindly retrying.

### State Version and Incremental Synchronization

Event frames can carry a `stateVersion` field:

```typescript
export const StateVersionSchema = Type.Object({
  presence: Type.Integer({ minimum: 0 }),  // Presence state version
  health: Type.Integer({ minimum: 0 }),    // Health state version
});
```

> **Sidebar**: State version (State Version) is an **optimistic concurrency control** (Optimistic Concurrency Control) technique. Whenever a state changes, the version number increments. Clients remember the current version number; if an event's version number is greater than their recorded version number, they know the state has changed and needs updating. This is much more efficient than fetching the complete state every time.
>
> Similar designs are also common in databases—for example, PostgreSQL's MVCC (Multi-Version Concurrency Control) and etcd's revision mechanism.

***

## Summary of This Section

Gateway's method and event design embodies several principles:

1. **Functional families**: Organize 80+ methods into clear functional groups through dot-separated namespacing
2. **Async-first**: The `agent` method is asynchronous, with results pushed through event streams; `agent.wait` provides the option for synchronous waiting
3. **Rich metadata**: Exchange large amounts of information during `connect` handshake (version, capabilities, state snapshot), reducing subsequent round-trip communication
4. **Three-state update pattern**: Methods like `sessions.patch` use the "pass value to set, pass null to reset, don't pass to keep" pattern
5. **Event-driven**: 18 event types cover all aspects of system state changes, allowing clients to subscribe to events of interest

In the next section, we will dive into Gateway's authentication mechanism—how Token authentication, device pairing, and Origin checking protect WebSocket connection security.
