Contents

OpenClaw Architecture

If you build a multi-channel AI assistant by spinning up a separate bot process for every messaging app, three problems show up fast: conversation context fragments across processes, local device capabilities (screenshots, shell access, location) become awkward to expose safely, and maintaining persistent platform sessions turns fragile. OpenClaw takes the opposite approach—it consolidates all messaging channels, session state, scheduled jobs, and device nodes behind a single long-lived Gateway daemon per host, with the agent runtime embedded inside and external clients talking over one typed WebSocket protocol.

One principle explains almost every design choice in OpenClaw (Gateway Protocol v4): routing and personas can be split freely inside a Gateway, but the Gateway process itself is the minimum security trust boundary.

For installation, loopback binding, pairing, and allowlist hardening, pair this post with OpenClaw Best Practices; for a broader mental model of agent runtimes, see AI Agent Design Patterns. Here we focus on OpenClaw’s architecture and its invariants.

The Gateway as the Single Messaging and Control Plane

In OpenClaw’s Gateway architecture, every chat platform—WhatsApp, Telegram, Slack, Discord, Signal, iMessage, WebChat, and more—attaches to the Gateway as a channel plugin. WhatsApp uses Baileys for linked-device sessions, and Telegram uses grammY with long polling by default.

Plugins stay strictly in the translation layer: they normalize platform events into Gateway envelopes while sockets, reconnect loops, and credentials remain inside the daemon. The topology is a clean hub-and-spoke layout:

Channels / WebChat      Clients (operator)         Nodes (role: node)
WhatsApp · Telegram     CLI · TUI · Control UI     macOS / iOS / Android
Slack · Discord · …     macOS app · automations    headless node host
        \                      |                          /
         \                     |                         /
          v                    v                        v
     ┌─────────────────────────────────────────────────────┐
     │  Gateway daemon   ws+http  127.0.0.1:18789          │
     │  channel sockets · SQLite sessions · bindings       │
     │  typed WS RPC · cron · canvas HTTP · node.invoke    │
     └──────────────────────────┬──────────────────────────┘
                                │
                                v
                    Agent runtime (embedded)
                    workspace · model loop · tools
                    MEMORY.md / memory/*.md

As documented in the FAQ, a live request follows one deterministic path:

Telegram → Gateway → Agent → node.* → Node → Gateway → Telegram

A common misconception is that device nodes inspect or route chat traffic. They do not. Inbound messages terminate at the Gateway, the model loop executes inside the Gateway’s embedded agent runtime, and a Node is only invoked via node.invoke when a tool requires hardware or local OS capabilities.

What the Single-Host Daemon Owns and Enforces

By default, Gateway runs one instance per host, bound to loopback 127.0.0.1:18789 (remote access travels over an SSH or Tailscale tunnel). That single port multiplexes two surfaces:

  • WebSocket: All control-plane RPC calls and Node device transport.
  • HTTP: Control UI, hooks, /__openclaw__/canvas/, /__openclaw__/a2ui/, and OpenAI-compatible endpoints such as /v1/models.

Even though HTTP shares the port, the control plane remains WebSocket-native. WebChat itself is an internal channel speaking the same Gateway WS (chat.history / chat.send), with the Control UI HTTP layer acting purely as a shell.

The architecture enforces four core invariants:

  1. Exclusive channel session ownership: Only one process per host may hold a WhatsApp/Baileys session. Running two processes against the same linked session causes session collisions—this is an architectural constraint, not an ops preference.
  2. Strict first-frame validation: Inbound WS frames are validated against JSON Schema (TypeBox). The first frame after connecting must be connect, or the server immediately closes the socket.
  3. No event replay: Real-time push events are not replayed. If a client observes a gap in sequence numbers (seq), it must fetch a fresh snapshot.
  4. In-process scheduling: Cron and heartbeat jobs run inside the Gateway daemon; if the daemon stops, scheduled triggers stop with it.

Inbound channels and outbound model providers live in the same daemon, yet remain cleanly decoupled: incoming messages map to a session key and enter the agent loop serially per session. Concurrent messages hitting the same session pass through queue policies (steer, followup, collect, or interrupt) so multiple channels cannot corrupt a single transcript.

For operational inspection, the official CLI exposes four core checks:

openclaw gateway status
openclaw channels status --probe
openclaw agents list --bindings
openclaw sessions --json

gateway status verifies both supervisor state and a live WebSocket connectivity probe, while channels status --probe confirms whether external IM surfaces are actually reachable. A running process or an accessible HTTP Control UI does not guarantee healthy WS RPC or channel sessions.

Wire Protocol: Three Frames and Three Roles

Gateway Protocol (currently v4) is the sole transport for both operators and nodes. After a server connect.challenge, the client sends connect as its first frame and receives hello-ok carrying features, snapshot, policy, and auth.

Keep in mind that hello-ok.features.methods is a conservative discovery list rather than an exhaustive catalog of every supported RPC method. Clients should negotiate capabilities by protocol version instead of treating discovery output as a full SDK contract.

The wire format uses three frame types:

{ "type": "req", "id": "r1", "method": "health", "params": {} }
{ "type": "res", "id": "r1", "ok": true, "payload": { "ok": true } }
{ "type": "event", "event": "tick", "payload": { "ts": 1730000000 }, "seq": 12 }

Side-effecting methods such as send, agent, and chat.send require an idempotencyKey to prevent duplicate delivery on retries. An agent run follows a three-step lifecycle: immediate acknowledgment, streamed progress events, and a terminal response:

sequenceDiagram participant Client participant Gateway Client->>Gateway: req:connect Gateway-->>Client: res (ok, payload=hello-ok) Gateway-->>Client: event:presence / event:tick Client->>Gateway: req:agent (with idempotencyKey) Gateway-->>Client: res:agent ack {runId, status:"accepted"} Gateway-->>Client: event:agent (streaming chunks) Gateway-->>Client: res:agent final {runId, status, summary}

During connect, every peer declares a role with strict boundaries:

role Purpose Explicit Boundary
operator CLI, TUI, Control UI, macOS control surface issuing RPCs and subscribing to events Does not expose local hardware or system.run
node macOS / iOS / Android / headless host exposing camera, canvas, location, and local commands Not a second Gateway; never ingests chat channels
worker Closed-protocol cloud execution host on /__openclaw__/worker Outside the general operator RPC surface

Nodes declare caps, commands, and permissions during connect, but the Gateway treats those strictly as claims. Actual execution passes through two server-side gates: per-device Device Pairing for handshake identity and node.pair.* allowlists for permitted commands.

Practical note: On macOS, the menu-bar app already registers as a node—do not launch a second CLI node on the same Mac. Likewise, do not try to write a custom “Agent WebSocket server”: the agent runtime is embedded in the Gateway, so custom integrations should either build an operator client or configure agent workspaces and bindings.

Session Is Routing; Memory Is Markdown on Disk

OpenClaw keeps conversational state and durable knowledge cleanly separated by ownership and storage:

  • Session belongs to the Gateway: It stores the active transcript, routing coordinates, and compaction state. UIs query the Gateway instead of keeping local authoritative state. Default storage lives at ~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite.
  • Memory belongs to the agent workspace: Plain Markdown files under ~/.openclaw/workspace. MEMORY.md holds distilled long-term facts injected at session start; memory/YYYY-MM-DD.md holds daily logs retrieved via search rather than preloaded every turn; USER.md, SOUL.md, and AGENTS.md define persona, preferences, and operating rules.

Default mapping from inbound sources to sessionKey:

Source Default Session
Direct Message (DM) Collapses into the agent’s main session (agent:<id>:main)
Group / Room Isolated per group (:thread: for Slack/Discord threads, :topic: for Telegram forum topics)
Cron Fresh session per run
Webhook Isolated per hook

A frequent configuration pitfall: If multiple people can DM the same bot while session.dmScope remains "main", Alice’s conversation context leaks into Bob’s session. That is a session-key scoping issue, not a MEMORY.md bug. Whenever a bot serves multiple DM users, explicitly isolate sessions per channel peer:

{
  session: {
    dmScope: "per-channel-peer",
  },
}

Even setting session.scope: "global" does not merge transcripts across different agents—accounting still stays scoped to the routed agent.

Multi-Agent in One Gateway vs. Multiple Gateways

Under Multi-agent, each agent is an independent brain with its own workspace, agentDir, and SQLite session store, routed via bindings on (channel, accountId, peer). If you wire external coding agents into OpenClaw, see OpenClaw with Copilot CLI Best Practices. Responsibilities divide cleanly:

Surface Owned by Gateway Configured per Agent
Channel sockets, reconnects, account login Yes No
Session keys, transcripts, compaction Yes No
WS protocol, device pairing, node.invoke Yes No
Cron / heartbeat scheduling & Canvas HTTP Yes No
AGENTS.md / SOUL.md / MEMORY.md No Yes
Model choice, skills snapshot, tool loop Embedded in daemon Configured per agent
Hard tool boundaries (allowlist, sandbox, exec approval) Enforced by Gateway Agent may tighten, never loosen global policy

Deciding between one Gateway and many comes down to trust boundaries, not channel count or persona count:

Use a single Gateway (with multiple agents) when:

  • Every operator sits inside the same trust domain—a personal assistant or a small, mutually trusting team sharing one deployment.
  • You want WhatsApp, Telegram, Discord, Feishu, Matrix, and personal device nodes unified under one control plane.
  • You want separate personas or project workspaces: adding agents.entries and bindings is lightweight.

Split into separate Gateways (isolated OPENCLAW_STATE_DIR, workspace, port, or OS user/host) when:

  • You mix different risk tiers—for example, a high-privilege personal assistant alongside a team bot or public-facing entry point.
  • Users do not trust one another. Neither sessionKey nor agentId isolates host-level credentials, browser sessions, or local files inside the same privileged process. As the docs put it: a gateway is one trust domain.
  • You maintain an isolated rescue bot or completely separate state trees (see Multiple gateways).

Debugging the Most Common Failure: Close Code 1008

When building a custom client or placing a reverse proxy in front of the Gateway, the most common error is an immediate WebSocket disconnect with code 1008. This is rarely a broken IM token—it means the protocol gate rejected the connection because the first frame was not a valid JSON connect frame (often caused by hitting an HTTP path as WS or a proxy stripping WebSocket upgrade headers).

Start with openclaw gateway status and verify that Probe target shows ws:// (or wss://) and Connectivity probe succeeds. Once the protocol handshake is healthy, run openclaw channels status --probe to diagnose channel-specific credentials. If messages appear to cross between users, inspect session.dmScope and openclaw sessions --json before blaming the model.

References