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

# 33.3 Chat Commands (Slash Commands)

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

***

Beyond CLI terminal commands (like `openclaw gateway`, `openclaw models`), OpenClaw features a complete **chat command system**—users can type `/status`, `/new`, `/compact`, and other slash commands (Slash Commands) in chat windows to control Agent behavior. This section analyzes the registration, parsing, and execution mechanisms of this command system.

## 33.3.1 Command Registry Center (`src/auto-reply/commands-registry.data.ts`)

### Command Definition Type

Each chat command is described through the `ChatCommandDefinition` type:

```typescript
// src/auto-reply/commands-registry.types.ts
export type ChatCommandDefinition = {
  key: string;              // Unique identifier, e.g., "status", "new"
  nativeName?: string;      // Native command name (for native slash command registration on Telegram/Discord/Slack)
  description: string;      // Command description
  textAliases: string[];    // Text alias list, e.g., ["/status"], ["/new", "/reset"]
  acceptsArgs?: boolean;    // Whether accepts arguments
  args?: CommandArgDefinition[];  // Argument definitions
  argsParsing?: "none" | "positional";  // Argument parsing mode
  formatArgs?: (values: CommandArgValues) => string | undefined;
  argsMenu?: CommandArgMenuSpec | "auto";  // Argument selection menu for native platforms
  scope: CommandScope;      // "text" | "native" | "both"
  category?: CommandCategory; // Category
};

export type CommandScope = "text" | "native" | "both";
export type CommandCategory =
  | "session"     // Session management
  | "options"     // Runtime options
  | "status"      // Status queries
  | "management"  // System management
  | "media"       // Media control
  | "tools"       // Tools
  | "docks";      // Channel switching
```

### Three Command Scopes

| Scope    | Description                                                                | Example                                           |
| -------- | -------------------------------------------------------------------------- | ------------------------------------------------- |
| `text`   | Recognized only in text messages (e.g., "/compact" in WhatsApp message)    | `/compact`, `/bash`, `/allowlist`                 |
| `native` | Registered only on native slash command platforms (Telegram/Discord/Slack) | No exclusive commands                             |
| `both`   | Support both text and native methods                                       | `/status`, `/new`, `/think`, etc. (most commands) |

> **Sidebar — Native Slash Commands**
>
> Telegram, Discord, and Slack all support "native slash commands"—Bots declare which `/command` they support during registration, and users see auto-completion menus when typing `/` in chat. This differs from including `/status` in plain message text—native commands are parsed by the platform and delivered to the Bot in special format, while text commands require OpenClaw to match them from message text itself.

### Command Factory

`defineChatCommand` is the factory function for command definitions, auto-inferring default values:

```typescript
// src/auto-reply/commands-registry.data.ts (simplified)
function defineChatCommand(input: DefineChatCommandInput): ChatCommandDefinition {
  // Infer scope based on whether nativeName and textAlias exist
  const scope = input.scope ??
    (input.nativeName ? (aliases.length ? "both" : "native") : "text");

  // Has args definition → accepts arguments
  const acceptsArgs = input.acceptsArgs ?? Boolean(input.args?.length);

  // Has args definition → positional argument parsing
  const argsParsing = input.argsParsing ?? (input.args?.length ? "positional" : "none");

  return { key, nativeName, description, acceptsArgs, args, argsParsing, ... };
}
```

### Complete Command Registry

The `buildChatCommands()` function builds the complete command list. Below is a categorical summary of all built-in chat commands:

**Session Management (session)**

| Command    | Alias | Description              | Arguments                                                       |
| ---------- | ----- | ------------------------ | --------------------------------------------------------------- |
| `/new`     | —     | Start new session        | `[instruction]` (optional, initial instruction for new session) |
| `/reset`   | —     | Reset current session    | `[instruction]`                                                 |
| `/compact` | —     | Compress session context | `[instructions]` (compression instructions)                     |
| `/stop`    | —     | Stop current run         | None                                                            |

**Runtime Options (options)**

| Command      | Alias             | Description                 | Arguments                                     |
| ------------ | ----------------- | --------------------------- | --------------------------------------------- |
| `/think`     | `/thinking`, `/t` | Set thinking level          | `off / minimal / low / medium / high / xhigh` |
| `/verbose`   | `/v`              | Toggle verbose mode         | `on / off`                                    |
| `/reasoning` | `/reason`         | Toggle reasoning visibility | `on / off / stream`                           |
| `/elevated`  | `/elev`           | Toggle elevated mode        | `on / off / ask / full`                       |
| `/model`     | —                 | View/set model              | `[model-id]`                                  |
| `/models`    | —                 | List model providers        | —                                             |
| `/usage`     | —                 | Usage statistics            | `off / tokens / full / cost`                  |
| `/queue`     | —                 | Adjust queue settings       | `steer / interrupt / followup / ...`          |
| `/exec`      | —                 | Set execution parameters    | `host=... security=... ask=...`               |

**Status Queries (status)**

| Command     | Alias | Description                                             |
| ----------- | ----- | ------------------------------------------------------- |
| `/status`   | —     | Show current status (model, session, Token usage, etc.) |
| `/help`     | —     | Show available commands                                 |
| `/commands` | —     | List all slash commands                                 |
| `/whoami`   | `/id` | Show sender identity                                    |
| `/context`  | —     | Explain context construction                            |

**Management (management)**

| Command       | Description                                           |
| ------------- | ----------------------------------------------------- |
| `/allowlist`  | Manage allowlist                                      |
| `/approve`    | Approve execution requests                            |
| `/config`     | View/set config (`show / get / set / unset`)          |
| `/debug`      | Set runtime debug overrides                           |
| `/subagents`  | Manage sub-agents (`list / stop / log / info / send`) |
| `/activation` | Set group activation mode (`mention / always`)        |
| `/send`       | Set send policy (`on / off / inherit`)                |

**Tools (tools)**

| Command    | Description                                 |
| ---------- | ------------------------------------------- |
| `/skill`   | Run skill by name                           |
| `/bash`    | Execute host Shell command (text mode only) |
| `/restart` | Restart OpenClaw                            |

**Media (media)**

| Command | Description                                                              |
| ------- | ------------------------------------------------------------------------ |
| `/tts`  | Control text-to-speech (on/off/status/provider/limit/summary/audio/help) |

**Channel Switching (docks)**

Channel Dock commands are **dynamically generated**—based on registered channel plugins that support native commands, automatically creating `/dock-<id>` commands:

```typescript
...listChannelDocks()
  .filter((dock) => dock.capabilities.nativeCommands)
  .map((dock) => defineDockCommand(dock)),
```

### Alias Registration

Some commands have shortcut aliases:

```typescript
registerAlias(commands, "whoami", "/id");
registerAlias(commands, "think", "/thinking", "/t");
registerAlias(commands, "verbose", "/v");
registerAlias(commands, "reasoning", "/reason");
registerAlias(commands, "elevated", "/elev");
```

`registerAlias` uses Set deduplication to ensure no duplicate aliases are registered.

### Registry Validation

`assertCommandRegistry` performs strict completeness validation after command building:

* **Uniqueness**: `key` cannot repeat, `nativeName` cannot repeat, `textAlias` cannot repeat
* **Consistency**: `text` scope commands cannot have `nativeName` but must have `textAlias`; `native` scope commands cannot have `textAlias`
* **Format**: All `textAlias` must start with `/`

### Caching Strategy

The command list uses singleton caching, with plugin registry version control for invalidation:

```typescript
let cachedCommands: ChatCommandDefinition[] | null = null;
let cachedRegistry: ReturnType<typeof getActivePluginRegistry> | null = null;

export function getChatCommands(): ChatCommandDefinition[] {
  const registry = getActivePluginRegistry();
  if (cachedCommands && registry === cachedRegistry) {
    return cachedCommands;  // Cache hit
  }
  const commands = buildChatCommands();
  cachedCommands = commands;
  cachedRegistry = registry;
  return commands;
}
```

When the plugin registry changes (e.g., new plugin loaded), the cache automatically invalidates and rebuilds the command list.

## 33.3.2 Command Recognition and Dispatch

### Command Detection

OpenClaw's command detection has two modes:

1. **Exact Match** — Message is entirely a command (e.g., "/status")
2. **Inline Detection** — Message contains command marker (e.g., "hey /status")

Inline `/status` detection uses regex:

```typescript
// src/auto-reply/reply/reply-inline.ts
const INLINE_STATUS_RE = /(?:^|\s)\/status(?=$|\s|:)(?:\s*:\s*)?/gi;
```

For senders on the allowlist, inline `/status` is executed immediately and stripped from message text (hiding command text from the model). For unauthorized senders, inline commands are preserved as plain text.

### Command Execution Flow

```
User message "/compact focus on decisions"
    │
    ├── Command detection → Match /compact
    │
    ├── Permission check
    │   ├── Owner → Allow
    │   ├── Allowlist member → Allow
    │   └── Unauthorized → Deny (only /status allowed for all)
    │
    ├── Argument parsing → { instructions: "focus on decisions" }
    │
    ├── Dispatch to handler
    │   ├── /status → commands-status.ts → buildStatusMessage()
    │   ├── /new, /reset → commands-core.ts → Reset session + trigger Hooks
    │   ├── /compact → commands-compact.ts → Call compression pipeline
    │   ├── /think, /verbose, ... → Update session options
    │   └── /bash → commands-bash.ts → Execute Shell command
    │
    └── Send reply (text / native command response)
```

### `/status` — Status Report

`/status` is the most frequently used chat command, generating a detailed status report including:

* Current model and provider
* Session Token usage and context window percentage
* Agent configuration (thinking level, verbose mode, reasoning mode, etc.)
* Active sub-agents
* Enabled tools and skills
* Channel connection status
* Cost statistics (if available)

The status report is organized by category, displaying different information amounts for authorized and unauthorized users.

### `/new` and `/reset` — Session Reset

`/new` and `/reset` are functionally equivalent—resetting the current session and starting a new conversation. The reset process:

1. Triggers internal hooks (`triggerInternalHook`), allowing registered hooks (e.g., session-memory) to save context before reset
2. Clears Token metrics
3. Preserves per-session override options
4. If "bare reset" (no arguments), triggers greeting Prompt

Default reset trigger configuration is in `config/sessions/types.ts`:

```typescript
export const DEFAULT_RESET_TRIGGER = "/new";
export const DEFAULT_RESET_TRIGGERS = ["/new", "/reset"];
```

### `/compact` — Context Compression

`/compact` triggers the session context compression pipeline, optionally with compression instructions (e.g., `/compact focus on decisions`). This is a restricted command—only owners or authorized senders can execute it; unauthorized user requests are silently ignored and logged.

### `/bash` — Shell Command Execution

The `/bash` command allows direct Shell command execution on the host machine:

```typescript
defineChatCommand({
  key: "bash",
  description: "Run host shell commands (host-only).",
  textAlias: "/bash",
  scope: "text",        // Text mode only (security consideration, not registered as native command)
  category: "tools",
  args: [{ name: "command", type: "string", captureRemaining: true }],
});
```

`/bash` is intentionally limited to `text` scope—it won't appear in Telegram, Discord, or Slack native command menus, reducing accidental execution risk. Execution requires enabling `commands.bash=true` in configuration.

### Argument Parsing System

Chat commands support two argument parsing modes:

| Mode         | Description                         | Example                                   |
| ------------ | ----------------------------------- | ----------------------------------------- |
| `positional` | Parse arguments by position         | `/think medium` → `{ level: "medium" }`   |
| `none`       | No auto-parsing, command handles it | `/config set agents.defaults.model gpt-4` |

Argument definitions support rich types and constraints:

```typescript
type CommandArgDefinition = {
  name: string;
  description: string;
  type: "string" | "number" | "boolean";
  required?: boolean;
  choices?: CommandArgChoice[] | CommandArgChoicesProvider; // Static options or dynamic generation
  captureRemaining?: boolean;  // Capture all remaining text
};
```

The `choices` field can be a static array or a function—for example, `/think` option list is dynamically computed based on current model provider (different models support different thinking levels):

```typescript
args: [{
  name: "level",
  choices: ({ provider, model }) => listThinkingLevels(provider, model),
}],
```

### Native Platform Argument Menus

The `argsMenu` field controls whether argument selection menus are provided on native platforms. When set to `"auto"`, the framework auto-generates menus based on `choices` in `args`. Can also manually specify menu title and target argument:

```typescript
argsMenu: {
  arg: "action",
  title: "TTS Actions:\n• On – Enable TTS\n• Off – Disable TTS\n..."
},
```

### TUI Integration

TUI (Terminal User Interface) also integrates the chat command system. `src/tui/commands.ts` converts chat commands to TUI-supported format through `getSlashCommands()`:

```typescript
// src/tui/commands.ts
export function getSlashCommands(options: SlashCommandOptions = {}): SlashCommand[] {
  const commands: SlashCommand[] = [
    { name: "help", description: "Show slash command help" },
    // ... TUI-exclusive commands
  ];
  // Merge Gateway chat commands
  const gatewayCommands = options.cfg
    ? listChatCommandsForConfig(options.cfg)
    : listChatCommands();
  // ...
}
```

TUI displays command completion list when user types `/`, matching the native slash command experience.

***

## Section Summary

1. **Unified command registry**: All chat commands defined through `ChatCommandDefinition` with unique key, native name, text aliases, argument definitions, and scope; `assertCommandRegistry` ensures registry completeness and consistency
2. **Three scopes**: `text` (text messages only), `native` (native platforms only), `both` (both compatible); security-sensitive commands like `/bash` restricted to `text` scope
3. **Seven command categories**: session (session management), options (runtime options), status (status queries), management (system management), media (media), tools (tools), docks (channel switching), totaling 25+ built-in commands
4. **Dynamic command generation**: Channel Dock commands generated based on registered plugins; `/think` option list dynamically computed based on current model
5. **Caching + plugin awareness**: Command list uses singleton caching, auto-invalidates and rebuilds when plugin registry changes
6. **Permission control**: Most commands allow only owners and allowlist members; inline commands (e.g., `/status` in messages) preserved as plain text for unauthorized users
7. **Multi-platform adaptation**: Same command definitions adapt to WhatsApp text messages, Telegram/Discord/Slack native slash commands, and TUI terminal interface

***

> ### 🔬 Going Deeper: 33.4 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**33.4 Source Deep Dive: Two Command Trees and Startup-Speed Paranoia**](https://www.openclawbook.xyz/en/ch33-cli-tools/33.4-source-deep-dive-two-command-trees.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
