> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch38-monitoring-and-troubleshooting/38.1-health-checks.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 38.1 Health Checks

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~250k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Health checks are an indispensable infrastructure component in production environments—they enable operations teams and automated systems to determine whether the Gateway is functioning normally. OpenClaw provides a multi-layered health check mechanism: **Gateway Probes** (WebSocket level), **Health RPC Methods** (application level), and **Status Snapshots** (system level).

## 38.1.1 Gateway Probe

`probeGateway()` (`src/gateway/probe.ts`, 126 lines) is OpenClaw's most comprehensive health check tool. It is not a simple TCP port detection, but rather establishes a complete client connection via WebSocket and then requests multiple data points:

```typescript
// src/gateway/probe.ts (simplified)
export async function probeGateway(opts: {
  url: string;
  auth?: { token?: string; password?: string };
  timeoutMs: number;
}): Promise<GatewayProbeResult> {
  const client = new GatewayClient({
    url: opts.url,
    mode: "probe",           // Special probe mode
    onHelloOk: async () => {
      // After handshake succeeds, request four data points in parallel
      const [health, status, presence, configSnapshot] = await Promise.all([
        client.request("health"),
        client.request("status"),
        client.request("system-presence"),
        client.request("config.get", {}),
      ]);
      // Return structured result
    },
  });
  client.start();
}
```

The returned `GatewayProbeResult` contains:

| Field              | Type               | Meaning                                     |
| ------------------ | ------------------ | ------------------------------------------- |
| `ok`               | `boolean`          | Overall health status                       |
| `url`              | `string`           | Probed Gateway URL                          |
| `connectLatencyMs` | `number`           | WebSocket connection latency (milliseconds) |
| `error`            | `string \| null`   | Error message                               |
| `close`            | `{code, reason}`   | WebSocket close code and reason             |
| `health`           | `HealthSummary`    | Health summary of channels and agents       |
| `status`           | `object`           | Gateway runtime status                      |
| `presence`         | `SystemPresence[]` | List of online devices                      |
| `configSnapshot`   | `object`           | Current configuration snapshot              |

Probe mode (`mode: "probe"`) is a special connection mode for the Gateway client—it only performs read-only queries and is not counted toward active client counts, nor does it trigger chat or command execution.

## 38.1.2 Health RPC Methods

The Gateway exposes `health` and `status` two RPC methods that can be invoked via WebSocket:

```typescript
// src/gateway/server-methods/health.ts
export const healthHandlers: GatewayRequestHandlers = {
  health: async ({ respond, context, params }) => {
    const wantsProbe = params?.probe === true;
    const cached = context.getHealthCache();
    
    // If cache is valid and active probing is not requested, return cached result
    if (!wantsProbe && cached && now - cached.ts < HEALTH_REFRESH_INTERVAL_MS) {
      respond(true, cached, undefined, { cached: true });
      // Asynchronously refresh cache in background
      void context.refreshHealthSnapshot({ probe: false });
      return;
    }
    
    // Otherwise synchronously refresh and return
    const snap = await context.refreshHealthSnapshot({ probe: wantsProbe });
    respond(true, snap, undefined);
  },
  
  status: async ({ respond }) => {
    const status = await getStatusSummary();
    respond(true, status, undefined);
  },
};
```

### Health Cache Strategy

Health checks involve probing multiple channels (such as Telegram, Discord), which can take several seconds. To avoid frequent queries impacting performance, the Gateway implements a two-layer caching strategy:

1. **In-memory cache**: The `healthCache` variable stores the latest `HealthSummary` with timestamp and version number
2. **Background refresh**: When returning a cached result, simultaneously trigger an asynchronous refresh in the background—users see an immediate response while the cache is silently updated in the background

`refreshGatewayHealthSnapshot()` uses Promise deduplication—if a refresh is already in progress, new refresh requests will wait for the same Promise to complete, avoiding concurrent duplicate probes:

```typescript
// src/gateway/server/health-state.ts
export async function refreshGatewayHealthSnapshot(opts?: { probe?: boolean }) {
  if (!healthRefresh) {
    healthRefresh = (async () => {
      const snap = await getHealthSnapshot({ probe: opts?.probe });
      healthCache = snap;
      healthVersion += 1;
      broadcastHealthUpdate?.(snap);    // Notify all connected clients
      return snap;
    })().finally(() => { healthRefresh = null; });
  }
  return healthRefresh;  // Multiple requests share the same Promise
}
```

## 38.1.3 Health Summary Structure

`getHealthSnapshot()` (`src/commands/health.ts`, 788 lines) generates a comprehensive `HealthSummary` containing:

### Channel Health

For each configured channel (Telegram, Discord, WhatsApp, etc.), check:

* **Whether configured**: Whether API keys/credentials exist
* **Whether linked**: Whether OAuth tokens are valid
* **Probe result**: Actively call channel API to verify connectivity
* **Bot info**: Bot username, webhook URL

### Agent Health

For each configured Agent:

* **Heartbeat status**: `HeartbeatSummary` (interval time, last run time)
* **Session statistics**: Number of sessions, list of recently active sessions

### Session Health

* **Session storage path**
* **Total number of sessions**
* **Last 5 active sessions** (key name, update time, active duration)

## 38.1.4 Status Snapshot

`buildGatewaySnapshot()` (`src/gateway/server/health-state.ts`) generates an initial status snapshot when the Gateway starts and when a client first connects:

```typescript
export function buildGatewaySnapshot(): Snapshot {
  const cfg = loadConfig();
  return {
    presence: listSystemPresence(),          // Online devices
    health: {},                               // Placeholder, filled asynchronously
    stateVersion: {
      presence: presenceVersion,              // Presence change counter
      health: healthVersion,                  // Health data change counter
    },
    uptimeMs: Math.round(process.uptime() * 1000),  // Gateway uptime
    configPath: CONFIG_PATH,                  // Actual config file path
    stateDir: STATE_DIR,                      // State directory path
    sessionDefaults: {
      defaultAgentId,                         // Default agent ID
      mainKey,                                // Main session key
      mainSessionKey,                         // Main session identifier
      scope,                                  // Session scope mode
    },
  };
}
```

State version numbers (`presenceVersion` and `healthVersion`) are monotonically increasing counters. Clients can determine whether to refresh their local cache by comparing version numbers—this is more efficient than polling complete data.

## 38.1.5 Heartbeat Broadcast

The Gateway periodically broadcasts heartbeat events to all connected clients, containing the latest health and Presence data. When health status changes, `broadcastHealthUpdate()` also triggers real-time push:

```
Gateway ──heartbeat─→ [All clients]
         {health, presence, stateVersion}

Gateway ──health.update─→ [All clients]  (when health changes)
         {HealthSummary}
```

This push model ensures that the Web console and native applications can reflect the Gateway's health status in real-time without requiring clients to actively poll.

***

## Section Summary

1. **Gateway Probe** is the most comprehensive health check—it establishes a complete WebSocket connection and requests four data points (health, status, Presence, and configuration) in parallel, suitable for external monitoring and CLI diagnostics.
2. **Health RPC Methods** support a two-layer strategy of caching + background refresh—return cached results immediately when valid, while asynchronously updating; Promise deduplication avoids concurrent probes.
3. **Health Summary** covers three dimensions: channels (probe + configuration), agents (heartbeat + sessions), and system (uptime + version).
4. **State version numbers** are an efficient cache invalidation mechanism—monotonically increasing counters allow clients to determine whether to refresh by simply comparing numbers.
5. **Heartbeat broadcast** proactively pushes health data to all clients, achieving real-time state synchronization.
