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

# 1.2 OpenClaw's Core Architecture Overview

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

***

Understanding OpenClaw's overall architecture is the foundation for diving into its source code. This section will introduce OpenClaw's core components and data flow from a high-level perspective.

## 1.2.1 Architecture Diagram: Message Channels → Gateway Control Plane → Pi Agent Runtime → Tool Execution

OpenClaw's architecture can be summarized in one sentence: **multiple message channels (Channels) are embedded as plugins within the Gateway process; Gateway routes messages to an AI Agent runtime for processing, the Agent can invoke various tools to complete tasks, and finally sends replies back to the user through the original channel**.

The following diagram shows the complete architecture:

```
                    ┌─────────────────────────────────────────────┐
                    │         Message Channels (Channels)          │
                    │      [Embedded within Gateway process]       │
                    │                                             │
                    │  WhatsApp  Telegram  Discord  Slack  Signal │
                    │  iMessage  WebChat   Teams    Matrix   ...  │
                    └──────────────────┬──────────────────────────┘
                                       │
                                       │ Inbound messages (in-process function calls, not network)
                                       ▼
┌──────────────────────────────────────────────────────────────────────┐
│                                                                      │
│                   Gateway (Control Plane)                             │
│                   ws://127.0.0.1:18789                               │
│                                                                      │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────┐ │
│  │  WebSocket   │  │   Session     │  │   Channel    │  │   Auth   │ │
│  │   Server    │  │  Management   │  │   Routing    │  │          │ │
│  └─────────────┘  └──────────────┘  └──────────────┘  └──────────┘ │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────┐ │
│  │  HTTP Server │  │   Cron        │  │   Hook       │  │ Config   │ │
│  │ (OpenAI API) │  │  Scheduling   │  │   System     │  │Management│ │
│  └─────────────┘  └──────────────┘  └──────────────┘  └──────────┘ │
│                                                                      │
└──────────┬───────────────────────────────────────┬──────────────────┘
           │                                       │
           │ Agent RPC call                        │ WebSocket connection
           ▼                                       ▼
┌────────────────────────────────┐  ┌──────────────────────────────────┐
│                                │  │       Clients (Clients)           │
│  Pi Agent Runtime              │  │  [Operator's monitoring & control │
│  (Agent Runtime)               │  │   dashboard]                     │
│                                │  │                                  │
│  ┌──────────┐ ┌─────────────┐ │  │  ┌──────────┐  ┌──────────┐     │
│  │ System    │ │ Model       │ │  │  │ macOS App│  │ CLI      │     │
│  │ Prompt    │ │ Selection / │ │  │  │(Menu Bar)│  │Terminal  │     │
│  │ Builder   │ │ Failover    │ │  │  └──────────┘  └──────────┘     │
│  └──────────┘ └─────────────┘ │  │  ┌──────────┐  ┌──────────┐     │
│  ┌──────────┐ ┌─────────────┐ │  │  │  iOS App │  │ Android  │     │
│  │ Streaming │ │ Context     │ │  │  │  (Node)  │  │App(Node) │     │
│  │ Processing│ │ Window Mgmt │ │  │  └──────────┘  └──────────┘     │
│  └──────────┘ └─────────────┘ │  │  ┌──────────┐  ┌──────────┐     │
│           │                    │  │  │ WebChat  │  │ Control  │     │
│           │ Tool invocation    │  │  │  (Web)   │  │ UI(Panel)│     │
│           ▼                    │  │  └──────────┘  └──────────┘     │
│  ┌────────────────────────┐   │  │                                  │
│  │    Tool System (Tools)  │   │  │  Responsibilities:              │
│  │                        │   │  │  · Monitor Agent execution live  │
│  │ Bash  Browser  Canvas  │   │  │  · Approve dangerous exec       │
│  │ Cron  Nodes   Sessions │   │  │  · Provide device capabilities  │
│  └────────────────────────┘   │  │  · View/manage sessions, config │
│           │                    │  │                                  │
│           │ Tool results       │  └──────────────────────────────────┘
│           ▼                    │
│  Reply flows back to Gateway   │
│  → Sent to user via channel    │
└────────────────────────────────┘
```

This architecture has several noteworthy characteristics:

**Channels Embedded in Gateway Process**: Channels are not separate services—they are plugins/adapters embedded within the Gateway process. When Gateway starts, it calls `startChannels()` to initialize all configured channels. Communication between channels and Gateway is via **in-process function calls**, not HTTP or WebSocket network communication. For example, the Telegram channel uses the grammY library to pull messages from Telegram servers via HTTP long polling, then directly calls Gateway's auto-reply pipeline within the same process.

**Single Control Plane**: Gateway is the hub of the entire system. All message channels are embedded within it, and client applications and node devices connect to Gateway via WebSocket. Gateway coordinates everything—routing messages, managing sessions, scheduling Agents, and distributing events. This centralized design simplifies state management and consistency guarantees.

