Back

04. OpenClaw Gateway Core Concepts Explained

Deep dive into OpenClaw Gateway's core architecture. This article explains Session model, Message Router, Tool Registry, Skills system, WebSocket protocol, and other key concepts to help developers master advanced configuration and troubleshooting.


For OpenClaw v2026.2 | This article is for users who have completed basic setup and want to understand the architecture in depth. We recommend completing the first 3 tutorials first.

TL;DR: Gateway is OpenClaw’s core control plane. Session is the conversation context container (main/channel/group), Message Router decides message routing, Tool Registry manages tool permissions, Skills are pre-packaged capability extensions. WebSocket endpoint: ws://127.0.0.1:18789/ws, common commands: openclaw gateway/doctor/config. Understanding these concepts is the foundation for advanced configuration.

Architecture Overview

Overall Architecture

flowchart TB
    subgraph Clients["Client Layer"]
        WA[WhatsApp]
        TG[Telegram]
        DC[Discord]
        SL[Slack]
        WC[WebChat]
        CLI[CLI]
        MAC[macOS App]
        IOS[iOS Node]
        AND[Android Node]
    end
    
    subgraph Gateway["Gateway Layer"]
        WS[WebSocket Server]
        HTTP[HTTP Server]
        MR[Message Router]
        SM[Session Manager]
        TR[Tool Registry]
        EM[Event Manager]
        CFG[Config Store]
    end
    
    subgraph Agent["Agent Layer"]
        PI[Pi Agent]
        PROMPT[Prompt Engine]
        TOOLS[Tool Executor]
        SKILLS[Skills Manager]
    end
    
    subgraph External["External Services"]
        FS[File System]
        BR[Browser]
        API[API Services]
        DB[Database]
        CAL[Cron Scheduler]
    end
    
    Clients --> WS
    Clients --> HTTP
    WS --> MR
    HTTP --> MR
    MR --> SM
    SM --> PI
    PI --> PROMPT
    PI --> TOOLS
    PI --> SKILLS
    TOOLS --> TR
    TR --> External
    EM --> MR
    CFG --> SM
    CFG --> TR

Component Responsibilities

Component Responsibility Key Capabilities
WebSocket Server Client connection management Connection maintenance, heartbeat detection, message send/receive
HTTP Server REST API and static resources Web UI, health check, config interface
Message Router Message routing and dispatch Channel identification, session mapping, message forwarding
Session Manager Session lifecycle management Create, restore, compress, cleanup
Tool Registry Tool registration and invocation Tool discovery, permission control, execution sandbox
Event Manager Event dispatch and subscription Webhook, Cron, internal events
Config Store Configuration persistence Hot reload, version management, backup/restore

Data Flow

sequenceDiagram
    participant U as User
    participant C as Channel
    participant WS as WebSocket
    participant MR as Router
    participant SM as Session
    participant A as Agent
    participant T as Tools
    
    U->>C: Send message
    C->>WS: Push message
    WS->>MR: Route request
    MR->>SM: Find/create session
    SM-->>MR: Return session
    MR->>A: Deliver message
    A->>A: Process message
    A->>T: Invoke tool (optional)
    T-->>A: Return result
    A-->>MR: Generate response
    MR->>WS: Send response
    WS->>C: Push response
    C-->>U: Display message

Session Model

What is a Session?

Session is one of the most core concepts in OpenClaw. Each Session represents an independent conversation context, containing:

Component Description
Message History Complete conversation records
Context State Current task, temporary variables
Configuration Model, thinking level, sandbox settings
Metadata Creation time, token statistics, associated channel

Session Types

{
  "sessions": {
    "main": {
      "type": "main",
      "model": "anthropic/claude-opus-4-6",
      "thinkingLevel": "high",
      "channel": null,
      "created": "2026-02-26T10:00:00Z"
    },
    "telegram:user:123456789": {
      "type": "channel",
      "model": "anthropic/claude-opus-4-6",
      "thinkingLevel": "normal",
      "channel": "telegram",
      "sender": "123456789",
      "created": "2026-02-26T10:05:00Z"
    },
    "telegram:group:-100123456789": {
      "type": "group",
      "model": "anthropic/claude-sonnet-4",
      "thinkingLevel": "minimal",
      "channel": "telegram",
      "groupId": "-100123456789",
      "created": "2026-02-26T10:10:00Z"
    }
  }
}
Type Session ID Format Description
main main Default main session, used by CLI and WebChat
channel {channel}:user:{senderId} Private chat session, isolated by channel and user
group {channel}:group:{groupId} Group session, isolated by group

