Welcome to RDK X5 MagicBox repository
7. OpenClawGate Gateway User Manual
Gateway User Manual
Last updated: 2025-12-09
What It Is
- A resident process with a single Baileys/Telegram connection and control/event plane.
- Replaces the legacy
gatewaycommand. CLI entry point:openclaw gateway. - Runs until stopped; exits with a non-zero exit code on fatal errors so supervisors can restart it.
How to Run (Local)
openclaw gateway --port 18789# Get full debug/trace logs in stdio:openclaw gateway --port 18789 --verbose# If port is occupied, kill the listener then start:openclaw gateway --force# Development loop (auto-reload on TS changes):pnpm gateway:watch
Configuration hot-reload watches
~/.openclaw/openclaw.json(orOPENCLAW_CONFIG_PATH).- Default mode:
gateway.reload.mode="hybrid"(hot-apply safe changes, restart on critical changes). - Hot-reload uses in-process restart via SIGUSR1 when needed.
- Disable with
gateway.reload.mode="off".
- Default mode:
Bind WebSocket control plane to
127.0.0.1:<port>(default 18789).The same port also serves HTTP (control UI, hooks, A2UI). Single-port multiplexing.
- OpenAI Chat Completions (HTTP):
/v1/chat/completions. - OpenResponses (HTTP):
/v1/responses. - Tools Invoke (HTTP):
/tools/invoke.
- OpenAI Chat Completions (HTTP):
Starts Canvas file server on
canvasHost.port(default18793) by default, servinghttp://<gateway-host>:18793/__openclaw__/canvas/from~/.openclaw/workspace/canvas. Disable withcanvasHost.enabled=falseorOPENCLAW_SKIP_CANVAS_HOST=1.Outputs logs to stdout; use launchd/systemd to keep running and rotate logs.
Pass
--verbosewhen troubleshooting to mirror debug logs (handshake, request/response, events) from log file to stdio.--forceuseslsofto find listeners on the selected port, sends SIGTERM, logs what it killed, then starts the Gateway (fails fast iflsofis missing).If you're running under a supervisor (launchd/systemd/macOS app subprocess mode), stop/restart typically sends SIGTERM; older versions may show this as
pnpmELIFECYCLEexit code 143 (SIGTERM), which is normal shutdown, not a crash.SIGUSR1 triggers in-process restart when authorized (Gateway tool/config apply/update, or
commands.restartenabled for manual 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.The wizard now generates tokens by default, even on loopback.
Port priority:
--port>OPENCLAW_GATEWAY_PORT>gateway.port> default18789.
Remote Access
Preferred: Tailscale/VPN; otherwise use SSH tunnels:
xxxxxxxxxxssh -N -L 18789:127.0.0.1:18789 user@hostThen clients connect through the tunnel to
ws://127.0.0.1:18789.If a token is configured, clients must include it in
connect.params.auth.tokeneven through the tunnel.
Multiple Gateways (Same Host)
Usually not needed: one Gateway can serve multiple messaging channels and agents. Only use multiple Gateways when you need redundancy or strict isolation (e.g., rescue bot). Supported if you isolate state + config and use unique ports. Full guide: Multiple Gateways. Service names are profile-aware:
- macOS:
bot.molt.<profile>(legacycom.openclaw.*may still exist) - Linux:
openclaw-gateway-<profile>.service - Windows:
OpenClaw Gateway (<profile>)
Installation metadata embedded in service config:
OPENCLAW_SERVICE_MARKER=openclawOPENCLAW_SERVICE_KIND=gatewayOPENCLAW_SERVICE_VERSION=<version>
Rescue bot mode: Keep a second Gateway isolated with its own config, state directory, workspace, and base port offset. Full guide: Rescue Bot Guide.
Dev Profile (--dev)
Quick path: Run a fully isolated dev instance (config/state/workspace) without touching your main setup.
xxxxxxxxxxopenclaw --dev setupopenclaw --dev gateway --allow-unconfigured# Then target the dev instance:openclaw --dev statusopenclaw --dev health
Defaults (overridable via env/flags/config):
OPENCLAW_STATE_DIR=~/.openclaw-devOPENCLAW_CONFIG_PATH=~/.openclaw-dev/openclaw.jsonOPENCLAW_GATEWAY_PORT=19001(Gateway WS + HTTP)- Browser control service port =
19003(derived:gateway.port+2, loopback only) canvasHost.port=19005(derived:gateway.port+4)- When you run
setup/onboardunder--dev,agents.defaults.workspacedefaults to~/.openclaw/workspace-dev.
Derived ports (rule of thumb):
- Base port =
gateway.port(orOPENCLAW_GATEWAY_PORT/--port) - Browser control service port = base + 2 (loopback only)
canvasHost.port = base + 4(orOPENCLAW_CANVAS_HOST_PORT/ config override)- Browser profile CDP ports auto-allocated from
browser.controlPort + 9 .. + 108(persisted per profile).
Per-instance checklist:
- Unique
gateway.port - Unique
OPENCLAW_CONFIG_PATH - Unique
OPENCLAW_STATE_DIR - Unique
agents.defaults.workspace - Separate WhatsApp number (if using WA)
Install service by profile:
xxxxxxxxxxopenclaw --profile main gateway installopenclaw --profile rescue gateway installExample:
xxxxxxxxxxOPENCLAW_CONFIG_PATH=~/.openclaw/a.json OPENCLAW_STATE_DIR=~/.openclaw-a openclaw gateway --port 19001OPENCLAW_CONFIG_PATH=~/.openclaw/b.json OPENCLAW_STATE_DIR=~/.openclaw-b openclaw gateway --port 19002
Protocol (Operations Perspective)
Full docs: Gateway Protocol and Bridge Protocol (Legacy).
First frame clients must send:
req {type:"req", id, method:"connect", params:{minProtocol,maxProtocol,client:{id,displayName?,version,platform,deviceFamily?,modelIdentifier?,mode,instanceId?}, caps, auth?, locale?, userAgent? } }.Gateway replies
res {type:"res", id, ok:true, payload:hello-ok }(orok:falsewith error, then closes).After handshake:
- Request:
{type:"req", id, method, params}→{type:"res", id, ok, payload|error} - Event:
{type:"event", event, payload, seq?, stateVersion?}
- Request:
Structured presence entries:
{host, ip, version, platform?, deviceFamily?, modelIdentifier?, mode, lastInputSeconds?, ts, reason?, tags?[], instanceId? }(for WS clients,instanceIdcomes fromconnect.client.instanceId).agentresponses are two-phase: firstresacknowledges{runId,status:"accepted"}, then a finalres{runId,status:"ok"|"error",summary}when the run completes; streamed output arrives asevent:"agent".
Methods (Initial Set)
health— Full health snapshot (same shape asopenclaw health --json).status— Short summary.system-presence— Current presence list.system-event— Publish presence/system notes (structured).send— Send message through active channel.agent— Run an agent turn (events flow back on the same connection).node.list— List paired + currently connected nodes (includescaps,deviceFamily,modelIdentifier,paired,connected, and broadcastcommands).node.describe— Describe a node (capabilities + supportednode.invokecommands; works for paired nodes and currently connected unpaired nodes).node.invoke— Invoke a command on a node (e.g.,canvas.*,camera.*).node.pair.*— Pairing lifecycle (request,list,approve,reject,verify).
See also: Presence for how presence is produced/deduplicated and why stable client.instanceId matters.
Events
agent— Streamed tool/output events from agent runs (with seq markers).presence— Presence updates (incremental with stateVersion) pushed to all connected clients.tick— Periodic keepalive/no-op to confirm liveness.shutdown— Gateway is exiting; payload includesreasonand optionalrestartExpectedMs. Clients should reconnect.
WebChat Integration
- WebChat is a native SwiftUI UI that communicates directly with the Gateway WebSocket for history, sending, abort, and events.
- Remote usage via the same SSH/Tailscale tunnel; if Gateway token is configured, clients include it during
connect. - macOS app uses a single WS connection (shared connection); it populates presence from the initial snapshot and listens to
presenceevents to update the UI.
Types and Validation
Server validates every inbound frame using AJV against JSON Schema emitted from protocol definitions.
Clients (TS/Swift) consume generated types (TS directly; Swift via generator in the repo).
Protocol definitions are the source of truth; regenerate schema/models with:
pnpm protocol:genpnpm protocol:gen:swift
Connection Snapshot
hello-okcontains asnapshotwithpresence,health,stateVersion, anduptimeMs, pluspolicy {maxPayload,maxBufferedBytes,tickIntervalMs}, so clients can render immediately without additional requests.health/system-presenceare still available for manual refresh but not required at connection time.
Error Codes (res.error shape)
Errors use
{ code, message, details?, retryable?, retryAfterMs? }.Standard codes:
NOT_LINKED— WhatsApp not authenticated.AGENT_TIMEOUT— Agent did not respond within configured deadline.INVALID_REQUEST— Schema/parameter validation failed.UNAVAILABLE— Gateway is shutting down or dependency unavailable.
Keepalive Behavior
tickevents (or WS ping/pong) fire periodically so clients know the Gateway is alive even when there's no traffic.- Send/agent acknowledgments are kept separate; don't overload tick for sends.
Replay / Gaps
- Events are not replayed. Clients detecting seq gaps should flush (
health+system-presence) before continuing. WebChat and macOS clients now auto-flush on gaps.
Supervision (macOS Example)
Use launchd to keep the service alive:
- Program: path to
openclaw - Arguments:
gateway - KeepAlive: true
- StandardOut/Err: file path or
syslog
- Program: path to
launchd restarts on failure; fatal config errors should keep exiting so operators notice.
LaunchAgents are per-user, require a logged-in session; for headless setups, use a custom LaunchDaemon (not bundled).
openclaw gateway installwrites~/Library/LaunchAgents/bot.molt.gateway.plist(orbot.molt.<profile>.plist; legacycom.openclaw.*is cleaned up).openclaw doctoraudits LaunchAgent config and can update it to current defaults.
Gateway Service Management (CLI)
Use the Gateway CLI for install/start/stop/restart/status:
xxxxxxxxxxopenclaw gateway statusopenclaw gateway installopenclaw gateway stopopenclaw gateway restartopenclaw logs --follow
Notes:
gateway statusprobes Gateway RPC via the service-resolved port/config by default (override with--url).gateway status --deepadds system-level scan (LaunchDaemons/system units).gateway status --no-probeskips RPC probe (useful on network failures).gateway status --jsonis stable for scripting.gateway statusseparates supervisor runtime (launchd/systemd running) from RPC reachability (WS connection + status RPC).gateway statusprints config path + probe target to avoid "localhost vs LAN binding" confusion and config file mismatches.gateway statusincludes the last line of Gateway error when the service appears to be running but the port is closed.logstails Gateway file logs via RPC (no manualtail/grep).The CLI warns if it detects other Gateway-like services, unless they are OpenClaw profile services. We still recommend
one Gateway per machine
; use isolated config files/ports for redundancy or rescue bots. See
Multiple Gateways
.
- Cleanup:
openclaw gateway uninstall(current service) andopenclaw doctor(legacy migration).
- Cleanup:
gateway installis a no-op when already installed; useopenclaw gateway install --forceto reinstall (config file/env/path changes).
Bundled macOS app:
OpenClaw.app can bundle the Node-based Gateway relay and install a per-user LaunchAgent tagged as
bot.molt.gateway(orbot.molt.<profile>; legacycom.openclaw.*tags uninstall cleanly).To stop it cleanly, use
openclaw gateway stop(orlaunchctl bootout gui/$UID/bot.molt.gateway).To restart, use
openclaw gateway restart(orlaunchctl kickstart -k gui/$UID/bot.molt.gateway).launchctlonly works when the LaunchAgent is installed; otherwise runopenclaw gateway installfirst.- When running a named profile, replace the tag with
bot.molt.<profile>.
Supervision (systemd User Unit)
OpenClaw installs systemd user services by default on Linux/WSL2. We recommend user services for single-user machines (simpler env, per-user config). For multi-user or resident servers use system services (no lingering, shared supervision). openclaw gateway install writes the user unit. openclaw doctor audits the unit and can update it to match current recommended defaults. Create ~/.config/systemd/user/openclaw-gateway[-<profile>].service:
x[Unit]Description=OpenClaw Gateway (profile: <profile>, v<version>)After=network-online.targetWants=network-online.target[Service]ExecStart=/usr/local/bin/openclaw gateway --port 18789Restart=alwaysRestartSec=5Environment=OPENCLAW_GATEWAY_TOKEN=WorkingDirectory=/home/youruser[Install]WantedBy=default.target
Enable lingering (required so user services survive logout/idle):
xxxxxxxxxxsudo loginctl enable-linger youruser
The wizard runs this command on Linux/WSL2 (may prompt for sudo; writes to /var/lib/systemd/linger). Then enable the service:
xxxxxxxxxxsystemctl --user enable --now openclaw-gateway[-<profile>].service
Alternative (system service) - For resident or multi-user servers, you can install systemd system units instead of user units (no lingering required). Create /etc/systemd/system/openclaw-gateway[-<profile>].service (copy the unit above, switch WantedBy=multi-user.target, set User= + WorkingDirectory=), then:
xxxxxxxxxxsudo systemctl daemon-reloadsudo systemctl enable --now openclaw-gateway[-<profile>].service
Windows (WSL2)
Windows installations should use WSL2 and follow the Linux systemd section above.
Operations Checklist
- Liveness check: Open WS and send
req:connect→ expectreswithpayload.type="hello-ok"(with snapshot). - Readiness check: Call
health→ expectok: trueand linked channel inlinkChannel(when applicable). - Debug: Subscribe to
tickandpresenceevents; ensurestatusshows linked/authenticated time; presence entries show Gateway host and connected clients.
Security Guarantees
- Default assumption: one Gateway per host; if you run multiple profiles, isolate ports/state and target the correct instance.
- Never falls back to direct Baileys connection; sends fail fast if Gateway is down.
- Non-connect first frame or malformed JSON is rejected and socket closed.
- Graceful shutdown: emits
shutdownevent before closing; clients must handle close + reconnect.
CLI Helpers
openclaw gateway health|status— Request health/status via Gateway WS.openclaw message send --target <num> --message "hi" [--media ...]— Send via Gateway (idempotent for WhatsApp).openclaw agent --message "hi" --to <num>— Run agent turn (waits for final result by default).openclaw gateway call <method> --params '{"k":"v"}'— Raw method invoker for debugging.openclaw gateway stop|restart— Stop/restart supervised Gateway service (launchd/systemd).- Gateway helper subcommands assume a running Gateway on
--url; they no longer auto-spawn one.
Migration Guide
- Deprecate use of
openclaw gatewayand legacy TCP control port. - Update clients to use WS protocol with mandatory connect and structured presence.
For more about Gateway, see: Gateway User Manual - OpenClaw