跳到主要内容OpenClaw Gateway 命令与交互指南 | 极客日志Shell / BashNode.jsAI
OpenClaw Gateway 命令与交互指南
综述由AI生成档详细阐述了 OpenClaw Gateway 的命令行接口(CLI)与 WebSocket API 的使用方法。内容包括 Gateway 的生命周期管理、健康诊断、配置变更、聊天消息收发、Agent 指令执行及会话控制。文档提供了完整的 CLI 命令参数说明、WebSocket 连接认证流程、聊天斜线命令列表以及 Node.js 和 Python 的 API 调用示例。此外还涵盖了系统事件类型、权限角色体系及设备配对机制,旨在帮助开发者高效集成自动化智能体工作流。
协议工匠33 浏览 OpenClaw Gateway 命令和交互
适用版本: OpenClaw v3.0+ / Moltbot v2.0+
CLI 命令
一、Gateway 生命周期管理
启动 Gateway(前台运行)
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 |
启动 Gateway(后台守护进程)
openclaw gateway install --port 18789 --token mytoken123
openclaw gateway start
openclaw gateway stop
openclaw gateway restart
openclaw gateway uninstall
openclaw gateway status
openclaw gateway status --json
二、Gateway 健康检查与诊断
健康状态检查
openclaw gateway health
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
状态检查(Service + RPC)
openclaw gateway status
openclaw gateway status --no-probe
openclaw gateway status --deep
openclaw gateway status --json
完整诊断(Debug Everything)
openclaw gateway probe
openclaw gateway probe --json
openclaw gateway probe --ssh user@gateway-host
openclaw gateway probe --ssh user@gateway-host:2222 --ssh-identity ~/.ssh/id_rsa
openclaw gateway probe --ssh-auto
三、Gateway 发现(Bonjour/mDNS)
openclaw gateway discover
openclaw gateway discover --timeout 4000
openclaw gateway discover --json
openclaw gateway discover --json | jq '.beacons[].wsUrl'
role: Gateway 角色提示
gatewayPort: WebSocket 端口(通常 18789)
sshPort: SSH 端口(默认 22)
tailnetDns: Tailscale Magic DNS 主机名
gatewayTls: TLS 是否启用
gatewayTlsSha256: TLS 证书指纹
四、低级 RPC 调用
openclaw gateway call <method> [--params <json>]
openclaw gateway call status
openclaw gateway call config.get --params '{}'
openclaw gateway call logs.tail --params '{"sinceMs": 60000}'
openclaw gateway call sessions.list --params '{"filter": "active"}'
openclaw gateway call agents.describe --params '{"id": "main"}'
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
WebSocket API 方法
Gateway 通过 WebSocket 暴露超过 84+ RPC 方法。以下是分类整理:
一、连接与认证
connect(建立连接)
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 }
}
}
device.token.rotate(轮换设备令牌)
openclaw gateway call device.token.rotate --params '{ "deviceId": "device-001", "scope": "operator" }'
device.token.revoke(撤销设备令牌)
openclaw gateway call device.token.revoke --params '{ "deviceId": "device-001", "token": "old-token" }'
二、系统状态
status(获取 Gateway 状态)
openclaw gateway call status
running: Gateway 是否在线
uptime: 运行时间(秒)
version: Gateway 版本
agents: 活动 Agent 列表
connections: 当前连接数
sessions: 会话统计
health(健康检查)
openclaw gateway call health
status: 'healthy' | 'degraded' | 'unhealthy'
components: 各组件的状态
gateway: 网关状态
storage: 存储状态
agents: Agent 运行时状态
system.info(系统信息)
openclaw gateway call system.info
platform: macOS | Linux | Windows
arch: 架构(x64、arm64 等)
memory: 可用内存
storage: 磁盘空间
三、配置管理
config.get(获取完整配置)
openclaw gateway call config.get --params '{}'
{"hash":"sha256_of_config","raw":"yaml_config_content","agents":[...],"channels":{},"models":{}}
config.patch(部分更新配置)
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 }'
config.apply(应用完整配置)
openclaw gateway call config.apply --params '{ "raw": "entire_yaml_config", "baseHash": "previous_hash", "sessionKey": "agent:main:whatsapp:dm:+1234567890", "restartDelayMs": 2000 }'
四、聊天与消息
chat.message(发送聊天消息)
openclaw gateway call chat.message --params '{ "channel": { "platform": "whatsapp", "id": "120363012345678-1234567890" }, "text": "用户消息内容", "attachments": [] }'
chat.history(获取对话历史)
openclaw gateway call chat.history --params '{ "channelId": "120363012345678-1234567890", "limit": 50, "since": "2026-01-01T00:00:00Z" }'
chat.search(搜索对话)
openclaw gateway call chat.search --params '{ "query": "搜索关键词", "channelId": "optional_channel_id", "limit": 20 }'
五、Agent 操作
agent.invoke(调用工具)
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"}}
agents.list(列出所有 Agent)
openclaw gateway call agents.list
agents.describe(获取 Agent 详细信息)
openclaw gateway call agents.describe --params '{ "id": "main" }'
id: Agent ID
name: Agent 名称
model: 使用的 LLM 模型
workspace: 工作区路径
skills: 可用技能列表
capabilities: 能力列表
agent.message(发送消息给 Agent)
openclaw gateway call agent.message --params '{ "agentId": "main", "text": "分析销售数据", "thinking": "high" }'
六、会话管理
sessions.list(列出会话)
openclaw gateway call sessions.list --params '{ "filter": "active" }'
sessions.get(获取会话详情)
openclaw gateway call sessions.get --params '{ "sessionId": "agent:main:whatsapp:dm:+1234567890" }'
sessions.delete(删除会话)
openclaw gateway call sessions.delete --params '{ "sessionId": "agent:main:whatsapp:dm:+1234567890" }'
七、工具与技能
skills.list(列出所有技能)
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":"管理葡萄酒收藏"}]}
skills.describe(获取技能详情)
openclaw gateway call skills.describe --params '{ "skillId": "shell" }'
skills.bins(获取可执行文件列表)
openclaw gateway call skills.bins
八、渠道管理
channels.list(列出已配置渠道)
openclaw gateway call channels.list
whatsapp
telegram
discord
slack
imessage
email
web
channels.describe(获取渠道详情)
openclaw gateway call channels.describe --params '{ "platform": "whatsapp" }'
channels.status(获取渠道连接状态)
openclaw gateway call channels.status --params '{ "platform": "whatsapp" }'
九、节点(Node)管理
nodes.list(列出连接的节点)
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"}]}
nodes.describe(获取节点详情)
openclaw gateway call nodes.describe --params '{ "nodeId": "peekaboo-node" }'
十、日志与调试
logs.tail(获取实时日志)
openclaw gateway call logs.tail --params '{ "sinceMs": 60000, "limit": 100 }'
logs.search(搜索日志)
openclaw gateway call logs.search --params '{ "query": "error", "level": "error|warn|info|debug", "since": "2026-01-01T00:00:00Z" }'
聊天斜线命令
通用斜线命令
这些命令可在任何支持的聊天平台上使用(WhatsApp、Telegram 等)。
/help(获取帮助)
用户:/help
Agent: 显示可用命令列表和使用说明
/status(查看 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)
用户:/agents
Agent: 列出所有可用的 Agent
用户:/agents use coding-agent
Agent: 切换到 "coding-agent"
/skills(列出和搜索技能)
用户:/skills
Agent: 列出所有加载的技能
用户:/skills search wine
Agent: 搜索名称包含 "wine" 的技能
/config(查看配置)
用户:/config
Agent: 显示当前 Agent 的配置信息
用户:/config agents.defaults.model
Agent: 显示指定配置项的值
/debug(启用调试模式)
用户:/debug on
Agent: 启用详细日志和思考过程显示
用户:/debug off
Agent: 关闭调试模式
- 工具调用的完整参数
- LLM 的思考过程(CoT)
- 中间执行结果
/memory(管理记忆)
用户:/memory status
Agent: 显示当前记忆使用情况
用户:/memory clear old
Agent: 清理 90 天前的旧记忆
用户:/memory export
Agent: 导出当前记忆为 JSON
Agent 特定命令
/subagents(管理子智能体)
用户:/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(直接 Agent 操作)
用户:/agent think <query>
Agent: 启用扩展思考模式(token 消耗更多,但推理更深)
用户:/agent fast <query>
Agent: 启用快速模式(回复更快,思考较浅)
用户:/agent focus <path>
Agent: 限制 Agent 只能访问指定目录
用户:/agent unfocus
Agent: 解除目录限制
工具和执行命令
/shell(执行 Shell 命令)
用户:/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(文件操作)
用户:/file read ~/data.csv
Agent: 读取文件内容
用户:/file write ~/output.txt "content"
Agent: 写入文件
用户:/file list ~/documents
Agent: 列出目录内容
用户:/file find "*.pdf"
Agent: 搜索文件
/web(网络搜索)
用户:/web search "latest AI news 2026"
Agent: 搜索网页
用户:/web screenshot https://example.com
Agent: 获取网页截图
用户:/web summarize https://example.com/article
Agent: 总结网页内容
/peek(截图和 UI 自动化)
用户:/peek screenshot
Agent: 获取当前屏幕截图
用户:/peek click 123 456
Agent: 点击坐标 (123, 456)
用户:/peek type "hello world"
Agent: 输入文本
用户:/peek find-button "Save"
Agent: 在屏幕上找到按钮
配置和管理命令
/config(修改配置)
用户:/config set agents.defaults.model claude-opus-4
Agent: 修改模型配置
用户:/config set channels.whatsapp.enabled false
Agent: 禁用 WhatsApp
用户:/config reload
Agent: 重新加载配置(无需重启)
/restart(重启 Gateway)
用户:/restart
Agent: 重启 Gateway 守护进程
用户:/restart --force
Agent: 强制重启(杀死所有进程)
/approve(审批执行请求)
用户:/approve exec-12345
Agent: 批准待审批的命令执行
用户:/deny exec-12345
Agent: 拒绝待审批的命令执行
Agent 子命令
通过 CLI 直接与 Agent 交互
moltbot agent(发送消息给 Agent)
moltbot 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 "完成整个任务"
moltbot agent --timeout 120 "这可能需要很长时间"
moltbot message(发送消息到渠道)
moltbot message send --to +1234567890 --message "Hello"
moltbot message send --to @username --platform telegram --message "你好"
moltbot message send --to
moltbot message send --to +1234567890 --file ~/image.jpg --caption "Check this"
moltbot skill(技能管理)
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
Gateway RPC 调用
通过 cURL 或编程方式调用 Gateway
JavaScript/Node.js 示例
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:18789');
ws.on('open', () => {
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);
});
Python 示例
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())
事件类型
聊天事件
| 事件 | 说明 | 示例 |
|---|
chat.message | 新消息 | 用户发送了消息 |
chat.message.edited | 消息编辑 | 消息被修改 |
chat.message.deleted | 消息删除 | 消息被删除 |
chat.reaction | 表情反应 | 用户对消息添加了反应 |
chat.typing | 输入指示 | 用户正在输入 |
chat.presence | 在线/离线状态 | 用户上线/离线 |
Agent 事件
| 事件 | 说明 | 示例 |
|---|
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 | 节点断开 | 节点离线 |
权限和认证
作用(Roles)
| 作用 | 说明 | 权限范围 |
|---|
operator | 本地控制客户端 | 完全访问 |
node | 执行节点(Peekaboo、远程工作机) | 受限于声明的能力 |
adapter | 聊天平台适配器 | 仅消息收发 |
权限范围(Scopes)
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 # 绑定频道
设置认证令牌
export OPENCLAW_GATEWAY_TOKEN="my-secret-token"
{"gateway":{"auth":{"token":"my-secret-token"}}}
openclaw gateway --token "my-secret-token"
openclaw gateway call status --token "my-secret-token"
设置设备配对
完整工作流示例
端到端聊天流程
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 收到回复
常见任务命令序列
任务:分析数据并生成报告
moltbot agent "分析 ~/data/sales.csv 并生成 PDF 报告"
moltbot agent /subagents list
moltbot agent "启动 3 个并行子智能体分析不同区域的数据"
moltbot agent /subagents info <uuid>
注意:所有命令和 API 调用都需要有效的 Gateway 令牌(如果配置了认证)。使用 --token 参数或设置 OPENCLAW_GATEWAY_TOKEN 环境变量。
相关免费在线工具
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online