# Query a running Gateway

> Query a running Gateway: health, usage-cost, stability, diagnostics export, status, connectivity checks, call, suspend, and resume

- 网址：https://funcoding.ai/agents/openclaw/cli/gateway/query/
- 来源：OpenClaw 官方文档原文（英文），MIT 许可，同步于 2026-10-11
- 官方原文：https://docs.openclaw.ai/zh-CN/cli/gateway/query

---
The WebSocket RPC query subcommands and their shared options. Part of the [`openclaw gateway`](https://funcoding.ai/agents/openclaw/cli/gateway/) reference.

## Query a running Gateway

All query commands use WebSocket RPC.

With token, password, or `none` authentication, ordinary RPC calls to the
configured local loopback Gateway do not open the shared state database for device
authentication. Explicit URL targets and paired remote connections retain their
device authentication rules. Existing identities are read through SQLite without
copying the shared database or entering its writer lifecycle. These reads can
create SQLite coordination files (WAL/SHM), but do not change stored identities,
tokens, or schema.

If device identity storage cannot be read, the call stops before connecting and
reports recovery guidance. It does not silently connect without the selected
device identity; check state-directory access and run `openclaw doctor --fix`
before retrying.

**Output modes**

- Default: human-readable (colored in TTY).
- `--json`: machine-readable JSON (no styling/spinner).
- `--no-color` (or `NO_COLOR=1`): disable ANSI while keeping human layout.

**Shared options**

- `--url <url>`: Gateway WebSocket URL.
- `--token <token>`: Gateway token.
- `--password <password>`: Gateway password.
- `--timeout <ms>`: timeout/budget (default varies per command; see each command below).
- `--expect-final`: wait for a "final" response (agent calls).

<div class="callout callout-note">

When you set `--url`, the CLI does not fall back to config or environment credentials. Pass `--token` or `--password` explicitly. Missing explicit credentials is an error.

</div>

WebSocket opening-handshake timeouts report a Gateway transport error with
`ETIMEDOUT`, including the target and a status-check hint. JSON error output uses
`error.type: "gateway_transport_error"`, as for other connection failures.

### `gateway health`

```bash
openclaw gateway health --url ws://127.0.0.1:18789
openclaw gateway health --port 18789
```

`/healthz` is a liveness check: it returns as soon as the server can answer HTTP. `/readyz` is stricter and stays red while startup plugin sidecars, channels, or configured hooks are still settling. Local or authenticated detailed `/readyz` responses include an `eventLoop` diagnostic block (delay, utilization, CPU-core ratio, `degraded` flag).

<a id="param-port"></a>

Target a local loopback Gateway on this port. Overrides `OPENCLAW_GATEWAY_URL` and `OPENCLAW_GATEWAY_PORT` for this call.

### `gateway usage-cost`

Fetch usage-cost summaries from session logs.

```bash
openclaw gateway usage-cost
openclaw gateway usage-cost --days 7
openclaw gateway usage-cost --agent work --json
openclaw gateway usage-cost --all-agents
openclaw gateway usage-cost --json
```

Human-readable output warns that totals may be incomplete when the usage cache is
refreshing, partial, or stale. The command returns the available snapshot from
one request; run it again later to check for refreshed totals. JSON output preserves
the `cacheStatus` object so scripts can inspect the same state.

<a id="param-days"></a>

Number of days to include.

<a id="param-agent"></a>

Scope the summary to one configured agent id.

<a id="param-all-agents"></a>

Aggregate across all configured agents. Cannot combine with `--agent`.

### `gateway stability`

Fetch the recent diagnostic stability recorder from a running Gateway.

```bash
openclaw gateway stability
openclaw gateway stability --type payload.large
openclaw gateway stability --bundle latest
openclaw gateway stability --bundle latest --export
openclaw gateway stability --json
```

<a id="param-limit"></a>

Maximum recent events to include (max `1000`).

<a id="param-type"></a>

Filter by diagnostic event type, e.g. `payload.large` or `diagnostic.memory.pressure`.

<a id="param-since-seq"></a>

Include only events after a diagnostic sequence number.

<a id="param-bundle-path"></a>

Read a persisted stability bundle instead of calling the running Gateway. `--bundle latest` (or bare `--bundle`) picks the newest bundle under the state directory; you can also pass a bundle JSON path directly.

<a id="param-export"></a>

Write a shareable support diagnostics zip instead of printing stability details.

Output path for `--export`.

<details>
<summary>Privacy and bundle behavior</summary>

- Records keep operational metadata: event names, counts, byte sizes, memory readings, queue/session state, approval ids, channel/plugin names, and redacted session summaries. They exclude chat text, webhook bodies, tool outputs, raw request/response bodies, tokens, cookies, secret values, hostnames, and raw session ids. Set `diagnostics.enabled: false` to disable the recorder entirely.
- Fatal Gateway exits, shutdown timeouts, and restart startup failures write a diagnostic snapshot to `~/.openclaw/logs/stability/openclaw-stability-*.json`, even when the recorder has no events. When the error has a stack, `error.stack` retains it with secrets redacted and a limit of 8,000 UTF-16 code units. Inspect the newest bundle with `openclaw gateway stability --bundle latest`; `--limit`, `--type`, and `--since-seq` apply to bundle output too.
- Failed shutdown steps include `evidence.shutdown`: the step and redacted error names, messages, codes, and stacks, including nested causes and aggregate errors. Use `openclaw gateway stability --bundle latest --json` to inspect these details. Capture is bounded to 32 errors and 8,000 UTF-16 code units per stack. `gateway.restart_close_failed` identifies a thrown close failure; `gateway.restart_shutdown_timeout` identifies the overall shutdown deadline. A timeout also retains any shutdown error already observed. Restart and stop failures flush the existing file logger before exit, within its shutdown budget.

</details>

### `gateway diagnostics export`

Write a local diagnostics zip designed for bug reports. For the privacy model and bundle contents, see [Diagnostics Export](https://funcoding.ai/agents/openclaw/gateway/diagnostics/).

```bash
openclaw gateway diagnostics export
openclaw gateway diagnostics export --output openclaw-diagnostics.zip
openclaw gateway diagnostics export --json
```

Output zip path. Defaults to a support export under the state directory.

<a id="param-log-lines"></a>

Maximum sanitized log lines to include.

<a id="param-log-bytes"></a>

Maximum log bytes to inspect.

<a id="param-url"></a>

Gateway WebSocket URL for the health snapshot.

<a id="param-token"></a>

Gateway token for the health snapshot.

<a id="param-password"></a>

Gateway password for the health snapshot.

<a id="param-timeout"></a>

Status/health snapshot timeout.

<a id="param-no-stability-bundle"></a>

Skip persisted stability bundle lookup.

<a id="param-json"></a>

Print the written path, size, and manifest as JSON.

The export bundles: `manifest.json` (file inventory), `summary.md` (Markdown summary), `diagnostics.json` (top-level config/logs/discovery/stability/status/health summary), `config/sanitized.json`, `status/gateway-status.json`, `health/gateway-health.json`, `logs/openclaw-sanitized.jsonl`, and `stability/latest.json` when a bundle exists.

It is designed to be shared. It keeps operational details useful for debugging — safe log fields, subsystem names, status codes, durations, configured modes, ports, plugin/provider ids, non-secret feature settings, and redacted operational log messages — and omits or redacts chat text, webhook bodies, tool outputs, credentials, cookies, account/message identifiers, prompt/instruction text, hostnames, and secret values. When a log message looks like user/chat/tool payload text (e.g. "user said", "chat text", "tool output", "webhook body"), the export keeps only the fact that a message was omitted plus its byte count.

### `gateway status`

Shows the Gateway service (launchd/systemd/schtasks) plus an optional connectivity/auth check.

```bash
openclaw gateway status
openclaw gateway status --json
openclaw gateway status --require-rpc
openclaw gateway status --port 19001
```

From a source checkout, `pnpm openclaw gateway status` reuses current prepared
runtime artifacts when their recorded input bytes still match, even if Git marks
those inputs dirty. Changed inputs or missing outputs still require a refresh;
status does not bypass the live Gateway's artifact-publication safeguards.

<a id="param-url-1"></a>

Check this explicit WebSocket URL instead of the service-derived target. Cannot combine with `--port`.

<a id="param-port-1"></a>

Select a local Gateway port using the invoking CLI config for auth and TLS. Accepts `gateway --port 19001 status` and `gateway status --port 19001`; an explicit status port wins. Native service details remain visible as diagnostics but do not select the check target.

<a id="param-token-1"></a>

Token auth for the check.

<a id="param-password-1"></a>

Password auth for the check.

<a id="param-timeout-1"></a>

Check timeout. Without an explicit value, the RPC check uses 10 seconds and Windows Task Scheduler state and registration checks allow 60 seconds for cold startup. The read-only registration query uses this allowance for both its total runtime and time without output. Explicit values also apply to native service checks. Each operation has its own budget; this is not an overall command deadline.

<a id="param-no-probe"></a>

Skip the connectivity check (service-only view).

<a id="param-deep"></a>

Scan system-level services too.

<a id="param-require-rpc"></a>

Upgrade the connectivity check to a read check and exit non-zero if it fails. Cannot combine with `--no-probe`.

<details>
<summary>Status semantics</summary>

- Stays available for diagnostics even when the local CLI config is missing or invalid. Config problems are warnings with `openclaw doctor --fix` guidance; valid connection settings and the recorded service identity remain usable.
- If service discovery cannot inspect a required file, such as a systemd environment file readable only by root, status reports the native service as unknown and continues with the caller's Gateway target and credentials. Observed service ownership refusals remain errors; status does not change file permissions or relax lifecycle checks.
- Default output proves service state, WebSocket connect, and the auth capability visible at handshake time — not read/write/admin operations.
- Checks are non-mutating for first-time device auth: they reuse an existing cached device token when one exists, but never create a new CLI device identity or read-only pairing record just to check status.
- Resolves configured auth SecretRefs for check auth when possible. If a required SecretRef is unresolved, `--json` reports `rpc.authWarning` when check connectivity/auth fails; pass `--token`/`--password` explicitly or fix the secret source. Unresolved-auth warnings are suppressed once the check succeeds.
- JSON output includes `gateway.version` when the running Gateway reports it; `--require-rpc` can fall back to the `status.runtimeVersion` RPC payload if the handshake check cannot supply version metadata.
- By default, exit 0 means diagnostics completed, not that the Gateway is healthy. A missing listener or failed auth/connectivity check can still exit 0; errors that prevent diagnostics from completing exit non-zero. `--json` changes the output format, not this exit behavior.
- Use `openclaw gateway status --deep --require-rpc` as a repair acceptance check or in scripts/automation that require working read-scope RPC. It exits non-zero if the read check fails, but does not certify plugin or channel readiness; inspect relevant diagnostics and reproduce the original symptom too. Status never starts or restarts the Gateway.
- `--deep` scans for extra launchd/systemd/schtasks installs; when multiple gateway-like services are found, human output prints cleanup hints (usually run one gateway per machine) and reports a recent supervisor restart handoff when relevant.
- `--deep` confirms exact npm targets before suggesting repairs for official-plugin version drift. Unpublished versions or registry failures are reported without an update command; retry deep status after registry access or the release cohort is restored. Ordinary status and readiness checks do not query npm for drift repairs.
- `--deep` also runs config validation in plugin-aware mode (`pluginValidation: "full"`) and surfaces plugin manifest warnings (e.g. missing channel config metadata). Default `gateway status` keeps the fast read-only path that skips plugin validation.
- On Linux, status reports the effective service currently loaded by systemd, including loaded drop-ins. If the unit or a drop-in changed on disk, `Systemd reload: pending` means you must run `systemctl --user daemon-reload` (or `sudo systemctl daemon-reload` for a system service) before those changes take effect.
- Human output includes the resolved file log path plus CLI-vs-service config paths/validity to help diagnose profile or state-dir drift.
- If the Gateway reports no version, human output still shows the locally inspected service package version and path when readable. A version mismatch suggests reinstalling only when that service is the check target; installation restrictions appear as the existing refusal message.
- A missing native service is informational when that service is diagnostic-only, such as a Gateway using a non-default state directory. The connectivity check still reports the selected Gateway's result.
- Install and reinstall guidance follows the invoking shell's installation rules, not the stored service environment or check target. Nix mode, external supervision, noncanonical installation identity, and Linux sudo/user-manager mismatches show the install refusal instead of an unusable command. A diagnostic-only target is not itself a refusal. Nix mode blocks installation, not starting an existing service.
- Human output includes `Gateway heap:` with configured service heap controls and a separate install-time recommendation based on memory visible to the CLI. JSON output exposes the same report as `service.gatewayHeap`. Neither is a measurement of the running Gateway's V8 heap ceiling; use runtime memory diagnostics for that.

</details>

<details>
<summary>Linux systemd auth-drift checks</summary>

- Service auth drift checks read both `Environment=` and `EnvironmentFile=` from the unit. `Environment=` assignments may be quoted. Use one unquoted absolute path per `EnvironmentFile=` directive, including paths with spaces; multiple directives and optional `-` files are supported. `%h` expands to the service home, and `%%` represents a literal percent sign.
- Resolves `gateway.auth.token` SecretRefs using merged runtime env (service command env first, then process env fallback).
- Token-drift checks skip config token resolution when token auth is not effectively active (`gateway.auth.mode` explicitly `password`/`none`/`trusted-proxy`, or mode unset where password can win and no token candidate can win).

</details>

### `gateway probe`

The "debug everything" command. It always checks:

- your configured remote gateway (if set), and
- localhost (loopback), **even if remote is configured**.

Passing `--url` adds that explicit target ahead of both. Human output labels targets `URL (explicit)`, `Remote (configured)` / `Remote (configured, inactive)`, and `Local loopback`.

<div class="callout callout-note">

If multiple check targets are reachable, all are printed. An SSH tunnel, TLS/proxy URL, and configured remote URL can point at the same gateway even with different transport ports; `multiple_gateways` is reserved for distinct or identity-ambiguous reachable gateways. Running multiple gateways is supported for isolated profiles (e.g. a rescue bot), but most installs run a single gateway.

</div>

```bash
openclaw gateway probe
openclaw gateway probe --json
openclaw gateway probe --port 18789
```

<a id="param-port-2"></a>

Use this port for the local loopback check target and SSH tunnel remote port. Without `--url`, this selects only the local loopback target instead of configured gateway environment URL, environment port, or remote targets.

<details>
<summary>Interpretation</summary>

- `Reachable: yes` means at least one target accepted a WebSocket connect.
- `Capability: read-only|write-capable|admin-capable|pairing-pending|connect-only` reports what the check could prove about auth, separate from reachability.
- A successful read check means read-scope detail RPC calls (`health`/`status`/`system-presence`/`config.get`) also succeeded.
- A read check limited by missing `operator.read` scope means connect succeeded but read-scope RPC is limited. Reported as **degraded** reachability, not full failure.
- A failed read check after `Connect: ok` means the WebSocket connected but follow-up read diagnostics timed out or failed — also **degraded**, not unreachable.
- Like `gateway status`, this command reuses existing cached device auth but does not create first-time device identity or pairing state.
- Exit code is non-zero only when no checked target is reachable.

</details>

<details>
<summary>JSON output</summary>

Top level:

- `ok`: at least one target is reachable.
- `degraded`: at least one target accepted a connection but did not complete full detail RPC diagnostics.
- `capability`: best capability seen across reachable targets (`read_only`, `write_capable`, `admin_capable`, `pairing_pending`, `connected_no_operator_scope`, or `unknown`).
- `primaryTargetId`: best target to treat as the active winner, in order: explicit URL, SSH tunnel, configured remote, local loopback.
- `warnings[]`: best-effort warning records with `code`, `message`, optional `targetIds`.
- `network`: local loopback/tailnet URL hints derived from current config and host networking.
- `discovery.timeoutMs` / `discovery.count`: the actual discovery budget/result count used for this check pass.

Per target (`targets[].connect`): `ok` (reachability + degraded classification), `rpcOk` (full detail RPC success), `scopeLimited` (detail RPC failed on missing operator scope).

Per target (`targets[].auth`): `role` and `scopes` reported in `hello-ok` when available, plus the surfaced `capability` classification.

</details>

<details>
<summary>Common warning codes</summary>

- `ssh_tunnel_failed`: SSH tunnel setup failed; the command fell back to direct checks.
- `multiple_gateways`: distinct gateway identities were reachable, or OpenClaw could not prove reachable targets are the same gateway. An SSH tunnel, proxy URL, or configured remote URL to the same gateway does not trigger this.
- `auth_secretref_unresolved`: a configured auth SecretRef could not be resolved for a failed target.
- `probe_scope_limited`: WebSocket connect succeeded, but the read check was limited by missing `operator.read`.
- `local_tls_runtime_unavailable`: local Gateway TLS is enabled but OpenClaw could not load the local certificate fingerprint.

</details>

#### Remote over SSH (Mac app parity)

The macOS app "Remote over SSH" mode uses a local port-forward so a loopback-only remote gateway becomes reachable at `ws://127.0.0.1:<port>`.

CLI equivalent:

```bash
openclaw gateway probe --ssh user@gateway-host
```

<a id="param-ssh"></a>

`user@host` or `user@host:port` (port defaults to `22`).

OpenClaw launches only an SSH client found in OS-managed system directories. On native Windows,
install the **OpenSSH Client** optional feature; Windows places it under
`%SystemRoot%\System32\OpenSSH`.

Identity file.

<a id="param-ssh-auto"></a>

Pick the first discovered gateway host as SSH target from the resolved discovery endpoint (`local.` plus the configured wide-area domain, if any). TXT-only hints are ignored.

Config defaults (optional): `gateway.remote.sshTarget`, `gateway.remote.sshIdentity`.

### `gateway call <method>`

Low-level RPC helper.

This command loads only the configuration needed to select and authenticate the
Gateway connection. It does not validate unrelated settings or preload plugin runtimes;
use `openclaw config validate` to check the full configuration.

Use `--expect-url <url>` to bind a call to a previously observed Gateway endpoint
without changing URL selection or authentication. The CLI compares the exact
resolved URL before connecting and fails if the destination changed. Automation
can obtain the endpoint from `gateway.url` in `openclaw status --json`; a redacted
URL cannot serve as an exact endpoint assertion.

```bash
openclaw gateway call status
openclaw gateway call health --port 18999
openclaw gateway call logs.tail --params '{"limit": 200}'
```

To add an existing checkout to the Control UI's Place picker, use the
[project registration and listing examples](https://funcoding.ai/agents/openclaw/web/control-ui/sessions-and-sidebar/#register-an-existing-repository).

For `sessions.send` and `chat.send`, JSON `timeoutMs` is the receiving agent's
execution budget, not an acknowledgment timeout. Omit it for ordinary
coordination; `--timeout` independently limits how long this CLI waits:

```bash
openclaw gateway call sessions.send --params '{"key":"<session-key>","message":"Status update"}' --timeout 10000
```

A `started` response confirms acceptance, not a completed reply. These CLI methods
are for operators and external automation. Agents use their exposed
[`sessions_send` tool](https://funcoding.ai/agents/openclaw/concepts/session-tool/#sending-cross-session-messages),
never a shell or direct RPC substitute. An unavailable messaging tool is not
permission to use the CLI. Subagents return results through their accepted task
completion path; the parent relays any necessary coordination with other sessions.

In an agent's `exec` subprocess (`OPENCLAW_SHELL=exec`), message RPCs are
refused before connecting so worker reports cannot appear as fresh human input.
Ordinary operator terminals and non-message Gateway diagnostics are unchanged.

<a id="param-params"></a>

JSON object string for params.

<a id="param-url-2"></a>

Gateway WebSocket URL.

<a id="param-port-3"></a>

Target a local loopback Gateway on this port. Overrides `OPENCLAW_GATEWAY_URL` and `OPENCLAW_GATEWAY_PORT` for this call. Cannot combine with `--url`.

<a id="param-token-2"></a>

Gateway token.

<a id="param-password-2"></a>

Gateway password.

<a id="param-timeout-2"></a>

Timeout budget.

<a id="param-expect-final"></a>

Mainly for agent-style RPCs that stream intermediate events before a final payload.

<a id="param-json-1"></a>

Machine-readable JSON output.

`openclaw.setup.detect` uses a 40-second default so the Gateway can finish its
bounded AI-access scan. An explicit `--timeout` still takes precedence.

<div class="callout callout-note">

`--params` must be valid JSON, and each method validates its own param shape (extra/misnamed fields are rejected). Use `--port` for a custom-port local Gateway; explicit `--url` targets still require explicit credentials.

</div>

### `gateway suspend`

Prepare an idle Gateway for a cooperative host freeze or snapshot. Without
`--wait`, active work returns a nonzero exit with blocker details. With
`--wait`, the CLI retries until the bounded deadline using one stable request
ID. The value must be a non-negative number of seconds; an empty value is rejected.
Use `--wait 0` for a single attempt without polling.

```bash
openclaw gateway suspend
openclaw gateway suspend --request-id snapshot-2026-08-11 --wait 30
openclaw gateway suspend --port 18999 --json
```

The ready output includes the suspension ID, lease expiry, and the matching
resume command. Common RPC options such as `--url`, `--token`, `--password`,
`--timeout`, `--json`, and `--port` are supported.

Suspension blocker messages name active root requests and include run IDs and
session keys for chat runs and pending terminal writes. Each category lists up
to eight holders, with an omitted count for the rest. `gateway.suspend.status`
returns the same details while draining, and each draining observation writes
one `DRAINING` line to the Gateway log. Pending final writes remain protected
until their persistence owner settles, even after a chat client disconnects.

### `gateway resume <suspensionId>`

Release a prepared suspension after thaw or when the host operation is
abandoned.

```bash
openclaw gateway resume <suspensionId>
openclaw gateway resume <suspensionId> --port 18999 --json
```

An already expired or resumed lease is a successful no-op. A different active
suspension ID is rejected. Once shutdown commits, resume is refused even for the
original owner; `gateway.suspend.status` reports that owner's shutdown progress
until server teardown closes RPC access.
