返回

04. OpenClaw Gateway 核心概念解析

深入理解 OpenClaw Gateway 的核心架構。本文詳細解析 Session 工作階段模型、Message Router 訊息路由、Tool Registry 工具註冊、Skills 技能系統、WebSocket 協定等關鍵概念,幫助開發者掌握進階設定和故障排查能力。

適用於 OpenClaw v2026.2 | 本文適合已完成基礎設定,想深入理解架構的使用者。建議先完成前 3 篇教學。

TL;DR: Gateway 是 OpenClaw 的核心控制平面。Session 是對話上下文容器(main/channel/group),Message Router 決定訊息路由,Tool Registry 管理工具權限,Skills 是預打包的能力擴充。WebSocket 端點 ws://127.0.0.1:18789/ws,常用命令 openclaw gateway/doctor/config。理解這些概念是進階設定的基礎。

架構概覽

整體架構

flowchart TB
    subgraph Clients["用戶端層"]
        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 層"]
        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 層"]
        PI[Pi Agent]
        PROMPT[Prompt Engine]
        TOOLS[Tool Executor]
        SKILLS[Skills Manager]
    end
    
    subgraph External["外部服務"]
        FS[檔案系統]
        BR[瀏覽器]
        API[API 服務]
        DB[資料庫]
        CAL[Cron 排程]
    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

元件職責

元件 職責 關鍵能力
WebSocket Server 用戶端連線管理 連線維護、心跳偵測、訊息收發
HTTP Server REST API 和靜態資源 Web UI、健康檢查、設定介面
Message Router 訊息路由分發 頻道識別、工作階段映射、訊息轉發
Session Manager 工作階段生命週期管理 建立、恢復、壓縮、清理
Tool Registry 工具註冊與呼叫 工具發現、權限控制、執行沙箱
Event Manager 事件分發與訂閱 Webhook、Cron、內部事件
Config Store 設定持久化 熱更新、版本管理、備份還原

資料流

sequenceDiagram
    participant U as 使用者
    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: 發送訊息
    C->>WS: 推送訊息
    WS->>MR: 路由請求
    MR->>SM: 尋找/建立工作階段
    SM-->>MR: 回傳工作階段
    MR->>A: 投遞訊息
    A->>A: 處理訊息
    A->>T: 呼叫工具(可選)
    T-->>A: 回傳結果
    A-->>MR: 產生回應
    MR->>WS: 發送回應
    WS->>C: 推送回應
    C-->>U: 顯示訊息

Session 工作階段模型

Session 是什麼?

Session 是 OpenClaw 中最核心的概念之一。每個 Session 代表一個獨立的對話上下文,包含:

組成部分 說明
訊息歷史 完整的對話記錄
上下文狀態 當前任務、暫時變數
設定 模型、思考級別、沙箱設定
中繼資料 建立時間、Token 統計、關聯頻道

Session 類型

{
  "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"
    }
  }
}
類型 Session ID 格式 說明
main main 預設主工作階段,CLI 和 WebChat 使用
channel {channel}:user:{senderId} 私聊工作階段,按頻道和使用者隔離
group {channel}:group:{groupId} 群組工作階段,按群組隔離

Session 生命週期

stateDiagram-v2
    [*] --> Created: 訊息到達
    Created --> Active: 首次回應
    Active --> Active: 訊息互動
    Active --> Idle: 無活動
    Idle --> Active: 新訊息
    Idle --> Compacted: 自動壓縮
    Compacted --> Active: 繼續對話
    Active --> Reset: /reset 命令
    Reset --> Created: 重新開始
    Active --> Pruned: 工作階段清理
    Idle --> Pruned: 逾時清理
    Pruned --> [*]

Session 命令

在聊天中發送以下命令管理工作階段:

命令 功能 範例
/status 查看工作階段狀態 顯示模型、Token、成本
/new/reset 重設工作階段 清空歷史,開始新對話
/compact 壓縮上下文 摘要歷史,釋放 Token
/think <level> 設定思考級別 /think high
/verbose on/off 開關詳細模式 顯示/隱藏工具呼叫
/usage off/tokens/full 使用量顯示 /usage full

Session 設定

{
  "sessionPruning": {
    "enabled": true,
    "maxAge": 86400000,
    "maxSize": 100,
    "pruneOnStartup": true
  },
  "sessionCompression": {
    "enabled": true,
    "threshold": 50000,
    "targetRatio": 0.3
  }
}
設定項 說明 預設值
maxAge 工作階段最大存活時間(毫秒) 24 小時
maxSize 最大訊息數量 100 條
threshold 壓縮閾值(Token) 50000
targetRatio 壓縮目標比例 30%

Message Router 訊息路由

路由規則

Message Router 負責將收到的訊息路由到正確的 Session:

flowchart TB
    MSG[訊息到達] --> CH{頻道類型?}
    CH -->|私聊| DM[擷取發送者 ID]
    CH -->|群聊| GRP[擷取群組 ID]
    CH -->|WebChat/CLI| MAIN[使用 main 工作階段]
    
    DM --> SID[Session: channel:user:id]
    GRP --> GID[Session: channel:group:id]
    
    SID --> EXISTS{工作階段存在?}
    GID --> EXISTS
    
    EXISTS -->|是| LOAD[載入工作階段]
    EXISTS -->|否| CREATE[建立新工作階段]
    
    CREATE --> LOAD
    LOAD --> AGENT[投遞給 Agent]

路由設定

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

群組啟用策略

模式 說明 適用場景
mention 需要 @提及才回應 活躍群組,減少干擾
always 回應所有訊息 專用工作群
keyword 包含關鍵字時回應 特定話題群
{
  "channels": {
    "telegram": {
      "groups": {
        "*": {
          "requireMention": true
        },
        "-100WORKGROUP": {
          "requireMention": false,
          "activationMode": "always"
        }
      }
    }
  }
}

Tool Registry 工具註冊

內建工具

OpenClaw 內建了豐富的工具:

工具類別 工具名稱 功能
檔案操作 read 讀取檔案
write 寫入檔案
edit 編輯檔案
命令執行 bash 執行 Shell 命令
process 管理程序
瀏覽器 browser 控制瀏覽器
搜尋 web_search 網頁搜尋
節點 camera 攝影機操作
screen_record 螢幕錄製
notify 發送通知
工作階段 sessions_list 列出工作階段
sessions_history 工作階段歷史
sessions_send 跨工作階段訊息
畫布 canvas 畫布操作

工具權限控制

{
  "agents": {
    "defaults": {
      "sandbox": {
        "mode": "off",
        "allowlist": ["read", "write", "bash", "web_search"],
        "denylist": []
      }
    }
  }
}
沙箱模式 說明
off 所有工具可用(僅限 main 工作階段)
non-main 非 main 工作階段啟用沙箱
always 所有工作階段啟用沙箱

沙箱設定詳解

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

Skills 技能系統

Skills 架構

flowchart LR
    subgraph Skills["Skills 目錄"]
        S1[gmail/SKILL.md]
        S2[calendar/SKILL.md]
        S3[home-assistant/SKILL.md]
    end
    
    subgraph Manager["Skills Manager"]
        DISC[發現]
        LOAD[載入]
        EXEC[執行]
    end
    
    subgraph Agent["Agent"]
        PROMPT[注入 Prompt]
        TOOLS[註冊 Tools]
        RES[回傳結果]
    end
    
    Skills --> DISC
    DISC --> LOAD
    LOAD --> PROMPT
    LOAD --> TOOLS
    PROMPT --> Agent
    TOOLS --> Agent
    Agent --> EXEC
    EXEC --> RES

Skills 目錄結構

~/.openclaw/workspace/skills/
├── gmail/
│   ├── SKILL.md          # 技能定義
│   ├── package.json      # 相依套件(可選)
│   └── src/
│       └── index.js      # 實作(可選)
├── calendar/
│   └── SKILL.md
└── my-custom-skill/
    └── SKILL.md

SKILL.md 結構

# 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 安裝方式

# 從 ClawHub 安裝
openclaw skill install gmail

# 從 GitHub 安裝
openclaw skill install github:user/repo/skill-name

# 手動安裝
git clone https://github.com/user/skill-repo.git ~/.openclaw/workspace/skills/skill-name

Skills 設定

{
  "skills": {
    "bundled": true,
    "managed": true,
    "workspace": true,
    "installGating": true
  }
}
設定項 說明
bundled 啟用內建技能
managed 啟用 ClawHub 託管技能
workspace 啟用本地工作區技能
installGating 安裝前需確認

WebSocket 協定

連線端點

ws://127.0.0.1:18789/ws

訊息格式

{
  "type": "message_type",
  "id": "unique_message_id",
  "data": {
    // 訊息內容
  }
}

用戶端訊息類型

類型 說明 範例
agent.send 發送訊息 與 Agent 對話
session.list 列出工作階段 管理工作階段
session.get 取得工作階段詳情 查看工作階段
session.patch 修改工作階段設定 變更模型
config.get 取得設定 讀取設定
config.set 設定 更新設定

伺服器端訊息類型

類型 說明
agent.response Agent 回應
agent.thinking 思考過程(串流)
tool.invoked 工具呼叫
tool.result 工具結果
session.created 工作階段建立
session.reset 工作階段重設
error 錯誤訊息

範例:發送訊息

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

// 發送訊息
ws.send(JSON.stringify({
  type: 'agent.send',
  id: 'msg-001',
  data: {
    session: 'main',
    message: '你好,請介紹一下你自己'
  }
}));

// 接收回應
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(msg);
  
  // 輸出範例:
  // {
  //   type: 'agent.response',
  //   id: 'msg-001',
  //   data: {
  //     content: '你好!我是你的 OpenClaw 助手...',
  //     session: 'main'
  //   }
  // }
};

Event System 事件系統

內建事件

事件 觸發時機
message.received 收到使用者訊息
message.sent 發送回覆訊息
session.created 新工作階段建立
session.reset 工作階段重設
tool.invoked 工具被呼叫
tool.completed 工具執行完成
agent.thinking Agent 思考中
error.occurred 發生錯誤