**Clients ≠ Message Channels**: This is an easily confused concept. Message Channels are the message entry points for **end users**—social platforms like WhatsApp, Telegram, etc. Clients are the monitoring and control dashboard for **operators** (i.e., the person who deploys/manages OpenClaw)—macOS App, CLI, Web UI, mobile Nodes, etc. Clients connect to Gateway via the WebSocket protocol, primarily used for: real-time monitoring of Agent execution status, approving dangerous command execution requests (exec approval), providing device capabilities (camera, screen recording, location, etc.), and managing sessions and configuration. In simple message Q\&A flows (e.g., user sends a message on Telegram, Agent replies), clients are completely uninvolved.

**Separation of Concerns**: Channels are only responsible for message transmission and format conversion, containing no business logic. The Agent runtime focuses solely on AI inference and tool invocation, regardless of which channel the message came from. Gateway acts as a coordinator in the middle—this is the classic Mediator Pattern.

**Tools as Capabilities**: Agent capabilities are not hardcoded but extended through registerable tools. Bash execution, browser control, Canvas rendering, Cron scheduling, device node operations—each capability is a tool that the Agent can invoke as needed.

## 1.2.2 Overview of Key Subsystems

Let's understand the responsibilities of each core subsystem more concretely:

### Gateway (Control Plane)

Gateway is the heart of OpenClaw. It's a long-running process listening on port `127.0.0.1:18789` (by default), with primary responsibilities including:

* **WebSocket Server**: Maintains connections with all clients and nodes
* **HTTP Server**: Provides OpenAI-compatible API, control panel UI, etc.
* **Channel Management**: Initiates and maintains connections to all message channels
* **Session Management**: Creates, maintains, resets, and persists session state
* **Message Routing**: Routes inbound messages to the correct Agent and session
* **Event Distribution**: Broadcasts Agent events and state changes to all connected clients
* **Cron Scheduling**: Manages scheduled tasks
* **Configuration Management**: Loads, validates, and hot-reloads configuration

Corresponding source directory: `src/gateway/` (128 files)

### Pi Agent Runtime (AI Agent Runtime)

The Agent runtime is responsible for executing the AI inference loop. When Gateway receives a message that needs AI processing, it calls the Agent runtime to handle it. Key functions:

* **Agent Loop**: Receive message → Assemble context → Call LLM → Execute tools → Stream reply → Persist
* **Model Selection and Failover**: Supports multiple models and providers with automatic switching
* **System Prompt Construction**: Assembles system prompts from workspace files, skills, and configuration
* **Tool Management**: Registers, schedules, and executes tools available to the Agent
* **Streaming**: Streams LLM output to clients
* **Context Compaction**: Automatically compacts context when conversations become too long

Corresponding source directory: `src/agents/` (308 files—the largest directory in the entire project)

### Channels (Channel System)

The channel system handles integration with external messaging platforms. Each channel is an adapter that converts platform-specific APIs into OpenClaw's internal message format.

* **Core Channels**: WhatsApp, Telegram, Discord, Slack, Signal, iMessage, WebChat
* **Extension Channels**: Teams, Matrix, Google Chat, Nostr, Twitch, etc. (31 extensions)
* **Channel Infrastructure**: Whitelists, mention gating, command gating, typing indicators, etc.

Corresponding source directory: `src/channels/` (31 files) + `src/whatsapp/`, `src/telegram/`, etc. + `extensions/`

### Tools (Tool System)

The tool system provides the Agent with capabilities to interact with the external world:

* **Bash**: Execute shell commands on the host or in a sandbox
* **Browser**: Control Chrome browser via Playwright/CDP
* **Canvas/A2UI**: Push HTML to a visual canvas
* **Cron**: Manage scheduled tasks
* **Nodes**: Invoke device node capabilities (camera, screen recording, location, etc.)
* **Sessions**: Cross-session communication

Corresponding source directory: `src/agents/tools/`, `src/browser/`, `src/canvas-host/`, `src/cron/`, `src/node-host/`

### Memory (Memory System)

The memory system allows the Agent to "remember" previous information:

* **File Memory**: Persistent memory based on Markdown files
* **Vector Search**: Semantic similarity search using embedding vectors
* **Hybrid Search**: Combines BM25 full-text search with vector search

Corresponding source directory: `src/memory/` (43 files)

### Skills (Skill System)

The skill system allows extending Agent capabilities through Markdown files:

* **Built-in Skills**: 52 pre-installed skills (GitHub, Slack, weather, coding agent, etc.)
* **Managed Skills**: Installed through the ClawHub registry
* **Workspace Skills**: User-defined in the workspace directory

Corresponding source directory: `src/agents/skills.ts`, `skills/` (52 subdirectories)

## 1.2.3 Data Flow Panorama: The Complete Lifecycle of a Message from User to AI Reply

To understand the architecture more intuitively, let's trace the complete lifecycle of a message. Suppose a user sends a message on Telegram: "Check tomorrow's weather for me, save the weather data to a local file, and post a weather tweet on Twitter." This is a complex scenario involving multiple chained tool invocations:

```
1. User sends message on Telegram
   │  "Check tomorrow's weather, save the data to a local file,
   │   and post a weather tweet on Twitter"
   ▼
2. Telegram channel (embedded in Gateway process) receives message
   │  grammY library fetches updates from Telegram API via HTTP long polling
   │  src/telegram/monitor.ts → run(bot) starts long polling loop
   ▼
3. Auto-reply system receives message (in-process function call)
   │  src/telegram/auto-reply.ts → Determine if processing is needed
   │  - Check whitelist (is sender in allowFrom)
   │  - Check DM policy (pairing / open)
   │  - Convert media attachments
   ▼
4. Message normalized to internal format
   │  src/channels/ → Sender identity, chat type, session label
   ▼
5. Gateway routes message
   │  src/routing/resolve-route.ts → Determine target Agent
   │  src/routing/session-key.ts → Generate session key (e.g., agent:main:main)
   ▼
6. Gateway initiates Agent RPC call
   │  src/gateway/server-chat.ts → agentCommand()
   │  - Parse model + thinking level
   │  - Load skill snapshot
   ▼
7. Pi Agent runtime takes over
   │  src/agents/pi-embedded-runner.ts → runEmbeddedPiAgent()
   │  - Queue serialization (ensure only one run per session at a time)
   │  - Parse Auth Profile
   │  - Construct system prompt
   │  - Load session history
   ▼
8. Call LLM (e.g., Anthropic Claude)
   │  pi-agent-core → Send HTTP request to model API
   │  - Stream receive tokens
   ▼
9. LLM decides to execute multiple tool calls in sequence:
   │
   ├─ 9a. Tool call 1: Query weather
   │  │  src/agents/pi-tools.ts → Tool scheduling
   │  │  src/agents/bash-tools.exec.ts → Execute bash command
   │  │  e.g.: curl wttr.in/Beijing?format=j1
   │  │  → Returns weather JSON data
   │  ▼
   ├─ 9b. Tool call 2: Save to local file
   │  │  LLM generates formatted text from weather data
   │  │  src/agents/bash-tools.exec.ts → Execute bash command
   │  │  e.g.: echo "2026-02-26 Beijing weather: Sunny 12°C" > ~/weather.txt
   │  │  → File write successful
   │  ▼
   └─ 9c. Tool call 3: Post tweet
      │  LLM invokes Twitter-related skill/tool
      │  src/agents/bash-tools.exec.ts → Execute API call
      │  → Tweet posted successfully
      ▼
10. All tool results returned to LLM
    │  LLM generates final reply based on results from all three tool calls
    ▼
11. Streaming processing
    │  src/agents/pi-embedded-subscribe.ts → Event bridging
    │  - assistant text stream → chunking
    │  - tool events → tool summary
    ▼
12. Gateway processes reply
    │  - Broadcasts events to connected WebSocket clients (for monitoring)
    │  - Routes final reply back to original channel
    ▼
13. Reply sent back via Telegram channel (in-process function call)
    │  src/telegram/outbound.ts → Send message
    │  - Markdown formatting
    │  - Chunking (Telegram has 4096 character message limit)
    │  - Sent to Telegram server via Telegram Bot API (HTTP)
    ▼
14. User sees reply on Telegram:
    "Done!
     Tomorrow Beijing weather: Sunny, high 12°C, low 3°C
     Weather data saved to ~/weather.txt
     Tweet posted: 'Beautiful sunny day in Beijing tomorrow, 12°C!'"
```

This data flow covers all of OpenClaw's core subsystems and demonstrates the Agent's ability to chain multiple tool invocations. In subsequent chapters, we'll dive deep into the source code implementation of each step.

It's worth noting that there are several key design decisions throughout the process:

* **Steps 2-3**: Communication between channels and Gateway is in-process. The Telegram channel fetches messages from external Telegram servers via HTTP long polling, but within OpenClaw, channels pass messages to Gateway through direct function calls with no additional network overhead.
* **Steps 6-7**: Agent invocation is asynchronous. Gateway first returns a `runId`, then pushes results through the event stream. This allows long-running tasks to not block Gateway.
* **Step 7**: Queue serialization ensures conversation history consistency for each session—concurrent messages won't cause context confusion.
* **Steps 9a-9c**: The Agent autonomously decides the order and method of tool invocations. After analyzing the user's request, the LLM identifies three independent tool calls needed and executes them sequentially. Each tool call's result is added to the context for subsequent tool calls to reference.
* **Steps 11-12**: Streaming is not simply sending token-by-token, but is processed through chunking before being sent to channels. The reply flows back to Gateway, then is sent back to the user through the original channel—not directly to clients. Clients (like the macOS App) simply receive event broadcasts via WebSocket for monitoring display.

***

By now, you have a panoramic understanding of OpenClaw's architecture. Next, let's look at the technology stack that supports this architecture.
