> 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/ch33-cli-tools/33.1-cli-architecture.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 33.1 CLI Architecture

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

***

OpenClaw's command-line interface (CLI) is the primary entry point for user interaction with the system. From `openclaw gateway` to start the service, to `openclaw agent` to send messages, to `openclaw doctor` to diagnose issues—all operations are dispatched through the CLI. This section analyzes the CLI architecture design from three dimensions: the Commander.js command framework, command dispatch mechanism, and command formatting utilities.

## 33.1.1 Commander.js Command Framework (`src/cli/program/build-program.ts`)

### Commander.js Introduction

> **Sidebar — Commander.js**
>
> Commander.js is the most popular command-line framework in the Node.js ecosystem, adopted by npm, webpack, and other well-known tools. It provides a declarative API for defining commands, options, arguments, and help text. Core concepts include:
>
> * **Command** — A command node that can contain subcommands (forming a tree structure)
> * **Option** — Named parameters passed as `--name` or `-n`
> * **Argument** — Positional arguments
> * **Action** — A callback function executed when a command is matched
> * **Hook** — Hooks triggered before/after command execution (e.g., `preAction`, `postAction`)

### Program Build Entry Point

`buildProgram()` is the factory function for the entire CLI, responsible for assembling a complete command tree:

```typescript
// src/cli/program/build-program.ts
import { Command } from "commander";
import { registerProgramCommands } from "./command-registry.js";
import { createProgramContext } from "./context.js";
import { configureProgramHelp } from "./help.js";
import { registerPreActionHooks } from "./preaction.js";

export function buildProgram() {
  const program = new Command();
  const ctx = createProgramContext();
  const argv = process.argv;

  configureProgramHelp(program, ctx);       // ① Help text and global options
  registerPreActionHooks(program, ctx.programVersion); // ② Pre-action hooks
  registerProgramCommands(program, ctx, argv);         // ③ Register all commands

  return program;
}
```

Four-step build process:

| Step                        | Function                    | Responsibility                                                                                                          |
| --------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| ① Create context            | `createProgramContext()`    | Collect version number, supported channel list (WhatsApp/Telegram/Discord/...)                                          |
| ② Configure help            | `configureProgramHelp()`    | Set `--dev`, `--profile`, `--no-color` global options; customize help output format (syntax highlighting, example code) |
| ③ Register pre-action hooks | `registerPreActionHooks()`  | Before each command executes: output Banner, set verbose, ensure config is valid, load plugins                          |
| ④ Register commands         | `registerProgramCommands()` | Iterate through command registry, register all top-level and subcommands                                                |

### ProgramContext — Context Object

```typescript
// src/cli/program/context.ts
export type ProgramContext = {
  programVersion: string;      // Current version number (e.g., "2.4.0")
  channelOptions: string[];    // List of supported channel names
  messageChannelOptions: string; // "whatsapp|telegram|discord|..."
  agentChannelOptions: string;   // "last|whatsapp|telegram|..."
};
```

`agentChannelOptions` adds `"last"` before the channel list, allowing users to use `--channel last` to automatically select the last-used channel.

### Help System Customization

OpenClaw deeply customizes Commander.js's default help system:

```typescript
// src/cli/program/help.ts (simplified)
program.configureHelp({
  sortSubcommands: true,   // Sort subcommands alphabetically
  sortOptions: true,       // Sort options alphabetically
  optionTerm: (option) => theme.option(option.flags),   // Color option names
  subcommandTerm: (cmd) => theme.command(cmd.name()),    // Color command names
});

program.configureOutput({
  writeOut: (str) => {
    // Color "Usage:", "Options:", "Commands:" headings
    const colored = str
      .replace(/^Usage:/gm, theme.heading("Usage:"))
      .replace(/^Options:/gm, theme.heading("Options:"))
      .replace(/^Commands:/gm, theme.heading("Commands:"));
    process.stdout.write(colored);
  },
});
```

The help text also includes rich examples (Examples), with each example consisting of two lines: command and description. The `openclaw` in commands is replaced with the actual CLI name by `replaceCliName()`.

### preAction Pre-Action Hook

Commander.js's `preAction` hook is triggered **before each command's action executes**:

```typescript
// src/cli/program/preaction.ts (simplified)
program.hook("preAction", async (_thisCommand, actionCommand) => {
  // 1. Set process title (e.g., "openclaw-gateway")
  setProcessTitleForCommand(actionCommand);

  // 2. Skip help/version commands
  if (hasHelpOrVersion(argv)) return;

  // 3. Output Banner (except update, completion, etc. commands)
  if (!hideBanner) emitCliBanner(programVersion);

  // 4. Set verbose mode
  setVerbose(getVerboseFlag(argv, { includeDebug: true }));

  // 5. Ensure config file is valid
  await ensureConfigReady({ runtime, commandPath });

  // 6. Load plugins for commands that require channels
  if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) {
    ensurePluginRegistryLoaded();
  }
});
```

`ensureConfigReady` is an important guard function—if the config file exists but is invalid (JSON parsing fails or schema validation fails), it prints an error message and suggests running `openclaw doctor --fix`. However, diagnostic commands like `doctor`, `health`, and `status` are whitelisted and allowed to execute even if the config is invalid.

### Command Registry

All top-level commands are centrally managed through the `commandRegistry` array:

```typescript
// src/cli/program/command-registry.ts (simplified)
export const commandRegistry: CommandRegistration[] = [
  { id: "setup",     register: ({ program }) => registerSetupCommand(program) },
  { id: "onboard",   register: ({ program }) => registerOnboardCommand(program) },
  { id: "configure",  register: ({ program }) => registerConfigureCommand(program) },
  { id: "config",     register: ({ program }) => registerConfigCli(program) },
  { id: "maintenance", register: ({ program }) => registerMaintenanceCommands(program) },
  { id: "message",   register: ({ program, ctx }) => registerMessageCommands(program, ctx) },
  { id: "memory",    register: ({ program }) => registerMemoryCli(program), routes: [...] },
  { id: "agent",     register: ({ program, ctx }) => registerAgentCommands(program, ctx), routes: [...] },
  { id: "subclis",   register: ({ program, argv }) => registerSubCliCommands(program, argv) },
  { id: "status-health-sessions", register: ({ program }) => registerStatusHealthSessionsCommands(program), routes: [...] },
  { id: "browser",   register: ({ program }) => registerBrowserCli(program) },
];
```

Each registration item contains:

* **id** — Unique identifier for debugging and logging
* **register** — Registration function receiving `{ program, ctx, argv }`
* **routes** (optional) — Fast routing rules (see next subsection)

Note the `subclis` item—it registers 25 lazy-loaded subcommands (gateway, models, channels, etc.), making it the largest source of CLI commands.

## 33.1.2 Command Dispatch (`src/cli/run-main.ts`)

### Two-Stage Dispatch Architecture

OpenClaw CLI's command dispatch employs a carefully designed **two-stage architecture**:

```
User input argv
    │
    ├─── Stage 1: Fast routing (tryRouteCli)
    │    └── Match → Execute directly, skip Commander.js
    │
    └─── Stage 2: Full dispatch (Commander.js parseAsync)
         ├── Lazy-load subcommands (registerSubCliByName)
         ├── Register plugin commands (registerPluginCliCommands)
         └── program.parseAsync(argv)
```

Why two stages? Performance. Building the complete Commander.js program requires importing many modules, loading configuration, and registering dozens of commands. But for high-frequency commands like `openclaw status`, only minimal dependencies are needed. Fast routing allows these commands to bypass the entire Commander.js pipeline.

### Complete Startup Flow

```typescript
// src/cli/run-main.ts (simplified)
export async function runCli(argv: string[] = process.argv) {
  // ① Windows compatibility: clean up extra node.exe paths in argv
  const normalizedArgv = stripWindowsNodeExec(argv);

  // ② Load .env file
  loadDotEnv({ quiet: true });

  // ③ Normalize environment variables
  normalizeEnv();

  // ④ Ensure openclaw executable is in PATH
  ensureOpenClawCliOnPath();

  // ⑤ Check Node.js/Bun version requirements
  assertSupportedRuntime();

  // ⑥ Fast routing: try to handle known commands directly
  if (await tryRouteCli(normalizedArgv)) return;

  // ⑦ Enable structured log capture
  enableConsoleCapture();

  // ⑧ Lazy-load Commander.js program
  const { buildProgram } = await import("./program.js");
  const program = buildProgram();

  // ⑨ Install global error handler
  installUnhandledRejectionHandler();

  // ⑩ Rewrite --update → update (backward compatibility)
  const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);

  // ⑪ Lazy-load subcommands as needed
  const primary = getPrimaryCommand(parseArgv);
  if (primary) {
    const { registerSubCliByName } = await import("./program/register.subclis.js");
    await registerSubCliByName(program, primary);
  }

  // ⑫ Register plugin-contributed commands
  if (!shouldSkipPluginRegistration) {
    const { registerPluginCliCommands } = await import("../plugins/cli.js");
    registerPluginCliCommands(program, loadConfig());
  }

  // ⑬ Execute command
  await program.parseAsync(parseArgv);
}
```

### Fast-Path Routing

Fast routing is a performance optimization mechanism that allows specific commands to bypass the complete Commander.js build process:

```typescript
// src/cli/route.ts
export async function tryRouteCli(argv: string[]): Promise<boolean> {
  // Environment variable can disable fast routing
  if (isTruthyEnvValue(process.env.OPENCLAW_DISABLE_ROUTE_FIRST)) return false;
  // Help/version requests need the complete command tree
  if (hasHelpOrVersion(argv)) return false;

  const path = getCommandPath(argv, 2);  // Extract up to 2 levels of command path
  if (!path[0]) return false;

  const route = findRoutedCommand(path);  // Look up matching route from registry
  if (!route) return false;

  // Output Banner + ensure config is ready
  await prepareRoutedCommand({ argv, commandPath: path, loadPlugins: route.loadPlugins });

  return route.run(argv);  // Execute directly
}
```

Commands supporting fast routing include:

| Command                  | Route Path             | Description   |
| ------------------------ | ---------------------- | ------------- |
| `openclaw health`        | `["health"]`           | Health check  |
| `openclaw status`        | `["status"]`           | Status query  |
| `openclaw sessions`      | `["sessions"]`         | Session list  |
| `openclaw agents list`   | `["agents", "list"]`   | Agent list    |
| `openclaw memory status` | `["memory", "status"]` | Memory status |

Each route's `run()` function directly parses flags in argv (`--json`, `--verbose`, `--timeout`, etc.) without Commander.js involvement. If argv format doesn't match expectations (e.g., `--timeout` without a value), the route returns `false`, delegating to the full process.

### Lazy-Loading Subcommands

The CLI registers 25 subcommands (gateway, models, channels, nodes, skills, cron, sandbox, tui, etc.), but each execution uses only one. Loading all of them causes startup delays—each subcommand file may introduce its own dependency chain.

OpenClaw's solution is **three-tier lazy loading**:

```
Tier 1: Register only target subcommand (most common path)
  ↓ Not found
Tier 2: Register placeholder commands (lazy loading)
  ↓ Placeholder triggered
Tier 3: Replace placeholder, load real command, re-parse
```

Core implementation in `register.subclis.ts`:

```typescript
// Tier 1: If target command is known, register it directly
const primary = getPrimaryCommand(argv);
if (primary && shouldRegisterPrimaryOnly(argv)) {
  const entry = entries.find((e) => e.name === primary);
  if (entry) {
    registerLazyCommand(program, entry);
    return;  // Register only one command
  }
}

// Tier 2: Register placeholders for all commands
for (const entry of entries) {
  registerLazyCommand(program, entry);
}
```

The elegance of placeholder commands lies in—they are real Commander.js commands, but with `allowUnknownOption(true)` and `allowExcessArguments(true)` set, so they match regardless of user input. When the placeholder's `action` is triggered:

```typescript
function registerLazyCommand(program: Command, entry: SubCliEntry) {
  const placeholder = program.command(entry.name).description(entry.description);
  placeholder.allowUnknownOption(true);
  placeholder.allowExcessArguments(true);
  placeholder.action(async (...actionArgs) => {
    // 1. Remove placeholder
    removeCommand(program, placeholder);
    // 2. Load and register real command
    await entry.register(program);
    // 3. Rebuild argv and re-parse
    const parseArgv = buildParseArgv({ programName, rawArgs, fallbackArgv });
    await program.parseAsync(parseArgv);
  });
}
```

This design allows `openclaw gateway start` to load only `gateway-cli.js`, without touching unrelated modules like `models-cli.js` or `channels-cli.js`.

> **Sidebar — Lazy Loading**
>
> Lazy loading is a deferred initialization pattern: load a resource only when it's actually needed. In CLI scenarios, this means importing (import) only the command modules the user actually requests. JavaScript's dynamic `import()` syntax makes this pattern concise: `const mod = await import("./gateway-cli.js")`. Unlike static `import` at the top of a file, dynamic import only triggers module loading when execution reaches that statement.

### argv Parsing Utilities

`argv.ts` provides a set of argv parsing utilities independent of Commander.js, used for fast routing and early decisions:

```typescript
// Extract command path (skip flags)
getCommandPath(["node", "openclaw", "memory", "--verbose", "status"], 2)
// → ["memory", "status"]

// Extract primary command
getPrimaryCommand(["node", "openclaw", "gateway", "start"])
// → "gateway"

// Check help/version flags
hasHelpOrVersion(["node", "openclaw", "--help"])
// → true

// Get flag value (supports both --name value and --name=value syntax)
getFlagValue(["node", "openclaw", "--timeout", "5000"], "--timeout")
// → "5000"
```

`getCommandPath` implementation skips all parameters starting with `-` (flags), collecting only positional parameters, and stops when encountering `--` (flag terminator). This follows UNIX command-line conventions.

### Windows Compatibility

`stripWindowsNodeExec` handles an edge case on Windows platforms—in some Windows environments, `process.argv` may contain extra `node.exe` paths or parameters with control characters (ASCII < 32):

```typescript
// Original argv (Windows anomaly):
["C:\\nodejs\\node.exe", "C:\\nodejs\\node.exe", "C:\\openclaw\\openclaw", "gateway"]

// After cleanup:
["C:\\nodejs\\node.exe", "C:\\openclaw\\openclaw", "gateway"]
```

The function also cleans up quote wrapping and Windows long path prefixes (`\\?\`).

## 33.1.3 Command Formatting (`src/cli/command-format.ts`)

When OpenClaw needs to display CLI commands in logs, error messages, or help text, `formatCliCommand` ensures commands use the correct name and configuration:

```typescript
// src/cli/command-format.ts
export function formatCliCommand(command: string): string {
  const cliName = resolveCliName();      // Resolve actual CLI name
  let formatted = replaceCliName(command, cliName); // Replace "openclaw" with actual name

  // If OPENCLAW_PROFILE environment variable is set, auto-inject --profile flag
  const profile = process.env.OPENCLAW_PROFILE;
  if (profile) {
    formatted = formatted.replace(cliName, `${cliName} --profile ${profile}`);
  }

  return formatted;
}
```

### CLI Name Resolution

`resolveCliName` extracts the CLI name from the filename of `process.argv[1]` (script path). If it's a known name (`"openclaw"`), use it directly; otherwise fall back to the default:

```typescript
// src/cli/cli-name.ts
export function resolveCliName(argv: string[] = process.argv): string {
  const base = path.basename(argv[1] ?? "").trim();
  if (KNOWN_CLI_NAMES.has(base)) return base;
  return DEFAULT_CLI_NAME; // "openclaw"
}
```

`replaceCliName` uses the regex `/^(?:(pnpm|npm|bunx|npx)\s+)?(openclaw)\b/` to match command prefixes, preserving package manager prefixes (e.g., `npx openclaw` → `npx mycli`), replacing only the CLI name part.

### Profile Injection

OpenClaw supports multi-profile execution—specified via `--profile <name>` or `OPENCLAW_PROFILE` environment variable. The built-in `--dev` option is actually a preset Profile named `dev`, which isolates the state directory to `~/.openclaw-dev` and offsets the Gateway port to 19001.

When the `OPENCLAW_PROFILE` environment variable is set, `formatCliCommand` automatically injects the `--profile` flag in all formatted commands, ensuring users see command examples they can directly copy and execute.

### CLI Dependency Injection

`deps.ts` defines the CLI's channel send dependency interface:

```typescript
// src/cli/deps.ts
export type CliDeps = {
  sendMessageWhatsApp: typeof sendMessageWhatsApp;
  sendMessageTelegram: typeof sendMessageTelegram;
  sendMessageDiscord:  typeof sendMessageDiscord;
  sendMessageSlack:    typeof sendMessageSlack;
  sendMessageSignal:   typeof sendMessageSignal;
  sendMessageIMessage:  typeof sendMessageIMessage;
};
```

`createDefaultDeps()` returns the real implementation, while `createOutboundSendDeps()` converts it to the `OutboundSendDeps` interface, decoupling the CLI layer from the channel send layer's naming conventions. This dependency injection pattern allows test implementations to be substituted with mocks.

### Banner Output

The CLI outputs a brand identification line on startup, including version number, Git commit hash, and a random tagline:

```
🦞 OpenClaw 2.4.0 (a1b2c3d) — Your AI, your rules
```

Banner output is controlled by multiple conditions:

* **Non-TTY** → Don't output (pipe scenario)
* **`--json` flag** → Don't output (machine-readable output)
* **`--version` flag** → Don't output
* **`OPENCLAW_HIDE_BANNER` environment variable** → Don't output
* **`update`/`completion` commands** → Don't output
* **Already output** → Don't repeat (singleton `bannerEmitted` flag)

In rich terminal (Rich TTY) mode, the Banner uses ANSI color codes; in plain terminals it outputs plain text. If terminal width is insufficient for a single line, it automatically wraps to two lines.

***

## Section Summary

1. **Commander.js Framework**: OpenClaw builds a command tree based on Commander.js through the `buildProgram()` factory function—creating context, configuring help, registering pre-action hooks, and registering commands in four steps
2. **Two-Stage Dispatch**: Fast routing (`tryRouteCli`) allows high-frequency commands to bypass the complete Commander.js pipeline and execute directly; only commands not matched by fast routing enter the full process
3. **Three-Tier Lazy Loading**: 25 subcommands are loaded on-demand—prioritize registering the target command, use placeholders for the rest, and when a placeholder is triggered, replace it with the real command and re-parse
4. **12-Step Startup Flow**: From Windows compatibility handling to `.env` loading, runtime checks, fast routing, lazy imports, subcommand registration, plugin command registration, finally executing `parseAsync`
5. **Command Formatting**: `formatCliCommand` ensures command examples in logs and help use the correct CLI name and inject Profile flags, guaranteeing users can directly copy and execute
6. **Dependency Injection and Banner**: The CLI layer decouples channel send implementations through the `CliDeps` type; Banner output automatically suppresses under multiple conditions, balancing aesthetics with programmability