Session Lifecycle

stateDiagram-v2
    [*] --> Created: Message arrives
    Created --> Active: First response
    Active --> Active: Message interaction
    Active --> Idle: No activity
    Idle --> Active: New message
    Idle --> Compacted: Auto compress
    Compacted --> Active: Continue conversation
    Active --> Reset: /reset command
    Reset --> Created: Start over
    Active --> Pruned: Session cleanup
    Idle --> Pruned: Timeout cleanup
    Pruned --> [*]

Session Commands

Send the following commands in chat to manage sessions:

Command Function Example
/status View session status Display model, tokens, cost
/new or /reset Reset session Clear history, start new conversation
/compact Compress context Summarize history, free tokens
/think <level> Set thinking level /think high
/verbose on/off Toggle verbose mode Show/hide tool invocations
/usage off/tokens/full Usage display /usage full

Session Configuration

{
  "sessionPruning": {
    "enabled": true,
    "maxAge": 86400000,
    "maxSize": 100,
    "pruneOnStartup": true
  },
  "sessionCompression": {
    "enabled": true,
    "threshold": 50000,
    "targetRatio": 0.3
  }
}
Config Description Default
maxAge Max session lifetime (milliseconds) 24 hours
maxSize Max message count 100
threshold Compression threshold (tokens) 50000
targetRatio Compression target ratio 30%

Message Router

Routing Rules

Message Router is responsible for routing incoming messages to the correct Session:

flowchart TB
    MSG[Message arrives] --> CH{Channel type?}
    CH -->|Private chat| DM[Extract sender ID]
    CH -->|Group chat| GRP[Extract group ID]
    CH -->|WebChat/CLI| MAIN[Use main session]
    
    DM --> SID[Session: channel:user:id]
    GRP --> GID[Session: channel:group:id]
    
    SID --> EXISTS{Session exists?}
    GID --> EXISTS
    
    EXISTS -->|Yes| LOAD[Load session]
    EXISTS -->|No| CREATE[Create new session]
    
    CREATE --> LOAD
    LOAD --> AGENT[Deliver to Agent]

Routing Configuration

{
  "messageRouting": {
    "defaultSession": "main",
    "channelMapping": {
      "telegram": {
        "userPrefix": "telegram:user",
        "groupPrefix": "telegram:group"
      },
      "whatsapp": {
        "userPrefix": "whatsapp:user",
        "groupPrefix": "whatsapp:group"
      }
    },
    "groupActivation": {
      "mode": "mention",
      "mentionPatterns": ["@bot", "/bot"]
    }
  }
}

Group Activation Strategies

Mode Description Use Case
mention Respond only when @mentioned Active groups, reduce noise
always Respond to all messages Dedicated work groups
keyword Respond when keywords present Topic-specific groups
{
  "channels": {
    "telegram": {
      "groups": {
        "*": {
          "requireMention": true
        },
        "-100WORKGROUP": {
          "requireMention": false,
          "activationMode": "always"
        }
      }
    }
  }
}

Tool Registry

Built-in Tools

OpenClaw includes a rich set of built-in tools:

Tool Category Tool Name Function
File Operations read Read file
write Write file
edit Edit file
Command Execution bash Execute shell command
process Process management
Browser browser Browser control
Search web_search Web search
Node camera Camera operations
screen_record Screen recording
notify Send notification
Session sessions_list List sessions
sessions_history Session history
sessions_send Cross-session messaging
Canvas canvas Canvas operations

Tool Permission Control

{
  "agents": {
    "defaults": {
      "sandbox": {
        "mode": "off",
        "allowlist": ["read", "write", "bash", "web_search"],
        "denylist": []
      }
    }
  }
}
Sandbox Mode Description
off All tools available (main session only)
non-main Sandbox enabled for non-main sessions
always Sandbox enabled for all sessions

Sandbox Configuration Details

{
  "agents": {
    "defaults": {
      "sandbox": {
        "mode": "non-main",
        "allowlist": [
          "read",
          "write",
          "edit",
          "bash",
          "web_search",
          "sessions_list",
          "sessions_history"
        ],
        "denylist": [
          "browser",
          "canvas",
          "camera",
          "screen_record"
        ]
      }
    }
  }
}

Skills System

Skills Architecture

flowchart LR
    subgraph Skills["Skills Directory"]
        S1[gmail/SKILL.md]
        S2[calendar/SKILL.md]
        S3[home-assistant/SKILL.md]
    end
    
    subgraph Manager["Skills Manager"]
        DISC[Discover]
        LOAD[Load]
        EXEC[Execute]
    end
    
    subgraph Agent["Agent"]
        PROMPT[Inject Prompt]
        TOOLS[Register Tools]
        RES[Return Result]
    end
    
    Skills --> DISC
    DISC --> LOAD
    LOAD --> PROMPT
    LOAD --> TOOLS
    PROMPT --> Agent
    TOOLS --> Agent
    Agent --> EXEC
    EXEC --> RES

Skills Directory Structure

~/.openclaw/workspace/skills/
├── gmail/
│   ├── SKILL.md          # Skill definition
│   ├── package.json      # Dependencies (optional)
│   └── src/
│       └── index.js      # Implementation (optional)
├── calendar/
│   └── SKILL.md
└── my-custom-skill/
    └── SKILL.md

SKILL.md Structure

# Gmail Skill

## Description
Send and read Gmail messages through OpenClaw.

## Triggers
- email
- gmail
- mail
- send email
- read email

## Instructions
When the user wants to send an email:
1. Ask for recipient, subject, and body
2. Use the gmail_send tool
3. Confirm the email was sent

When the user wants to check emails:
1. Use the gmail_list tool
2. Summarize the results

## Tools
- gmail_list: List recent emails
- gmail_send: Send an email
- gmail_read: Read a specific email

## Examples
User: "Check my email"
Action: Use gmail_list tool

User: "Send an email to [email protected]"
Action: Ask for subject and body, then use gmail_send

Skills Installation

# Install from ClawHub
openclaw skill install gmail

# Install from GitHub
openclaw skill install github:user/repo/skill-name

# Manual install
git clone https://github.com/user/skill-repo.git ~/.openclaw/workspace/skills/skill-name

Skills Configuration

{
  "skills": {
    "bundled": true,
    "managed": true,
    "workspace": true,
    "installGating": true
  }
}
Config Description
bundled Enable built-in skills
managed Enable ClawHub managed skills
workspace Enable local workspace skills
installGating Require confirmation before install

WebSocket Protocol

Connection Endpoint

ws://127.0.0.1:18789/ws

Message Format

{
  "type": "message_type",
  "id": "unique_message_id",
  "data": {
    // Message content
  }
}

Client Message Types

Type Description Example
agent.send Send message Chat with Agent
session.list List sessions Manage sessions
session.get Get session details View session
session.patch Modify session config Change model
config.get Get config Read settings
config.set Set config Update settings

Server Message Types

Type Description
agent.response Agent response
agent.thinking Thinking process (streaming)
tool.invoked Tool invocation
tool.result Tool result
session.created Session created
session.reset Session reset
error Error message

Example: Sending a Message

// Connect WebSocket
const ws = new WebSocket('ws://127.0.0.1:18789/ws');

// Send message
ws.send(JSON.stringify({
  type: 'agent.send',
  id: 'msg-001',
  data: {
    session: 'main',
    message: 'Hello, please introduce yourself'
  }
}));

// Receive response
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(msg);
  
  // Output example:
  // {
  //   type: 'agent.response',
  //   id: 'msg-001',
  //   data: {
  //     content: 'Hello! I am your OpenClaw assistant...',
  //     session: 'main'
  //   }
  // }
};

Event System

Built-in Events

Event Trigger
message.received User message received
message.sent Reply message sent
session.created New session created
session.reset Session reset
tool.invoked Tool invoked
tool.completed Tool execution completed
agent.thinking Agent thinking
error.occurred Error occurred

Webhook Configuration

{
  "webhooks": [
    {
      "url": "https://your-server.com/webhook/openclaw",
      "events": ["message.received", "tool.invoked"],
      "secret": "your_webhook_secret",
      "headers": {
        "X-Custom-Header": "value"
      }
    }
  ]
}

Webhook Payload

{
  "event": "message.received",
  "timestamp": "2026-02-26T10:30:00Z",
  "data": {
    "channel": "telegram",
    "sender": "123456789",
    "session": "telegram:user:123456789",
    "message": "Hello",
    "metadata": {
      "messageId": "msg_abc123",
      "timestamp": "2026-02-26T10:30:00Z"
    }
  },
  "signature": "sha256=..."
}

