Gateway Runbook(运用指南)
Gateway service, lifecycle, and operations
最終更新:2025-12-09
What is this
- The always-on process that owns the single Baileys/Telegram connection and the control/event plane.
- Replaces the legacy
gatewaycommand. CLI entry point:openclaw gateway. - Runs until stopped; exits non-zero on fatal errors so the supervisor restarts it.
実行方法(本地)
openclaw gateway --port 18789 openclaw gateway --port 18789 --verbose openclaw gateway --force pnpm gateway:watch
- Config hot reload watches
~/.openclaw/openclaw.json(orOPENCLAW_CONFIG_PATH). - Default mode:
gateway.reload.mode="hybrid"(hot-apply safe changes, restart on critical). - Hot reload uses in-process restart via SIGUSR1 when needed.
gateway.reload.mode="off"在禁用执行。- Binds WebSocket control plane to
127.0.0.1:<port>(default 18789). - The same port also serves HTTP (control UI, hooks, A2UI). Single-port multiplex.
- OpenAI Chat Completions(HTTP):
/v1/chat/completions。 - OpenResponses(HTTP):
/v1/responses。 - Toolscall(HTTP):
/tools/invoke。 - Starts a Canvas file server by default on
canvasHost.port(default18793), servinghttp://<gateway-host>:18793/__openclaw__/canvas/from~/.openclaw/workspace/canvas. Disable withcanvasHost.enabled=falseorOPENCLAW_SKIP_CANVAS_HOST=1. - Logs to stdout; use launchd/systemd to keep it alive and rotate logs.
- Pass
--verboseto mirror debug logging (handshakes, req/res, events) from the log file into stdio when troubleshooting. --forceuseslsofto find listeners on the chosen port, sends SIGTERM, logs what it killed, then starts the gateway (fails fast iflsofis missing).- 如果您在监督程序(launchd/systemd/mac app 子进程模式)下运行,停止/重启通常会发送 SIGTERM;旧版本可能将其显示为
pnpmELIFECYCLE退出代码 143(SIGTERM),这是正常关闭,不是崩溃。 - SIGUSR1 是認可如果已被在进程内重启触发器执行(gateway tools/config apply/update、或
commands.restart由手动重启)。 - Gateway auth is required by default: set
gateway.auth.token(orOPENCLAW_GATEWAY_TOKEN) orgateway.auth.password. Clients must sendconnect.params.auth.token/passwordunless using Tailscale Serve identity. - 向导是 loopback 在也默认 token 生成执行。
- 端口优先级:
--port>OPENCLAW_GATEWAY_PORT>gateway.port> 默认18789。
远程访问
Tailscale/VPN preferred; otherwise SSH tunnel:
ssh -N -L 18789:127.0.0.1:18789 user@host
- 客户端是隧道通过在
ws://127.0.0.1:18789在连接执行。 - If a token is configured, clients must include it in
connect.params.auth.tokeneven over the tunnel.
复数 Gateway(同一主机)
Usually unnecessary: one Gateway can serve multiple messaging channels and agents. Use multiple Gateways only for redundancy or strict isolation (ex: rescue bot).
Supported if you isolate state + config and use unique ports. Full guide: Multiple gateways.
服务名是 profile 認識执行:
- macOS:
bot.molt.<profile>(legacycom.openclaw.*may still exist) - Linux:
openclaw-gateway-<profile>.service - Windows:
OpenClaw Gateway (<profile>)
安装元数据嵌入在服务配置中:
OPENCLAW_SERVICE_MARKER=openclawOPENCLAW_SERVICE_KIND=gatewayOPENCLAW_SERVICE_VERSION=<version>
Rescue-Bot Pattern: keep a second Gateway isolated with its own profile, state dir, workspace, and base port spacing. Full guide: Rescue-bot guide.
開発者 profile(`--dev`)
Fast path: run a fully-isolated dev instance (config/state/workspace) without touching your primary setup.
openclaw --dev setup openclaw --dev gateway --allow-unconfigured openclaw --dev status openclaw --dev health
默认(env/flags/config 在上写机可能):
OPENCLAW_STATE_DIR=~/.openclaw-devOPENCLAW_CONFIG_PATH=~/.openclaw-dev/openclaw.jsonOPENCLAW_GATEWAY_PORT=19001(Gateway WS + HTTP)- 浏览器控制服务 =
19003(派生:gateway.port+2、loopback 仅) canvasHost.port=19005(派生:gateway.port+4)--dev在setup/onboard运行当执行、agents.defaults.workspace是~/.openclaw/workspace-dev但默认变为。
派生端口(目安):
- 基础端口 =
gateway.port(或OPENCLAW_GATEWAY_PORT/--port) - 浏览器控制服务 = base + 2(loopback 仅)
canvasHost.port = base + 4(或OPENCLAW_CANVAS_HOST_PORT/ 设置上写机)- 浏览器 profile 的 CDP 端口是
browser.controlPort + 9 .. + 108从自动割当(profile 每个予約)。
实示示例每个检查列表:
- unique
gateway.port - unique
OPENCLAW_CONFIG_PATH - unique
OPENCLAW_STATE_DIR - unique
agents.defaults.workspace - WhatsApp 编号是別途(WA 使用時)
profile 每个服务安装:
openclaw --profile main gateway install openclaw --profile rescue gateway install
例:
OPENCLAW_CONFIG_PATH=~/.openclaw/a.json OPENCLAW_STATE_DIR=~/.openclaw-a openclaw gateway --port 19001 OPENCLAW_CONFIG_PATH=~/.openclaw/b.json OPENCLAW_STATE_DIR=~/.openclaw-b openclaw gateway --port 19002
协议(运维者視点)
Full docs: Gateway protocol and Bridge protocol (legacy).
- Mandatory first frame from client: <code>req {type:"req", id, method:"connect", params:{minProtocol,maxProtocol,client:{id,displayName?,version,platform,deviceFamily?,modelIdentifier?,mode,instanceId?}, caps, auth?, locale?, userAgent? } }'</code>.
- Gateway 是 <code>res {type:"res", id, ok:true, payload:hello-ok }'</code> 返执行(或 <code>ok:false</code> + error 的後在 close)。
- 握手後:
- 请求:<code>'{type:"req", id, method, params}'</code> → <code>'{type:"res", id, ok, payload|error}'</code>
- 活动:<code>'{type:"event", event, payload, seq?, stateVersion?}'</code>
- 構造化 presence:<code>'{host, ip, version, platform?, deviceFamily?, modelIdentifier?, mode, lastInputSeconds?, ts, reason?, tags?[], instanceId? }'</code>(WS 客户端在是 <code>instanceId</code> 是 <code>connect.client.instanceId</code> 由来)。
- <code>agent</code> responses are two-stage: first <code>res</code> ack <code>'{runId,status:"accepted"}'</code>, then a final <code>res</code> <code>'{runId,status:"ok"|"error",summary}'</code> after the run finishes; streamed output arrives as <code>event:"agent"</code>.
方法(初期集合)
health— full health snapshot (same shape asopenclaw health --json).status— short summary.system-presence— 现在的 presence 列表。system-event— 状态/系统注記 publish(構造化)。send— 活跃那渠道通过在发送。agent— run an agent turn (streams events back on same connection).node.list— list paired + currently-connected nodes (includescaps,deviceFamily,modelIdentifier,paired,connected, and advertisedcommands).node.describe— describe a node (capabilities + supportednode.invokecommands; works for paired nodes and for currently-connected unpaired nodes).node.invoke— 节点上在命令运行(示示例:canvas.*、camera.*)。node.pair.*— pairing lifecycle (request,list,approve,reject,verify).
Presence 也参照(重复排除和、安定已执行 client.instanceId 但重要那理由)。
活动
agent— streamed tool/output events from the agent run (seq-tagged).presence— presence updates (deltas with stateVersion) pushed to all connected clients.tick— 定期 keepalive/no-op。shutdown— Gateway 但结束中。payload 在reason和任意的restartExpectedMs。客户端是再连接执行。
WebChat 連携
- WebChat is a native SwiftUI UI that talks directly to the Gateway WebSocket for history, sends, abort, and events.
- 远程使用通过相同的 SSH/Tailscale 隧道;如果配置了网关令牌,客户端在
connect期间包含它。 - macOS app connects via a single WS (shared connection); it hydrates presence from the initial snapshot and listens for
presenceevents to update the UI.
输入和验证
- Server validates every inbound frame with AJV against JSON Schema emitted from the protocol definitions.
- 客户端(TS/Swift)是生成型使用执行(TS 直、Swift 是仓库生成器)。
- 协议定义是真实来源;使用以下命令重新生成 schema/models:
pnpm protocol:genpnpm protocol:gen:swift
Connection snapshot
- <code>hello-ok</code> includes a <code>snapshot</code> with <code>presence</code>, <code>health</code>, <code>stateVersion</code>, and <code>uptimeMs</code> plus <code>policy {maxPayload,maxBufferedBytes,tickIntervalMs}'</code> so clients can render immediately without extra requests.
health/system-presenceremain available for manual refresh, but are not required at connect time.
错误代码(res.error 形)
Errors use <code>'{ code, message, details?, retryable?, retryAfterMs? }'</code>.
标准代码:
NOT_LINKED— WhatsApp 但未认证。AGENT_TIMEOUT— 代理但截止日期内在応答不会执行在已执行。INVALID_REQUEST— schema/参数验证在失败。UNAVAILABLE— Gateway 但关机中、或依赖但利用不可。
keepalive 的挙動
tickevents (or WS ping/pong) are emitted periodically so clients know the Gateway is alive even when no traffic occurs.- Send/agent acknowledgements remain separate responses; do not overload ticks for sends.
Replay / gaps
Events are not replayed. Clients detect seq gaps and should refresh (health + system-presence) before continuing. WebChat and macOS clients now auto-refresh on gap.
監督(macOS 例)
使用 launchd 保持服务运行:
- Program:
openclaw的路径 - Args:
gateway - KeepAlive:true
- StandardOut/Err:文件路径或
syslog - On failure, launchd restarts; fatal misconfig should keep exiting so the operator notices.
- LaunchAgents are per-user and require a logged-in session; for headless setups use a custom LaunchDaemon (not shipped).
openclaw gateway installwrites~/Library/LaunchAgents/bot.molt.gateway.plist(orbot.molt.<profile>.plist; legacycom.openclaw.*is cleaned up).openclaw doctoraudits the LaunchAgent config and can update it to current defaults.
Gateway 服务管理(CLI)
Gateway CLI 在 install/start/stop/restart/status:
openclaw gateway status openclaw gateway install openclaw gateway stop openclaw gateway restart openclaw logs --follow
注意:
gateway status是服务的解决済见 port/config 在 RPC probe(--url在上写机)。gateway status --deepadds system-level scans (LaunchDaemons/system units).gateway status --no-probe是 RPC probe 跳过(网络断在有用)。gateway status --json是脚本向可在安定。gateway statusreports supervisor runtime (launchd/systemd running) separately from RPC reachability (WS connect + status RPC).- <code>gateway status</code> prints config path + probe target to avoid "localhost vs LAN bind" confusion and profile mismatches.
- <code>gateway status</code> includes the last gateway error line when the service looks running but the port is closed.
logs是 RPC 通过在 Gateway 的文件日志 follow(手动tail/grep不要)。- If other gateway-like services are detected, the CLI warns unless they are OpenClaw profile services.
- 多可的配置在是 1台在次机1 Gateway 推荐。冗長化与 rescue bot 在是 profile/port 分钟離。Multiple Gateways 参照。
- Cleanup:
openclaw gateway uninstall(current service) andopenclaw doctor(legacy migrations). gateway installis a no-op when already installed; useopenclaw gateway install --forceto reinstall (profile/env/path changes).
同梱 Mac 应用:
- OpenClaw.app can bundle a Node-based gateway relay and install a per-user LaunchAgent labeled
bot.molt.gateway(orbot.molt.<profile>; legacycom.openclaw.*labels still unload cleanly). - 完全停止:
openclaw gateway stop(或launchctl bootout gui/$UID/bot.molt.gateway)。 - 重启:
openclaw gateway restart(或launchctl kickstart -k gui/$UID/bot.molt.gateway)。 launchctlonly works if the LaunchAgent is installed; otherwise useopenclaw gateway installfirst.- 运行命名配置文件时,将标签替换为
bot.molt.<profile>。
監督(systemd user unit)
Linux/WSL2 在默认 systemd user service 安装执行。单一用户機在是 user service(环境但簡単、用户別设置)推荐。多用户/常時稼働服务器是 system service(linger 不要、分钟享監督)推荐。
openclaw gateway install writes the user unit. openclaw doctor audits the unit and can update it to match the current recommended defaults.
~/.config/systemd/user/openclaw-gateway[-<profile>].service 创建:
[Unit] Description=OpenClaw Gateway (profile: <profile>, v<version>) After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/local/bin/openclaw gateway --port 18789 Restart=always RestartSec=5 Environment=OPENCLAW_GATEWAY_TOKEN= WorkingDirectory=/home/youruser [Install] WantedBy=default.target
Enable lingering (required so the user service survives logout/idle):
sudo loginctl enable-linger youruser
Onboarding runs this on Linux/WSL2 (may prompt for sudo; writes /var/lib/systemd/linger). Then enable the service:
那个後服务启用:
systemctl --user enable --now openclaw-gateway[-<profile>].service
代替(system service):常時稼働/多用户服务器在是 systemd 的 system unit 安装(linger 不要)。
Create /etc/systemd/system/openclaw-gateway[-<profile>].service (copy the unit above, change WantedBy=multi-user.target, set User= + WorkingDirectory=) and run:
sudo systemctl daemon-reload sudo systemctl enable --now openclaw-gateway[-<profile>].service
Windows(WSL2)
On Windows, use WSL2 and follow the Linux systemd section above.
运维检查
- Liveness: open WS and expect
req:connect→payload.type="hello-ok"(with snapshot)res. - Readiness:
health→ok: true和linkChannel在链接済见渠道(該当時)期待。 - Debug: subscribe to
tick/presence, checkstatuslink/auth age, and confirm presence gateway host / connected clients.
安全性的保証
- Default assumes one Gateway per host. If running multiple profiles, isolate port/state and specify the correct instance.
- No direct fallback to Baileys connection. If the Gateway is down, sends fail immediately.
- 拒绝未连接的首帧和无效 JSON,关闭套接字。
- Graceful shutdown:close 前在
shutdown送出。客户端是 close + reconnect 処理执行。
CLI helpers
openclaw gateway health|status— Gateway WS 通过在 health/status 获取。openclaw message send --target <num> --message "hi" [--media ...]— Gateway 通过在发送(WhatsApp 是冪等)。openclaw agent --message "hi" --to <num>— 代理轮运行(默认在最終到待機)。openclaw gateway call <method> --params {"k":"v"}— Raw method call for debugging.openclaw gateway stop|restart— 監督下的 Gateway 服务 stop/restart(launchd/systemd)。- Gateway helpers assume
--urlis running; they do not auto-start.
迁移指南
- Stop using the old
openclaw gatewayand old TCP control port. - 更新客户端以使用所需的连接和具有自己WS协议的结构化存在。