Hướng dẫn vận hành Gateway service

Cập nhật lần cuối: 09/12/2025

Gateway là gì

  • Một process chạy liên tục, quản lý kết nối Baileys/Telegram và control/event plane.
  • Thay thế lệnh gateway cũ. Điểm vào CLI: openclaw gateway.
  • Chạy cho đến khi bị dừng; thoát với mã lỗi khác 0 khi gặp lỗi nghiêm trọng để supervisor khởi động lại.

Cách chạy (local)

openclaw gateway --port 18789
# để xem đầy đủ debug/trace logs trong stdio:
openclaw gateway --port 18789 --verbose
# nếu port đang bận, dừng các listener rồi khởi động:
openclaw gateway --force
# dev loop (tự động reload khi TS thay đổi):
pnpm gateway:watch
  • Config hot reload theo dõi ~/.openclaw/openclaw.json (hoặc OPENCLAW_CONFIG_PATH).
    • Chế độ mặc định: gateway.reload.mode="hybrid" (áp dụng nóng các thay đổi an toàn, restart khi cần thiết).
    • Hot reload sử dụng in-process restart qua SIGUSR1 khi cần.
    • Tắt bằng gateway.reload.mode="off".
  • Bind WebSocket control plane tới 127.0.0.1:<port> (mặc định 18789).
  • Cùng port này cũng phục vụ HTTP (control UI, hooks, A2UI). Single-port multiplex.
  • Khởi động Canvas file server mặc định trên canvasHost.port (mặc định 18793), phục vụ http://<gateway-host>:18793/__openclaw__/canvas/ từ ~/.openclaw/workspace/canvas. Tắt bằng canvasHost.enabled=false hoặc OPENCLAW_SKIP_CANVAS_HOST=1.
  • Logs ra stdout; dùng launchd/systemd để giữ nó chạy và rotate logs.
  • Thêm --verbose để mirror debug logging (handshakes, req/res, events) từ log file vào stdio khi troubleshoot.
  • --force dùng lsof để tìm listeners trên port đã chọn, gửi SIGTERM, log những gì đã kill, rồi khởi động gateway (fail nhanh nếu thiếu lsof).
  • Nếu các bạn chạy dưới supervisor (launchd/systemd/mac app child-process mode), stop/restart thường gửi SIGTERM; các build cũ có thể hiển thị dưới dạng pnpm ELIFECYCLE exit code 143 (SIGTERM), đây là shutdown bình thường, không phải crash.
  • SIGUSR1 kích hoạt in-process restart khi được ủy quyền (gateway tool/config apply/update, hoặc bật commands.restart cho manual restarts).
  • Gateway auth được yêu cầu mặc định: đặt gateway.auth.token (hoặc OPENCLAW_GATEWAY_TOKEN) hoặc gateway.auth.password. Clients phải gửi connect.params.auth.token/password trừ khi dùng Tailscale Serve identity.
  • Wizard giờ tạo token mặc định, ngay cả trên loopback.
  • Thứ tự ưu tiên port: --port > OPENCLAW_GATEWAY_PORT > gateway.port > mặc định 18789.

Truy cập từ xa

  • Ưu tiên Tailscale/VPN; nếu không thì dùng SSH tunnel:
    ssh -N -L 18789:127.0.0.1:18789 user@host
  • Clients sau đó kết nối tới ws://127.0.0.1:18789 qua tunnel.
  • Nếu token được cấu hình, clients phải include nó trong connect.params.auth.token ngay cả qua tunnel.

Nhiều Gateway (cùng host)

Thường không cần thiết: một Gateway có thể phục vụ nhiều messaging channels và agents. Chỉ dùng nhiều Gateway cho redundancy hoặc strict isolation (ví dụ: rescue bot).

Được hỗ trợ nếu các bạn tách biệt state + config và dùng các port riêng biệt. Hướng dẫn đầy đủ: Multiple gateways.

Tên service nhận biết profile:

  • macOS: bot.molt.<profile> (legacy com.openclaw.* có thể vẫn tồn tại)
  • Linux: openclaw-gateway-<profile>.service
  • Windows: OpenClaw Gateway (<profile>)

Install metadata được nhúng trong service config:

  • OPENCLAW_SERVICE_MARKER=openclaw
  • OPENCLAW_SERVICE_KIND=gateway
  • OPENCLAW_SERVICE_VERSION=<version>

Rescue-Bot Pattern: giữ một Gateway thứ hai tách biệt với profile riêng, state dir, workspace, và base port spacing. Hướng dẫn đầy đủ: Rescue-bot guide.

Dev profile (--dev)

Cách nhanh: chạy một dev instance hoàn toàn tách biệt (config/state/workspace) mà không động vào setup chính.

openclaw --dev setup
openclaw --dev gateway --allow-unconfigured
# sau đó target dev instance:
openclaw --dev status
openclaw --dev health

Mặc định (có thể override qua env/flags/config):

  • OPENCLAW_STATE_DIR=~/.openclaw-dev
  • OPENCLAW_CONFIG_PATH=~/.openclaw-dev/openclaw.json
  • OPENCLAW_GATEWAY_PORT=19001 (Gateway WS + HTTP)
  • browser control service port = 19003 (derived: gateway.port+2, loopback only)
  • canvasHost.port=19005 (derived: gateway.port+4)
  • agents.defaults.workspace mặc định trở thành ~/.openclaw/workspace-dev khi các bạn chạy setup/onboard dưới --dev.

Derived ports (quy tắc chung):

  • Base port = gateway.port (hoặc OPENCLAW_GATEWAY_PORT / --port)
  • browser control service port = base + 2 (loopback only)
  • canvasHost.port = base + 4 (hoặc OPENCLAW_CANVAS_HOST_PORT / config override)
  • Browser profile CDP ports tự động phân bổ từ browser.controlPort + 9 .. + 108 (persisted per profile).

Checklist cho mỗi instance:

  • gateway.port riêng biệt
  • OPENCLAW_CONFIG_PATH riêng biệt
  • OPENCLAW_STATE_DIR riêng biệt
  • agents.defaults.workspace riêng biệt
  • Số WhatsApp riêng biệt (nếu dùng WA)

Service install cho mỗi profile:

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

Ví dụ:

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

Protocol (góc nhìn operator)

  • Tài liệu đầy đủ: Gateway protocolBridge protocol (legacy).
  • Frame đầu tiên bắt buộc từ client: req {type:"req", id, method:"connect", params:{minProtocol,maxProtocol,client:{id,displayName?,version,platform,deviceFamily?,modelIdentifier?,mode,instanceId?}, caps, auth?, locale?, userAgent? } }.
  • Gateway trả lời res {type:"res", id, ok:true, payload:hello-ok } (hoặc ok:false với error, rồi đóng).
  • Sau handshake:
    • Requests: {type:"req", id, method, params}{type:"res", id, ok, payload|error}
    • Events: {type:"event", event, payload, seq?, stateVersion?}
  • Structured presence entries: {host, ip, version, platform?, deviceFamily?, modelIdentifier?, mode, lastInputSeconds?, ts, reason?, tags?[], instanceId? } (với WS clients, instanceId đến từ connect.client.instanceId).
  • agent responses có hai giai đoạn: đầu tiên res ack {runId,status:"accepted"}, sau đó res cuối cùng {runId,status:"ok"|"error",summary} sau khi run kết thúc; streamed output đến dưới dạng event:"agent".

Methods (tập ban đầu)

  • health — full health snapshot (cùng shape với openclaw health --json).
  • status — tóm tắt ngắn.
  • system-presence — danh sách presence hiện tại.
  • system-event — post một presence/system note (structured).
  • send — gửi message qua channel(s) đang hoạt động.
  • agent — chạy một agent turn (streams events trở lại trên cùng connection).
  • node.list — liệt kê các nodes đã pair + đang kết nối (bao gồm caps, deviceFamily, modelIdentifier, paired, connected, và advertised commands).
  • node.describe — mô tả một node (capabilities + supported node.invoke commands; hoạt động cho paired nodes và currently-connected unpaired nodes).
  • node.invoke — invoke một command trên node (ví dụ canvas.*, camera.*).
  • node.pair.* — pairing lifecycle (request, list, approve, reject, verify).

Xem thêm: Presence để hiểu cách presence được tạo/dedup và tại sao client.instanceId ổn định lại quan trọng.

Events

  • agent — streamed tool/output events từ agent run (seq-tagged).
  • presence — presence updates (deltas với stateVersion) được push tới tất cả connected clients.
  • tick — periodic keepalive/no-op để xác nhận liveness.
  • shutdown — Gateway đang thoát; payload bao gồm reason và optional restartExpectedMs. Clients nên reconnect.

WebChat integration

  • WebChat là native SwiftUI UI giao tiếp trực tiếp với Gateway WebSocket cho history, sends, abort, và events.
  • Remote use đi qua cùng SSH/Tailscale tunnel; nếu gateway token được cấu hình, client include nó trong connect.
  • macOS app kết nối qua một WS duy nhất (shared connection); nó hydrates presence từ initial snapshot và lắng nghe presence events để update UI.

Typing và validation

  • Server validate mọi inbound frame với AJV dựa trên JSON Schema được emit từ protocol definitions.
  • Clients (TS/Swift) consume generated types (TS trực tiếp; Swift qua repo’s generator).
  • Protocol definitions là source of truth; regenerate schema/models với:
    • pnpm protocol:gen
    • pnpm protocol:gen:swift

Connection snapshot

  • hello-ok bao gồm một snapshot với presence, health, stateVersion, và uptimeMs cộng với policy {maxPayload,maxBufferedBytes,tickIntervalMs} để clients có thể render ngay mà không cần extra requests.
  • health/system-presence vẫn có sẵn cho manual refresh, nhưng không bắt buộc lúc connect.

Error codes (res.error shape)

  • Errors dùng { code, message, details?, retryable?, retryAfterMs? }.
  • Standard codes:
    • NOT_LINKED — WhatsApp chưa authenticated.
    • AGENT_TIMEOUT — agent không phản hồi trong deadline đã cấu hình.
    • INVALID_REQUEST — schema/param validation failed.
    • UNAVAILABLE — Gateway đang shutdown hoặc một dependency không khả dụng.

Keepalive behavior

  • tick events (hoặc WS ping/pong) được emit định kỳ để clients biết Gateway còn sống ngay cả khi không có traffic.
  • Send/agent acknowledgements vẫn là responses riêng biệt; không overload ticks cho sends.

Replay / gaps

  • Events không được replay. Clients phát hiện seq gaps và nên refresh (health + system-presence) trước khi tiếp tục. WebChat và macOS clients giờ tự động refresh khi có gap.

Supervision (ví dụ macOS)

  • Dùng launchd để giữ service chạy:
    • Program: đường dẫn tới openclaw
    • Arguments: gateway
    • KeepAlive: true
    • StandardOut/Err: file paths hoặc syslog
  • Khi fail, launchd restarts; fatal misconfig nên tiếp tục exit để operator nhận ra.
  • LaunchAgents là per-user và yêu cầu logged-in session; cho headless setups dùng custom LaunchDaemon (không được ship).
    • openclaw gateway install ghi ~/Library/LaunchAgents/bot.molt.gateway.plist (hoặc bot.molt.<profile>.plist; legacy com.openclaw.* được dọn dẹp).
    • openclaw doctor audit LaunchAgent config và có thể update nó về current defaults.

Gateway service management (CLI)

Dùng Gateway CLI cho install/start/stop/restart/status:

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

Lưu ý:

  • gateway status probes Gateway RPC mặc định dùng service’s resolved port/config (override với --url).
  • gateway status --deep thêm system-level scans (LaunchDaemons/system units).
  • gateway status --no-probe bỏ qua RPC probe (hữu ích khi networking down).
  • gateway status --json ổn định cho scripts.
  • gateway status báo cáo supervisor runtime (launchd/systemd running) riêng biệt với RPC reachability (WS connect + status RPC).
  • gateway status in config path + probe target để tránh nhầm lẫn “localhost vs LAN bind” và profile mismatches.
  • gateway status bao gồm dòng gateway error cuối cùng khi service trông có vẻ đang chạy nhưng port đóng.
  • logs tails Gateway file log qua RPC (không cần manual tail/grep).
  • Nếu phát hiện các gateway-like services khác, CLI cảnh báo trừ khi chúng là OpenClaw profile services. Mình vẫn khuyên một gateway per machine cho hầu hết setups; dùng isolated profiles/ports cho redundancy hoặc rescue bot. Xem Multiple gateways.
    • Cleanup: openclaw gateway uninstall (current service) và openclaw doctor (legacy migrations).
  • gateway install là no-op khi đã installed; dùng openclaw gateway install --force để reinstall (profile/env/path changes).

Bundled mac app:

  • OpenClaw.app có thể bundle một Node-based gateway relay và install một per-user LaunchAgent labeled bot.molt.gateway (hoặc bot.molt.<profile>; legacy com.openclaw.* labels vẫn unload sạch sẽ).
  • Để stop sạch sẽ, dùng openclaw gateway stop (hoặc launchctl bootout gui/$UID/bot.molt.gateway).
  • Để restart, dùng openclaw gateway restart (hoặc launchctl kickstart -k gui/$UID/bot.molt.gateway).
    • launchctl chỉ hoạt động nếu LaunchAgent đã installed; nếu không dùng openclaw gateway install trước.
    • Thay label bằng bot.molt.<profile> khi chạy named profile.

Supervision (systemd user unit)

OpenClaw cài đặt systemd user service mặc định trên Linux/WSL2. Mình khuyên dùng user services cho single-user machines (env đơn giản hơn, per-user config). Dùng system service cho multi-user hoặc always-on servers (không cần lingering, shared supervision).

openclaw gateway install ghi user unit. openclaw doctor audit unit và có thể update nó về current recommended defaults.

Tạo ~/.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 (bắt buộc để user service tồn tại sau logout/idle):

sudo loginctl enable-linger youruser

Onboarding chạy cái này trên Linux/WSL2 (có thể prompt sudo; ghi /var/lib/systemd/linger). Sau đó enable service:

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

Alternative (system service) - cho always-on hoặc multi-user servers, các bạn có thể install một systemd system unit thay vì user unit (không cần lingering). Tạo /etc/systemd/system/openclaw-gateway[-<profile>].service (copy unit ở trên, đổi WantedBy=multi-user.target, đặt User= + WorkingDirectory=), sau đó:

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

Windows (WSL2)

Windows installs nên dùng WSL2 và làm theo phần Linux systemd ở trên.

Operational checks

  • Liveness: mở WS và gửi req:connect → expect res với payload.type="hello-ok" (với snapshot).
  • Readiness: gọi health → expect ok: true và một linked channel trong linkChannel (khi applicable).
  • Debug: subscribe tới tickpresence events; đảm bảo status hiển thị linked/auth age; presence entries hiển thị Gateway host và connected clients.

Safety guarantees

  • Giả định một Gateway per host mặc định; nếu các bạn chạy nhiều profiles, tách biệt ports/state và target đúng instance.
  • Không có fallback tới direct Baileys connections; nếu Gateway down, sends fail nhanh.
  • Non-connect first frames hoặc malformed JSON bị reject và socket bị đóng.
  • Graceful shutdown: emit shutdown event trước khi đóng; clients phải handle close + reconnect.

CLI helpers

  • openclaw gateway health|status — request health/status qua Gateway WS.
  • openclaw message send --target <num> --message "hi" [--media ...] — gửi qua Gateway (idempotent cho WhatsApp).
  • openclaw agent --message "hi" --to <num> — chạy một agent turn (đợi final mặc định).
  • openclaw gateway call <method> --params '{"k":"v"}' — raw method invoker cho debugging.
  • openclaw gateway stop|restart — stop/restart supervised gateway service (launchd/systemd).
  • Gateway helper subcommands giả định một running gateway trên --url; chúng không còn auto-spawn nữa.

Migration guidance

  • Ngừng dùng openclaw gateway và legacy TCP control port.
  • Update clients để nói WS protocol với mandatory connect và structured presence.