Webhook 設定

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

Webhook 酬載

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

Cron 定時任務

設定範例

{
  "cron": [
    {
      "id": "daily-briefing",
      "schedule": "0 9 * * *",
      "session": "main",
      "message": "請給我今天的行程安排",
      "enabled": true
    },
    {
      "id": "weekly-summary",
      "schedule": "0 18 * * 5",
      "session": "main",
      "message": "產生本週工作總結",
      "enabled": true
    }
  ]
}

Cron 運算式

┌───────────── 分鐘 (0 - 59)
│ ┌───────────── 小時 (0 - 23)
│ │ ┌───────────── 日期 (1 - 31)
│ │ │ ┌───────────── 月份 (1 - 12)
│ │ │ │ ┌───────────── 星期幾 (0 - 6, 0 = 週日)
│ │ │ │ │
* * * * *

常用範例

運算式 說明
0 9 * * * 每天 9:00
0 18 * * 1-5 工作日 18:00
*/30 * * * * 每 30 分鐘
0 0 1 * * 每月 1 日 0:00

設定層級與優先順序

優先順序

CLI 參數 > 環境變數 > 設定檔 > 預設值

設定來源

來源 位置 優先順序
CLI 參數 命令列參數 最高
環境變數 OPENCLAW_*
設定檔 ~/.openclaw/openclaw.json
預設值 程式碼內建 最低

設定合併範例

// ~/.openclaw/openclaw.json
{
  "agent": {
    "model": "anthropic/claude-opus-4-6"
  }
}
# 環境變數覆蓋
export OPENCLAW_AGENT_MODEL="anthropic/claude-sonnet-4"

# CLI 參數覆蓋(最高優先順序)
openclaw gateway --model "anthropic/claude-opus-4"

設定熱更新

# 更新設定(不重新啟動)
openclaw config set agent.model "anthropic/claude-sonnet-4"

# 重新載入設定檔
openclaw config reload

# 驗證設定
openclaw config get agent.model

常用命令速查

Gateway 管理

# 啟動 Gateway
openclaw gateway

# 指定連接埠
openclaw gateway --port 18790

# 背景執行
openclaw gateway --daemon

# 詳細日誌
openclaw gateway --verbose

# 健康檢查
openclaw health

工作階段管理

# 列出所有工作階段
openclaw session list

# 查看工作階段詳情
openclaw session show main
openclaw session show telegram:user:123456789

# 重設工作階段
openclaw session reset main

# 刪除工作階段
openclaw session delete telegram:user:123456789

設定管理

# 查看設定
openclaw config get agent.model
openclaw config get channels.telegram.botToken

# 設定
openclaw config set agent.thinkingLevel high

# 列出所有設定
openclaw config list

# 驗證設定
openclaw config validate

診斷工具

# 完整診斷
openclaw doctor

# 檢查特定項
openclaw doctor --check gateway
openclaw doctor --check config
openclaw doctor --check channels

# 查看日誌
openclaw logs
openclaw logs --follow
openclaw logs --level error

故障排查

Gateway 無法啟動

# 檢查連接埠佔用
lsof -i :18789
netstat -tlnp | grep 18789

# 檢查設定語法
openclaw config validate

# 查看詳細錯誤
openclaw gateway --verbose 2>&1 | tee gateway.log

工作階段遺失

# 檢查工作階段目錄
ls -la ~/.openclaw/sessions/

# 檢查清理設定
openclaw config get sessionPruning

# 停用自動清理
openclaw config set sessionPruning.enabled false

工具呼叫失敗

# 檢查沙箱設定
openclaw config get agents.defaults.sandbox

# 暫時停用沙箱
openclaw config set agents.defaults.sandbox.mode off

# 查看工具日誌
openclaw logs --filter tool

WebSocket 連線失敗

# 檢查 Gateway 狀態
curl http://127.0.0.1:18789/health

# 檢查 WebSocket 端點
wscat -c ws://127.0.0.1:18789/ws

# 檢查防火牆
sudo ufw status
sudo iptables -L -n | grep 18789

小結

理解 Gateway 核心概念是掌握 OpenClaw 的關鍵:

  • Session:對話上下文的容器,支援類型隔離
  • Message Router:訊息路由的核心,決定訊息去向
  • Tool Registry:工具註冊中心,控制 Agent 能力
  • Skills:技能擴充系統,快速增強功能
  • WebSocket:即時通訊協定,支援自訂用戶端
  • Event System:事件分發機制,支援 Webhook 和 Cron

這些概念將在後續文章中反覆出現,深入理解它們將幫助你更好地設定和使用 OpenClaw。


本篇小結

  • 掌握了 Gateway 整體架構和元件職責
  • 理解了 Session 工作階段模型和生命週期
  • 學習了訊息路由和群組啟用策略
  • 了解了工具權限和沙箱設定
  • 掌握了 WebSocket 協定和事件系統

更新記錄

  • 2026-02-26:初版發布,基於 OpenClaw v2026.2

系列導航