网关协议架构概览
OpenClaw 的网关(Gateway)采用了独特的单端口复用架构,在同一端口上同时承载 WebSocket 控制面和 HTTP 数据面。这种设计大幅简化了部署和防火墙配置。
客户端 ──┐
├──→ [单端口 Gateway] ──→ WebSocket 控制面(长连接管理)
└──→ [单端口 Gateway] ──→ HTTP 数据面(API 请求)
启动网关
# 使用默认端口启动网关
openclaw gateway start
# 指定端口
openclaw gateway start --port 8080
# 后台运行
openclaw gateway start --daemon
WebSocket 控制面
WebSocket 连接用于实时双向通信,包括会话管理、工具调用状态推送、以及流式响应。
连接认证
连接时需要在 URL 参数中提供认证信息:
// Token 认证方式
const ws = new WebSocket('ws://localhost:8080/ws?token=your-gateway-token');
// 密码认证方式
const ws = new WebSocket('ws://localhost:8080/ws?password=your-password');
在配置文件中设置认证:
{
gateway: {
// Token 认证(推荐)
authToken: "oc_gw_xxxxxxxxxxxxx",
// 或密码认证
password: "your-secure-password",
// 监听端口
port: 8080
}
}
HTTP API 接口
OpenAI Chat Completions 兼容接口
OpenClaw 提供了与 OpenAI Chat Completions API 完全兼容的接口,可以直接对接现有的 OpenAI 客户端库。
curl http://localhost:8080/v1/chat/completions \
-H "Authorization: Bearer oc_gw_xxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4-20250514",
"messages": [
{"role": "user", "content": "你好,请介绍一下自己"}
],
"stream": true
}'
OpenResponses HTTP API
OpenResponses 接口提供了更丰富的交互能力,支持工具调用和上下文管理:
curl http://localhost:8080/v1/responses \
-H "Authorization: Bearer oc_gw_xxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4-20250514",
"input": "帮我查看当前目录的文件",
"tools": ["fs_read", "fs_list"]
}'
Tools Invoke API
直接调用已注册的工具:
curl -X POST http://localhost:8080/v1/tools/invoke \
-H "Authorization: Bearer oc_gw_xxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"tool": "web_fetch",
"arguments": {
"url": "https://example.com"
}
}'
热重载配置
无需重启网关即可重新加载配置文件,向进程发送 SIGUSR1 信号即可:
# 查找网关进程 ID
pgrep -f "openclaw gateway"
# 发送热重载信号
kill -SIGUSR1 $(pgrep -f "openclaw gateway")
热重载支持的配置项包括:模型路由、工具权限、频道设置。认证信息和端口变更仍需完整重启。
服务生命周期管理
使用 systemd 管理(Linux)
[Unit]
Description=OpenClaw Gateway Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/openclaw gateway start
Restart=on-failure
RestartSec=5
User=openclaw
[Install]
WantedBy=multi-user.target
使用 launchd 管理(macOS)
将 plist 文件放置在 ~/Library/LaunchAgents/ 目录下,OpenClaw 提供了自动生成命令:
openclaw gateway install-service
错误处理
网关在遇到致命错误时会以非零退出码退出,方便进程管理器自动重启:
| 退出码 | 含义 |
|---|---|
| 1 | 配置文件解析失败 |
| 2 | 端口被占用 |
| 3 | 认证配置缺失 |
| 4 | 数据库初始化失败 |
常见问题排查
- 连接被拒绝:检查端口是否正确、防火墙规则是否放行
- 认证失败:确认 token 或密码与配置文件一致,注意 URL 编码
- 热重载无效:确认发送信号到正确的进程,检查日志中的重载记录