适用于 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"
}
}
}
}
}
内置工具
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
系列导航: