Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Openclaw Openclaw DoctorCommand

From Leeroopedia


DoctorCommand

This page documents the implementation of Diagnostic Repair in the OpenClaw gateway. It covers the main doctorCommand function and the checkGatewayHealth helper that performs the gateway connectivity check within the doctor flow.

Source Locations

Function File Lines
doctorCommand src/commands/doctor.ts L65-313
checkGatewayHealth src/commands/doctor-gateway-health.ts L9-58

doctorCommand

Signature

export async function doctorCommand(
  runtime: RuntimeEnv = defaultRuntime,
  options: DoctorOptions = {},
): Promise<void>

Purpose

doctorCommand is the main entry point for the openclaw doctor command. It orchestrates a comprehensive suite of diagnostic checks and optional repairs across the entire OpenClaw installation.

Parameters

Parameter Type Description
runtime RuntimeEnv Runtime environment for output. Defaults to defaultRuntime.
options DoctorOptions Configuration for the doctor run (see below).

DoctorOptions

export type DoctorOptions = {
  workspaceSuggestions?: boolean;
  yes?: boolean;
  nonInteractive?: boolean;
  deep?: boolean;
  repair?: boolean;
  force?: boolean;
  generateGatewayToken?: boolean;
};
Option Description
workspaceSuggestions Whether to show workspace improvement suggestions (default: true).
yes Auto-accept all repair prompts.
nonInteractive Skip all prompts; report only.
deep Run deeper diagnostic checks.
repair Equivalent to --fix; auto-apply safe repairs.
force Combined with repair, also apply aggressive fixes.
generateGatewayToken Auto-generate a gateway auth token if missing.

Behavior

The function executes the following diagnostic steps in order:

1. Initialization

  • Creates a DoctorPrompter via createDoctorPrompter which adapts confirmation prompts to the current mode (interactive, auto-repair, or non-interactive).
  • Prints the wizard header and the "OpenClaw doctor" intro banner.
  • Resolves the package root directory.

2. Pre-flight: Update check

  • Calls maybeOfferUpdateBeforeDoctor which checks for available updates and optionally offers to update first. If the user accepts and the update runs, returns early.

3. UI and install checks

  • maybeRepairUiProtocolFreshness -- ensures control UI assets match the expected protocol version.
  • noteSourceInstallIssues -- flags problems with the source installation (e.g., missing dist directory).
  • noteDeprecatedLegacyEnvVars -- warns about deprecated environment variable names.

4. Configuration

  • loadAndMaybeMigrateDoctorConfig -- loads openclaw.json, optionally migrating from legacy formats.
  • Checks if gateway.mode is set; if not, displays a note with fix instructions.

5. Authentication

  • maybeRepairAnthropicOAuthProfileId -- fixes malformed OAuth profile identifiers.
  • maybeRemoveDeprecatedCliAuthProfiles -- removes obsolete CLI auth profile entries.
  • noteAuthProfileHealth -- validates all configured auth profiles (keychain, OAuth, API keys).

6. Gateway auth

  • Checks if gateway auth is configured (token or password mode).
  • If missing, optionally generates and saves a token via randomToken().

7. Legacy state migration

  • detectLegacyStateMigrations -- scans for old session/agent/WhatsApp auth state.
  • If found, optionally runs runLegacyStateMigrations to move data to current locations.

8. State integrity and sandbox

  • noteStateIntegrity -- validates session store consistency.
  • maybeRepairSandboxImages -- checks Docker sandbox images.
  • noteSandboxScopeWarnings -- flags scope configuration issues.

9. Service configuration

  • maybeScanExtraGatewayServices -- detects duplicate or stale service registrations.
  • maybeRepairGatewayServiceConfig -- validates and repairs the OS service definition.
  • noteMacLaunchAgentOverrides -- checks for macOS LaunchAgent environment overrides.
  • noteMacLaunchctlGatewayEnvOverrides -- checks launchctl environment configuration.

10. Security and model checks

  • noteSecurityWarnings -- scans for insecure configuration patterns.
  • Validates hooks.gmail.model against the model catalog and allowlist if configured.

11. Linux-specific: systemd linger

  • On Linux with a loaded gateway service, checks for systemd user linger and optionally enables it.

12. Shell completion

  • doctorShellCompletion -- checks and installs shell tab completion.

13. Gateway health

  • Calls checkGatewayHealth (documented below) to verify the running gateway is reachable and channels are healthy.
  • maybeRepairGatewayDaemon -- if the gateway is not healthy, offers to restart or reinstall the daemon.

14. Finalization

  • If any repairs were made (prompter.shouldRepair or config migration occurred), writes the updated configuration and logs the change.
  • noteWorkspaceBackupTip -- suggests backing up the workspace directory.
  • shouldSuggestMemorySystem -- optionally suggests enabling the memory system.
  • Validates the final configuration file for structural correctness.
  • Prints "Doctor complete."

checkGatewayHealth

Signature

export async function checkGatewayHealth(params: {
  runtime: RuntimeEnv;
  cfg: OpenClawConfig;
  timeoutMs?: number;
}): Promise<{ healthOk: boolean }>

Purpose

checkGatewayHealth is a focused diagnostic function that verifies the running gateway is reachable and checks for channel-level issues. It is called as part of the doctor flow but can also be used independently.

Parameters

Parameter Type Description
params.runtime RuntimeEnv Runtime environment for output.
params.cfg OpenClawConfig Current configuration.
params.timeoutMs number (optional) Timeout for health and status RPC calls. Defaults to 10000ms; 3000ms in non-interactive mode.

Behavior

  1. Calls healthCommand with json: false to display the health summary in the terminal.
  2. If the health check succeeds (healthOk = true):
    • Makes a follow-up channels.status RPC call with probe: true to get detailed channel status.
    • Runs collectChannelStatusIssues to extract actionable warnings (e.g., expired tokens, misconfigured webhooks).
    • Displays any issues as a boxed note listing channel, account ID, message, and fix suggestion.
  3. If the health check fails:
    • Checks if the error indicates the gateway is not running ("gateway closed").
    • If so, displays "Gateway not running" with connection details.
    • Otherwise, formats and displays the error via formatHealthCheckFailure.

Return Value

Returns { healthOk: boolean } indicating whether the gateway was reachable and responded to the health RPC.

DoctorPrompter

The DoctorPrompter type (from src/commands/doctor-prompter.ts) adapts user interaction to the current mode:

export type DoctorPrompter = {
  confirm: (params: Parameters<typeof confirm>[0]) => Promise<boolean>;
  confirmRepair: (params: Parameters<typeof confirm>[0]) => Promise<boolean>;
  confirmAggressive: (params: Parameters<typeof confirm>[0]) => Promise<boolean>;
  confirmSkipInNonInteractive: (params: Parameters<typeof confirm>[0]) => Promise<boolean>;
  select: <T>(params: Parameters<typeof select>[0], fallback: T) => Promise<T>;
  shouldRepair: boolean;
  shouldForce: boolean;
};
Method Behavior
confirm Standard confirmation. Returns false in non-interactive mode, true in repair mode, prompts otherwise.
confirmRepair Same as confirm but also returns false in non-interactive mode (no auto-repair).
confirmAggressive Only returns true when both repair and force are set. Otherwise prompts or returns false.
confirmSkipInNonInteractive Returns false in non-interactive mode; otherwise behaves like confirm.

Dependencies

Module Purpose
src/commands/doctor-auth.ts Authentication profile health checks and repairs.
src/commands/doctor-completion.ts Shell completion diagnostics.
src/commands/doctor-config-flow.ts Configuration loading and migration.
src/commands/doctor-gateway-daemon-flow.ts Gateway daemon repair logic.
src/commands/doctor-gateway-services.ts Service configuration scanning and repair.
src/commands/doctor-sandbox.ts Sandbox image checks.
src/commands/doctor-security.ts Security warning detection.
src/commands/doctor-state-migrations.ts Legacy state detection and migration.
src/commands/health.ts healthCommand for gateway health checks.
src/infra/channels-status-issues.ts collectChannelStatusIssues for channel problem detection.

Principle:Openclaw_Openclaw_Diagnostic_Repair

Related Pages

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment