OpenClawSkills
GitHub
Gateway / 运用 • TutorialHeader.readTime

Gateway Runbook(运用指南)

Gateway service, lifecycle, and operations

最終更新:2025-12-09

Tutorial.step

What is this

  • The always-on process that owns the single Baileys/Telegram connection and the control/event plane.
  • Replaces the legacy gateway command. CLI entry point: openclaw gateway.
  • Runs until stopped; exits non-zero on fatal errors so the supervisor restarts it.
Tutorial.step

実行方法(本地)

Bash
openclaw gateway --port 18789

openclaw gateway --port 18789 --verbose

openclaw gateway --force

pnpm gateway:watch
  • Config hot reload watches ~/.openclaw/openclaw.json (or OPENCLAW_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 (default 18793), serving http://<gateway-host>:18793/__openclaw__/canvas/ from ~/.openclaw/workspace/canvas. Disable with canvasHost.enabled=false or OPENCLAW_SKIP_CANVAS_HOST=1.
  • Logs to stdout; use launchd/systemd to keep it alive and rotate logs.
  • Pass --verbose to mirror debug logging (handshakes, req/res, events) from the log file into stdio when troubleshooting.
  • --force uses lsof to find listeners on the chosen port, sends SIGTERM, logs what it killed, then starts the gateway (fails fast if lsof is missing).
  • 如果您在监督程序(launchd/systemd/mac app 子进程模式)下运行,停止/重启通常会发送 SIGTERM;旧版本可能将其显示为 pnpm ELIFECYCLE 退出代码 143(SIGTERM),这是正常关闭,不是崩溃。
  • SIGUSR1 是認可如果已被在进程内重启触发器执行(gateway tools/config apply/update、或 commands.restart 由手动重启)。
  • Gateway auth is required by default: set gateway.auth.token (or OPENCLAW_GATEWAY_TOKEN) or gateway.auth.password. Clients must send connect.params.auth.token/password unless using Tailscale Serve identity.
  • 向导是 loopback 在也默认 token 生成执行。
  • 端口优先级:--port > OPENCLAW_GATEWAY_PORT > gateway.port > 默认 18789。
Tutorial.step

远程访问

Tailscale/VPN preferred; otherwise SSH tunnel:

Bash
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.token even over the tunnel.
Tutorial.step

复数 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> (legacy com.openclaw.* may still exist)
  • Linux:openclaw-gateway-<profile>.service
  • Windows:OpenClaw Gateway (<profile>)

安装元数据嵌入在服务配置中:

  • OPENCLAW_SERVICE_MARKER=openclaw
  • OPENCLAW_SERVICE_KIND=gateway
  • OPENCLAW_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.

Tutorial.step

開発者 profile(`--dev`)

Fast path: run a fully-isolated dev instance (config/state/workspace) without touching your primary setup.

Bash
openclaw --dev setup
openclaw --dev gateway --allow-unconfigured

openclaw --dev status
openclaw --dev health

默认(env/flags/config 在上写机可能):

  • OPENCLAW_STATE_DIR=~/.openclaw-dev
  • OPENCLAW_CONFIG_PATH=~/.openclaw-dev/openclaw.json
  • OPENCLAW_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 每个服务安装:

Bash
openclaw --profile main gateway install
openclaw --profile rescue gateway install

例:

Bash
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
Tutorial.step

协议(运维者視点)

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>.
Tutorial.step

方法(初期集合)

  • health — full health snapshot (same shape as openclaw 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 (includes caps, deviceFamily, modelIdentifier, paired, connected, and advertised commands).
  • node.describe — describe a node (capabilities + supported node.invoke commands; 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 但重要那理由)。

Tutorial.step

活动

  • 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。客户端是再连接执行。
Tutorial.step

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 presence events to update the UI.
Tutorial.step

输入和验证

  • Server validates every inbound frame with AJV against JSON Schema emitted from the protocol definitions.
  • 客户端(TS/Swift)是生成型使用执行(TS 直、Swift 是仓库生成器)。
  • 协议定义是真实来源;使用以下命令重新生成 schema/models:
  • pnpm protocol:gen
  • pnpm protocol:gen:swift
Tutorial.step

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-presence remain available for manual refresh, but are not required at connect time.
Tutorial.step

错误代码(res.error 形)

Errors use <code>'{ code, message, details?, retryable?, retryAfterMs? }'</code>.

标准代码:

  • NOT_LINKED — WhatsApp 但未认证。
  • AGENT_TIMEOUT — 代理但截止日期内在応答不会执行在已执行。
  • INVALID_REQUEST — schema/参数验证在失败。
  • UNAVAILABLE — Gateway 但关机中、或依赖但利用不可。
Tutorial.step

keepalive 的挙動

  • tick events (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.
Tutorial.step

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.

Tutorial.step

監督(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 install writes ~/Library/LaunchAgents/bot.molt.gateway.plist (or bot.molt.&lt;profile&gt;.plist; legacy com.openclaw.* is cleaned up).
  • openclaw doctor audits the LaunchAgent config and can update it to current defaults.
Tutorial.step

Gateway 服务管理(CLI)

Gateway CLI 在 install/start/stop/restart/status:

Bash
openclaw gateway status
openclaw gateway install
openclaw gateway stop
openclaw gateway restart
openclaw logs --follow

注意:

  • gateway status 是服务的解决済见 port/config 在 RPC probe(--url 在上写机)。
  • gateway status --deep adds system-level scans (LaunchDaemons/system units).
  • gateway status --no-probe 是 RPC probe 跳过(网络断在有用)。
  • gateway status --json 是脚本向可在安定。
  • gateway status reports 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) and openclaw doctor (legacy migrations).
  • gateway install is a no-op when already installed; use openclaw gateway install --force to 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 (or bot.molt.&lt;profile&gt;; legacy com.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)。
  • launchctl only works if the LaunchAgent is installed; otherwise use openclaw gateway install first.
  • 运行命名配置文件时,将标签替换为 bot.molt.&lt;profile&gt;。
Tutorial.step

監督(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[-&lt;profile&gt;].service 创建:

Terminal
[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):

Terminal
sudo loginctl enable-linger youruser

Onboarding runs this on Linux/WSL2 (may prompt for sudo; writes /var/lib/systemd/linger). Then enable the service:

那个後服务启用:

Terminal
systemctl --user enable --now openclaw-gateway[-<profile>].service

代替(system service):常時稼働/多用户服务器在是 systemd 的 system unit 安装(linger 不要)。

Create /etc/systemd/system/openclaw-gateway[-&lt;profile&gt;].service (copy the unit above, change WantedBy=multi-user.target, set User= + WorkingDirectory=) and run:

Terminal
sudo systemctl daemon-reload
sudo systemctl enable --now openclaw-gateway[-<profile>].service
Tutorial.step

Windows(WSL2)

On Windows, use WSL2 and follow the Linux systemd section above.

Tutorial.step

运维检查

  • Liveness: open WS and expect req:connect → payload.type="hello-ok" (with snapshot) res.
  • Readiness:health → ok: true 和 linkChannel 在链接済见渠道(該当時)期待。
  • Debug: subscribe to tick/presence, check status link/auth age, and confirm presence gateway host / connected clients.
Tutorial.step

安全性的保証

  • 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 処理执行。
Tutorial.step

CLI helpers

  • openclaw gateway health|status — Gateway WS 通过在 health/status 获取。
  • openclaw message send --target &lt;num&gt; --message "hi" [--media ...] — Gateway 通过在发送(WhatsApp 是冪等)。
  • openclaw agent --message "hi" --to &lt;num&gt; — 代理轮运行(默认在最終到待機)。
  • openclaw gateway call &lt;method&gt; --params {"k":"v"} — Raw method call for debugging.
  • openclaw gateway stop|restart — 監督下的 Gateway 服务 stop/restart(launchd/systemd)。
  • Gateway helpers assume --url is running; they do not auto-start.
Tutorial.step

迁移指南

  • Stop using the old openclaw gateway and old TCP control port.
  • 更新客户端以使用所需的连接和具有自己WS协议的结构化存在。