Cron Scheduled Tasks

Configuration Example

{
  "cron": [
    {
      "id": "daily-briefing",
      "schedule": "0 9 * * *",
      "session": "main",
      "message": "Please give me today's schedule",
      "enabled": true
    },
    {
      "id": "weekly-summary",
      "schedule": "0 18 * * 5",
      "session": "main",
      "message": "Generate this week's work summary",
      "enabled": true
    }
  ]
}

Cron Expression

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6, 0 = Sunday)
│ │ │ │ │
* * * * *

Common Examples

Expression Description
0 9 * * * Daily at 9:00
0 18 * * 1-5 Weekdays at 18:00
*/30 * * * * Every 30 minutes
0 0 1 * * 1st of month at 0:00

Configuration Hierarchy and Priority

Priority Order

CLI args > Environment variables > Config file > Defaults

Configuration Sources

Source Location Priority
CLI args Command line Highest
Environment variables OPENCLAW_* High
Config file ~/.openclaw/openclaw.json Medium
Defaults Built-in Lowest

Configuration Merge Example

// ~/.openclaw/openclaw.json
{
  "agent": {
    "model": "anthropic/claude-opus-4-6"
  }
}
# Environment variable override
export OPENCLAW_AGENT_MODEL="anthropic/claude-sonnet-4"

# CLI arg override (highest priority)
openclaw gateway --model "anthropic/claude-opus-4"

Config Hot Reload

# Update config (no restart)
openclaw config set agent.model "anthropic/claude-sonnet-4"

# Reload config file
openclaw config reload

# Validate config
openclaw config get agent.model

Command Quick Reference

Gateway Management

# Start Gateway
openclaw gateway

# Specify port
openclaw gateway --port 18790

# Run in background
openclaw gateway --daemon

# Verbose logging
openclaw gateway --verbose

# Health check
openclaw health

Session Management

# List all sessions
openclaw session list

# View session details
openclaw session show main
openclaw session show telegram:user:123456789

# Reset session
openclaw session reset main

# Delete session
openclaw session delete telegram:user:123456789

Config Management

# View config
openclaw config get agent.model
openclaw config get channels.telegram.botToken

# Set config
openclaw config set agent.thinkingLevel high

# List all config
openclaw config list

# Validate config
openclaw config validate

Diagnostic Tools

# Full diagnostic
openclaw doctor

# Check specific item
openclaw doctor --check gateway
openclaw doctor --check config
openclaw doctor --check channels

# View logs
openclaw logs
openclaw logs --follow
openclaw logs --level error

Troubleshooting

Gateway Won’t Start

# Check port usage
lsof -i :18789
netstat -tlnp | grep 18789

# Check config syntax
openclaw config validate

# View detailed errors
openclaw gateway --verbose 2>&1 | tee gateway.log

Session Lost

# Check session directory
ls -la ~/.openclaw/sessions/

# Check cleanup config
openclaw config get sessionPruning

# Disable auto cleanup
openclaw config set sessionPruning.enabled false

Tool Invocation Failed

# Check sandbox config
openclaw config get agents.defaults.sandbox

# Temporarily disable sandbox
openclaw config set agents.defaults.sandbox.mode off

# View tool logs
openclaw logs --filter tool

WebSocket Connection Failed

# Check Gateway status
curl http://127.0.0.1:18789/health

# Check WebSocket endpoint
wscat -c ws://127.0.0.1:18789/ws

# Check firewall
sudo ufw status
sudo iptables -L -n | grep 18789

Summary

Understanding Gateway core concepts is key to mastering OpenClaw:

  • Session: Conversation context container with type isolation
  • Message Router: Core of message routing, determines message destination
  • Tool Registry: Tool registration center, controls Agent capabilities
  • Skills: Capability extension system for quick feature enhancement
  • WebSocket: Real-time communication protocol, supports custom clients
  • Event System: Event dispatch mechanism, supports Webhook and Cron

These concepts will appear throughout subsequent articles. A deep understanding will help you configure and use OpenClaw more effectively.


Article Summary:

  • Mastered Gateway overall architecture and component responsibilities
  • Understood Session model and lifecycle
  • Learned message routing and group activation strategies
  • Explored tool permissions and sandbox configuration
  • Mastered WebSocket protocol and event system

Changelog:

  • 2026-02-26: Initial release, based on OpenClaw v2026.2

Series Navigation: