OpenClaw Gateway 命令和交互
适用版本: OpenClaw v3.0+ / Moltbot v2.0+
CLI 命令
一、Gateway 生命周期管理
启动 Gateway(前台运行)
openclaw gateway
openclaw gateway run
档详细阐述了 OpenClaw Gateway 的命令行接口(CLI)与 WebSocket API 的使用方法。内容包括 Gateway 的生命周期管理、健康诊断、配置变更、聊天消息收发、Agent 指令执行及会话控制。文档提供了完整的 CLI 命令参数说明、WebSocket 连接认证流程、聊天斜线命令列表以及 Node.js 和 Python 的 API 调用示例。此外还涵盖了系统事件类型、权限角色体系及设备配对机制,旨在帮助开发者高效集成自动化智能体工作流。
适用版本: OpenClaw v3.0+ / Moltbot v2.0+
openclaw gateway
openclaw gateway run
常用选项:
| 选项 | 说明 | 示例 |
|---|---|---|
--port <port> | WebSocket 端口(默认 18789) | openclaw gateway --port 19000 |
--bind <mode> | 绑定模式:loopback | lan |
--token <token> | Gateway 认证令牌 | openclaw gateway --token abc123xyz |
--password <password> | 密码认证模式 | openclaw gateway --password mypass |
--force | 强制杀死现有进程并重启 | openclaw gateway --force |
--dev | 开发模式(自动创建默认配置) | openclaw gateway --dev |
--reset | 重置配置、凭证、工作区(仅与 --dev 配合) | openclaw gateway --dev --reset |
--verbose | 详细日志输出 | openclaw gateway --verbose |
--allow-unconfigured | 允许未配置的启动 | openclaw gateway --allow-unconfigured |
--tailscale <mode> | Tailscale 暴露模式:off | serve |
--ws-log <style> | WebSocket 日志风格:auto | full |
# 安装为系统服务
openclaw gateway install --port 18789 --token mytoken123
# 启动服务
openclaw gateway start
# 停止服务
openclaw gateway stop
# 重启服务
openclaw gateway restart
# 卸载服务
openclaw gateway uninstall
# 检查服务状态
openclaw gateway status
# 详细状态检查(包括 RPC 探测)
openclaw gateway status --json
# 基本健康检查
openclaw gateway health
# 连接到远程 Gateway
openclaw gateway health --url ws://192.168.1.100:18789
# 带认证的健康检查
openclaw gateway health --url ws://192.168.1.100:18789 --token mytoken
# 使用密码认证
openclaw gateway health --url ws://192.168.1.100:18789 --password mypass
# 自定义超时(毫秒)
openclaw gateway health --timeout 5000
# 检查系统服务状态
openclaw gateway status
# 仅检查服务状态,跳过 RPC 探测
openclaw gateway status --no-probe
# 深度检查(包括系统级服务)
openclaw gateway status --deep
# JSON 输出(用于脚本)
openclaw gateway status --json
# 探测本地和远程 Gateway
openclaw gateway probe
# JSON 格式输出
openclaw gateway probe --json
# 通过 SSH 远程探测
openclaw gateway probe --ssh user@gateway-host
# 指定 SSH 私钥
openclaw gateway probe --ssh user@gateway-host:2222 --ssh-identity ~/.ssh/id_rsa
# 自动选择 LAN 上的第一个发现的 Gateway
openclaw gateway probe --ssh-auto
# 扫描局域网上的 Gateway
openclaw gateway discover
# 自定义超时(毫秒)
openclaw gateway discover --timeout 4000
# JSON 输出
openclaw gateway discover --json
# 提取 WebSocket URL 列表
openclaw gateway discover --json | jq '.beacons[].wsUrl'
发现的信息包括:
role: Gateway 角色提示gatewayPort: WebSocket 端口(通常 18789)sshPort: SSH 端口(默认 22)tailnetDns: Tailscale Magic DNS 主机名gatewayTls: TLS 是否启用gatewayTlsSha256: TLS 证书指纹# 调用 Gateway RPC 方法
openclaw gateway call <method> [--params <json>]
# 示例:获取当前状态
openclaw gateway call status
# 示例:查询配置(带哈希值)
openclaw gateway call config.get --params '{}'
# 示例:查看最近 60 秒的日志
openclaw gateway call logs.tail --params '{"sinceMs": 60000}'
# 示例:列出所有活动会话
openclaw gateway call sessions.list --params '{"filter": "active"}'
# 示例:获取 Agent 信息
openclaw gateway call agents.describe --params '{"id": "main"}'
# 自定义 Gateway URL
openclaw gateway call status --url ws://127.0.0.1:18789
# 带认证
openclaw gateway call status --url ws://127.0.0.1:18789 --token mytoken
# 自定义超时(毫秒)
openclaw gateway call status --timeout 10000
Gateway 通过 WebSocket 暴露超过 84+ RPC 方法。以下是分类整理:
Request:
{
"type": "req",
"id": "conn-001",
"method": "connect",
"params": {
"minProtocol": 3,
"maxProtocol": 3,
"client": { "id": "cli", "version": "1.2.3", "platform": "macos", "mode": "operator" },
"role": "operator",
"scopes": ["operator.read", "operator.write"],
"caps": [],
"commands": [],
"auth": { "token": "OPENCLAW_GATEWAY_TOKEN" },
"locale": "zh_CN",
"device": { "id": "device-fingerprint", "publicKey": "...", "signature": "...", "signedAt": 1737264000000, "nonce": "..." }
}
}
Response:
{
"type": "res",
"id": "conn-001",
"ok": true,
"payload": {
"type": "hello-ok",
"protocol": 3,
"auth": { "deviceToken": "jwt-token", "role": "operator", "scopes": ["operator.read", "operator.write"] },
"policy": { "tickIntervalMs": 15000, "maxMessageSize": 1048576, "connectionTimeout": 300000 }
}
}
openclaw gateway call device.token.rotate --params '{ "deviceId": "device-001", "scope": "operator" }'
openclaw gateway call device.token.revoke --params '{ "deviceId": "device-001", "token": "old-token" }'
openclaw gateway call status
响应字段:
running: Gateway 是否在线uptime: 运行时间(秒)version: Gateway 版本agents: 活动 Agent 列表connections: 当前连接数sessions: 会话统计openclaw gateway call health
响应字段:
status: 'healthy' | 'degraded' | 'unhealthy'components: 各组件的状态
gateway: 网关状态storage: 存储状态agents: Agent 运行时状态openclaw gateway call system.info
响应包括:
platform: macOS | Linux | Windowsarch: 架构(x64、arm64 等)memory: 可用内存storage: 磁盘空间openclaw gateway call config.get --params '{}'
响应:
{"hash":"sha256_of_config","raw":"yaml_config_content","agents":[...],"channels":{},"models":{}}
openclaw gateway call config.patch --params '{ "raw": "agents:\n defaults:\n workspace: ~/.openclaw/workspace", "baseHash": "previous_hash_from_config.get", "sessionKey": "agent:main:whatsapp:dm:+1234567890", "restartDelayMs": 1000 }'
openclaw gateway call config.apply --params '{ "raw": "entire_yaml_config", "baseHash": "previous_hash", "sessionKey": "agent:main:whatsapp:dm:+1234567890", "restartDelayMs": 2000 }'
openclaw gateway call chat.message --params '{ "channel": { "platform": "whatsapp", "id": "120363012345678-1234567890" }, "text": "用户消息内容", "attachments": [] }'
openclaw gateway call chat.history --params '{ "channelId": "120363012345678-1234567890", "limit": 50, "since": "2026-01-01T00:00:00Z" }'
openclaw gateway call chat.search --params '{ "query": "搜索关键词", "channelId": "optional_channel_id", "limit": 20 }'
openclaw gateway call agent.invoke --params '{ "agentId": "main", "tool": "shell.exec", "args": { "command": "ls -la ~" } }' --expect-final
流式响应:
{"type":"res","id":"invoke-001","stream":true,"chunk":0,"payload":{"status":"executing","progress":0.3}}
// ... 后续块 ...
{"type":"res","id":"invoke-001","stream":true,"chunk":5,"stream_done":true,"ok":true,"payload":{"status":"completed","result":"output_content"}}
openclaw gateway call agents.list
openclaw gateway call agents.describe --params '{ "id": "main" }'
响应:
id: Agent IDname: Agent 名称model: 使用的 LLM 模型workspace: 工作区路径skills: 可用技能列表capabilities: 能力列表openclaw gateway call agent.message --params '{ "agentId": "main", "text": "分析销售数据", "thinking": "high" }'
openclaw gateway call sessions.list --params '{ "filter": "active" }'
openclaw gateway call sessions.get --params '{ "sessionId": "agent:main:whatsapp:dm:+1234567890" }'
openclaw gateway call sessions.delete --params '{ "sessionId": "agent:main:whatsapp:dm:+1234567890" }'
openclaw gateway call skills.list
响应:
{"bundled":[{"id":"shell","name":"Shell Execution","description":"在本地运行 Shell 命令"},{"id":"files","name":"File Operations","description":"读写文件"}],"custom":[{"id":"wine-cellar","name":"Wine Cellar Manager","description":"管理葡萄酒收藏"}]}
openclaw gateway call skills.describe --params '{ "skillId": "shell" }'
openclaw gateway call skills.bins
用途:Node 用此检查是否允许执行某个命令
openclaw gateway call channels.list
可能的渠道:
whatsapptelegramdiscordslackimessageemailwebopenclaw gateway call channels.describe --params '{ "platform": "whatsapp" }'
openclaw gateway call channels.status --params '{ "platform": "whatsapp" }'
openclaw gateway call nodes.list
响应:
{"nodes":[{"id":"peekaboo-node","platform":"macos","capabilities":["screenshot","click","type"],"status":"online","lastSeen":"2026-01-30T10:30:00Z"},{"id":"ios-node","platform":"ios","capabilities":["camera","voice","canvas"],"status":"offline"}]}
openclaw gateway call nodes.describe --params '{ "nodeId": "peekaboo-node" }'
openclaw gateway call logs.tail --params '{ "sinceMs": 60000, "limit": 100 }'
openclaw gateway call logs.search --params '{ "query": "error", "level": "error|warn|info|debug", "since": "2026-01-01T00:00:00Z" }'
这些命令可在任何支持的聊天平台上使用(WhatsApp、Telegram 等)。
用户:/help
Agent: 显示可用命令列表和使用说明
用户:/status
Agent: 返回当前 Agent、模型、可用技能等信息
响应示例:
🤖 Agent 状态:
├─ ID: main
├─ 模型:claude-3.5-sonnet
├─ 工作区:~/.openclaw/workspaces/default
├─ 可用技能:shell, files, peekaboo, web-search (4)
└─ 内存使用:245 MB / 500 MB
用户:/agents
Agent: 列出所有可用的 Agent
用户:/agents use coding-agent
Agent: 切换到 "coding-agent"
用户:/skills
Agent: 列出所有加载的技能
用户:/skills search wine
Agent: 搜索名称包含 "wine" 的技能
用户:/config
Agent: 显示当前 Agent 的配置信息
用户:/config agents.defaults.model
Agent: 显示指定配置项的值
用户:/debug on
Agent: 启用详细日志和思考过程显示
用户:/debug off
Agent: 关闭调试模式
启用调试后,Agent 会显示:
用户:/memory status
Agent: 显示当前记忆使用情况
用户:/memory clear old
Agent: 清理 90 天前的旧记忆
用户:/memory export
Agent: 导出当前记忆为 JSON
用户:/subagents list
Agent: 列出所有活跃和已完成的子智能体
用户:/subagents stop <uuid>
Agent: 停止指定 UUID 的子智能体
用户:/subagents log <uuid>
Agent: 查看子智能体的完整对话历史
用户:/subagents info <uuid>
Agent: 获取子智能体的详细信息(模型、创建时间、token 使用量等)
用户:/subagents send <uuid> "refocus on X"
Agent: 向运行中的子智能体发送额外指令
子智能体 UUID 格式:84f72b1c(8 字符十六进制)
用户:/agent think <query>
Agent: 启用扩展思考模式(token 消耗更多,但推理更深)
用户:/agent fast <query>
Agent: 启用快速模式(回复更快,思考较浅)
用户:/agent focus <path>
Agent: 限制 Agent 只能访问指定目录
用户:/agent unfocus
Agent: 解除目录限制
用户:/shell ls -la ~
Agent: 执行命令并返回输出
用户:/bash python script.py
Agent: 执行 bash 脚本(别名)
用户:! grep -r "pattern" .
Agent: 使用 ! 前缀的快捷方式
可选参数:
用户:/shell ls -la ~ --background
Agent: 后台执行,不等待结果
用户:/shell long-running-task.sh --timeout 300
Agent: 设置最大执行时间(秒)
用户:/file read ~/data.csv
Agent: 读取文件内容
用户:/file write ~/output.txt "content"
Agent: 写入文件
用户:/file list ~/documents
Agent: 列出目录内容
用户:/file find "*.pdf"
Agent: 搜索文件
用户:/web search "latest AI news 2026"
Agent: 搜索网页
用户:/web screenshot https://example.com
Agent: 获取网页截图
用户:/web summarize https://example.com/article
Agent: 总结网页内容
用户:/peek screenshot
Agent: 获取当前屏幕截图
用户:/peek click 123 456
Agent: 点击坐标 (123, 456)
用户:/peek type "hello world"
Agent: 输入文本
用户:/peek find-button "Save"
Agent: 在屏幕上找到按钮
用户:/config set agents.defaults.model claude-opus-4
Agent: 修改模型配置
用户:/config set channels.whatsapp.enabled false
Agent: 禁用 WhatsApp
用户:/config reload
Agent: 重新加载配置(无需重启)
用户:/restart
Agent: 重启 Gateway 守护进程
用户:/restart --force
Agent: 强制重启(杀死所有进程)
用户:/approve exec-12345
Agent: 批准待审批的命令执行
用户:/deny exec-12345
Agent: 拒绝待审批的命令执行
# 基本用法
moltbot agent "分析销售数据"
# 指定 Agent
moltbot agent --agent coding-agent "修复这个 bug"
# 启用扩展思考
moltbot agent --thinking high "设计系统架构"
# 快速回复(低延迟)
moltbot agent --thinking low "这是什么"
# 限制工具使用
moltbot agent --commands "shell,files" "列出 Python 文件"
# 指定目录范围
moltbot agent --workdir ~/project "项目中有多少行代码"
# 等待最终结果
moltbot agent --expect-final "完成整个任务"
# 自定义 timeout(秒)
moltbot agent --timeout 120 "这可能需要很长时间"
# 发送到 WhatsApp
moltbot message send --to +1234567890 --message "Hello"
# 发送到 Telegram
moltbot message send --to @username --platform telegram --message "你好"
# 发送到 Discord
moltbot message send --to #channel-name --platform discord --message "Hi"
# 发送带附件
moltbot message send --to +1234567890 --file ~/image.jpg --caption "Check this"
# 列出所有技能
moltbot skill list
# 搜索技能
moltbot skill search wine
# 查看技能详情
moltbot skill info wine-cellar
# 安装社区技能
moltbot skill install @community/wine-cellar
# 发布自己的技能
moltbot skill publish ./my-awesome-skill --name "My Awesome Skill" --version "1.0.0" --license MIT
# 启用/禁用技能
moltbot skill enable wine-cellar
moltbot skill disable wine-cellar
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:18789');
ws.on('open', () => {
// 1. 连接请求
ws.send(JSON.stringify({
type: 'req',
id: 'conn-1',
method: 'connect',
params: {
minProtocol: 3,
maxProtocol: 3,
role: 'operator',
auth: { token: process.env.OPENCLAW_GATEWAY_TOKEN }
}
}));
});
ws.on('message', (data) => {
const msg = JSON.parse(data);
if (msg.type === 'res' && msg.id === 'conn-1') {
// 连接成功,开始发送命令
ws.send(JSON.stringify({
type: 'req',
id: 'invoke-1',
method: 'agent.invoke',
params: {
agentId: 'main',
tool: 'shell.exec',
args: { command: 'ls -la ~' }
}
}));
}
console.log('Response:', msg);
});
ws.on('error', (err) => {
console.error('WebSocket error:', err);
});
import asyncio
import json
import websockets
import os
async def interact_with_gateway():
token = os.getenv('OPENCLAW_GATEWAY_TOKEN')
uri = 'ws://localhost:18789'
async with websockets.connect(uri) as websocket:
# 连接请求
connect_msg = {
'type': 'req',
'id': 'conn-1',
'method': 'connect',
'params': {
'minProtocol': 3,
'maxProtocol': 3,
'role': 'operator',
'auth': { 'token': token }
}
}
await websocket.send(json.dumps(connect_msg))
response = await websocket.recv()
print('Connection response:', json.loads(response))
# 调用工具
invoke_msg = {
'type': 'req',
'id': 'invoke-1',
'method': 'agent.invoke',
'params': {
'agentId': 'main',
'tool': 'shell.exec',
'args': { 'command': 'pwd' }
}
}
await websocket.send(json.dumps(invoke_msg))
# 接收流式响应
while True:
response = await websocket.recv()
msg = json.loads(response)
print('Chunk:', msg)
if msg.get('stream_done'):
break
asyncio.run(interact_with_gateway())
Gateway 通过以下事件类型推送实时更新:
| 事件 | 说明 | 示例 |
|---|---|---|
chat.message | 新消息 | 用户发送了消息 |
chat.message.edited | 消息编辑 | 消息被修改 |
chat.message.deleted | 消息删除 | 消息被删除 |
chat.reaction | 表情反应 | 用户对消息添加了反应 |
chat.typing | 输入指示 | 用户正在输入 |
chat.presence | 在线/离线状态 | 用户上线/离线 |
| 事件 | 说明 | 示例 |
|---|---|---|
agent.thinking | Agent 正在思考 | 显示中间步骤 |
agent.tool-call | 工具调用 | Agent 调用了某个工具 |
agent.error | 执行错误 | 工具返回错误 |
agent.complete | 执行完成 | Agent 完成任务 |
| 事件 | 说明 | 示例 |
|---|---|---|
gateway.ready | Gateway 就绪 | 所有组件已初始化 |
gateway.restart | Gateway 重启 | 网关即将重启 |
config.changed | 配置变更 | 配置被修改 |
skill.loaded | 技能加载 | 新技能已加载 |
node.connected | 节点连接 | 新节点连接 |
node.disconnected | 节点断开 | 节点离线 |
| 作用 | 说明 | 权限范围 |
|---|---|---|
operator | 本地控制客户端 | 完全访问 |
node | 执行节点(Peekaboo、远程工作机) | 受限于声明的能力 |
adapter | 聊天平台适配器 | 仅消息收发 |
operator.*
├── operator.read # 读取配置、会话、日志
├── operator.write # 修改配置、发起任务
├── operator.admin # 管理其他操作员
├── operator.approvals # 批准执行请求
└── operator.pairing # 批准新设备
node.*
├── node.caps # 声明能力
├── node.execute # 执行工具调用
└── node.report # 报告状态
adapter.*
├── adapter.message.read # 接收消息
├── adapter.message.write # 发送消息
└── adapter.channel.bind # 绑定频道
# 方式 1:环境变量
export OPENCLAW_GATEWAY_TOKEN="my-secret-token"
# 方式 2:配置文件
# ~/.openclaw/openclaw.json
{"gateway":{"auth":{"token":"my-secret-token"}}}
# 方式 3:启动时指定
openclaw gateway --token "my-secret-token"
# 方式 4:CLI 调用时指定
openclaw gateway call status --token "my-secret-token"
第一次连接新设备时,Gateway 会要求批准:
# 新设备首次连接会显示配对码
openclaw status
# 输出中会显示配对码(如果需要)
# 在已授权的设备上批准
# 设备会自动获得 deviceToken,后续连接使用该令牌
1. 用户在 WhatsApp 发送消息
↓
2. WhatsApp Adapter 接收消息,转换为标准格式
↓
3. Gateway 路由消息给 main Agent
↓
4. Agent 接收消息,分析并选择工具
↓
5. Agent 发送工具调用请求到 Gateway
↓
6. Gateway 转发给对应的 Node(如 Peekaboo)或本地执行
↓
7. 工具返回结果
↓
8. Agent 处理结果,生成回复
↓
9. Gateway 通过 WhatsApp Adapter 发送回复
↓
10. 用户在 WhatsApp 收到回复
# 步骤 1:发送任务给 Agent
moltbot agent "分析 ~/data/sales.csv 并生成 PDF 报告"
# 步骤 2:在后台检查 Agent 状态
moltbot agent /subagents list
# 步骤 3:如果需要并行处理,使用子智能体
moltbot agent "启动 3 个并行子智能体分析不同区域的数据"
# 步骤 4:检查完成情况
moltbot agent /subagents info <uuid>
注意:所有命令和 API 调用都需要有效的 Gateway 令牌(如果配置了认证)。使用 --token 参数或设置 OPENCLAW_GATEWAY_TOKEN 环境变量。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online