Commands — Command Processing & Dispatch

Command Processing & Dispatch

The Commands module implements the CLI command interface for all OpenClaw operations. It routes user-facing commands through a dispatch system with support for both interactive wizards and non-interactive batch modes, handling agent management, channel configuration, model selection, diagnostics, and system health checks.

3
Sub-Modules
448
TS Files
258
Command Files
TypeScript
Language

CLI Interface Interactive Wizards Batch Mode Diagnostics

Architecture

Commands are organized around a central dispatch pattern. User input enters through CLI entry points, is routed to domain-specific command handlers, and each handler follows a consistent lifecycle: load config snapshot, validate inputs, apply changes, and persist results with backup rotation.

flowchart LR
  subgraph Entry["CLI Entry"]
    CLI["CLI Dispatch
entry.ts"] --> Router["Command Router"] end subgraph Handlers["Command Handlers"] Router --> Agents["Agent Commands
agents.commands.*.ts"] Router --> Channels["Channel Commands
channels/*.ts"] Router --> Models["Model Commands
models/*.ts"] Router --> Doctor["Doctor Commands
doctor/*.ts"] Router --> Status["Status & Health
status.command.ts"] end subgraph Shared["Shared Infrastructure"] Config["Config I/O
requireValidConfigFileSnapshot()"] Runtime["RuntimeEnv
log / warn / error / exit"] Wizard["Wizard Prompter
createClackPrompter()"] end Agents --> Config Channels --> Config Models --> Config Agents --> Runtime Doctor --> Runtime Status --> Runtime Agents --> Wizard Channels --> Wizard

Data Flow

Every command that modifies configuration follows a transactional pattern: read a snapshot, compute a diff, validate, and atomically write back with backup rotation.

flowchart TD
  Input["User Input
CLI args & flags"] --> Dispatch["Command Router"] Dispatch --> ConfigLoad["Config Load
requireValidConfigFileSnapshot()"] ConfigLoad --> Branch{Interactive?} Branch -->|Yes| Prompt["Wizard Prompts
createClackPrompter()"] Branch -->|No| Parse["Parse CLI Flags"] Prompt --> Validate["Validate Choices
auth, model, channel"] Parse --> Validate Validate --> Apply["Apply Changes
config merge patch"] Apply --> Write["Config Write
replaceConfigFile()"] Write --> Backup["Backup Rotation
config/backup-rotation.ts"] Backup --> Output["Format Output
JSON or table"]

🚶 Step-by-Step Narrated Walkthrough

Follow a single models set gpt-4o command as it flows through the entire Commands pipeline:

  1. CLI Entry — The user types openclaw models set gpt-4o. The CLI framework parses the command and arguments.
  2. Command Routing — The dispatch layer identifies models set and routes to modelsSetCommand() in models/set.ts.
  3. Config Snapshot — requireValidConfigFileSnapshot(runtime) loads the current config file, computing a content hash for conflict detection.
  4. Model Validation — The raw model string "gpt-4o" is normalized and validated against known provider schemas.
  5. Auth Check — The system verifies that the selected provider has valid credentials. If not, an auth flow is triggered via applyAuthChoice().
  6. Config Diff — A merge patch is computed: the model ID is written to cfg.agents.defaults.model.
  7. Conflict Detection — The current config hash is compared against the snapshot hash. If another process modified the config, a conflict error is raised.
  8. Atomic Write — replaceConfigFile(nextConfig) writes the updated config atomically.
  9. Backup Rotation — The previous config version is rotated into the backup queue, keeping the last N versions.
  10. Output — A success message (or JSON if --json) is written to runtime.log(), confirming the model change.

Key Types & Interfaces

TypeFilePurpose
AgentsAddOptionsagents.commands.add.tsOptions for interactive/batch agent creation
AgentRouteBindingagents.bindings.tsRoute binding model mapping agent to channel/peer
AgentSummaryagents.config.tsDisplay-ready agent info with bindings and identity
ChannelAddResultchannels/add.tsResult of channel configuration with status
HealthSummaryhealth.tsSystem health across config, daemon, network, storage
DoctorCheckResultdoctor-state-integrity.tsDiagnostic finding with category, status, and remediation
ModelStatusItemmodels/list.probe.tsModel availability, pricing, and fallback status
ApplyAuthChoiceParamsauth-choice.apply.tsParameters for multi-strategy auth application
RuntimeEnvruntime.tsAbstraction for stdout/stderr with exit code control

Sub-Modules

slash-commands/

Slash command parsing, dispatch, and the command registry. Handles routing user input to the correct handler through pattern matching and argument parsing.

  • Command parsing & dispatch
  • Command registry with aliases
  • Agent route binding system

admin/

Administrative commands for system management including permission gating, doctor diagnostics, and operational tools for config repair and health monitoring.

  • Permission gating & allowlists
  • Doctor diagnostics & auto-repair
  • Health checks & status reporting

provider-switching/

Model and provider management including interactive model selection, auth flow orchestration, fallback configuration, and search provider setup.

  • Model picker & selection
  • Multi-strategy auth flow
  • Search provider configuration

Directory Map

Source tree for Commands
src/commands/
├── agents/                         ← Agent CRUD, binding, identity
│   ├── agents.commands.add.ts      ← Wizard-driven agent creation
│   ├── agents.commands.bind.ts     ← Route binding management
│   ├── agents.commands.delete.ts   ← Agent removal
│   ├── agents.commands.list.ts     ← Agent listing & display
│   ├── agents.bindings.ts          ← Binding model & dispatch logic
│   └── agents.config.ts            ← Agent configuration & summaries
├── channels/                       ← Channel add/remove/list/status
│   ├── add.ts                      ← Interactive channel configuration
│   ├── capabilities.ts             ← Channel capability detection
│   ├── status.ts                   ← Channel health & probing
│   └── resolve.ts                  ← Channel adapter resolution
├── models/                         ← Model selection, auth, aliases
│   ├── aliases.ts                  ← Model alias management
│   ├── auth.ts                     ← Provider authentication flows
│   ├── fallbacks.ts                ← Fallback model configuration
│   ├── list.probe.ts               ← Model availability probing
│   └── set.ts                      ← Default model selection
├── doctor/                         ← Diagnostics & repair
│   ├── shared/                     ← Allowlist, permission repair
│   │   ├── allowlist.ts            ← Permission gating logic
│   │   └── allowlist-policy-repair.ts ← Auto-repair routines
│   └── providers/                  ← Channel-specific diagnostics
├── auth-choice.apply.ts            ← Multi-strategy auth dispatch
├── status.command.ts               ← Main status command (794 LOC)
├── health.ts                       ← System health checks (845 LOC)
├── configure.wizard.ts             ← Multi-step onboarding (719 LOC)
├── onboard-search.ts               ← Search provider setup
└── sessions-cleanup.ts             ← Session lifecycle management