The Claw Code Command System

At the heart of Claw Code's interactive experience is its command system — a structured registry of slash commands that let developers control every aspect of an active agent session. Unlike ad-hoc text parsing, Claw Code treats commands as first-class entities with formal type definitions, source tracking, and categorization metadata. This design complements the tool system, which provides the agent's execution capabilities. This design ensures that the command surface is discoverable, extensible, and consistent across the Python and Rust layers of the framework.

Every command in Claw Code is represented by a CommandManifestEntry — a frozen dataclass containing a name (the slash command string) and a CommandSource enum that classifies how the command was introduced into the system. The three possible sources are: Builtin (shipped with the core framework and always available), InternalOnly (available only in development or debug builds), and FeatureGated (requires a specific feature flag to be enabled at runtime).

The CommandRegistry is the central data structure that holds all registered CommandManifestEntry objects. It is populated at startup from a combination of hardcoded definitions and dynamically loaded plugin manifests. The Python orchestration layer mirrors this registry from a JSON snapshot file, ensuring that the Python CLI and the Rust REPL always agree on which commands are available and how they behave. This mirroring strategy eliminates a common source of bugs in dual-runtime systems — command definition drift between layers.

Beyond individual entries, commands are further organized through a CommandGraph — a categorization layer that groups commands into builtins (core session management), plugin-like (extensible functionality contributed by optional modules), and skill-like (higher-order capabilities that compose multiple tools and commands). This three-tier categorization drives both the help output and the command-routing logic, ensuring that the agent can intelligently suggest relevant commands based on the current session context. For a broader view of how commands fit into the system, see the architecture overview.

Complete Claw Code Slash Command Reference

Claw Code ships with exactly 15 slash commands. Each command has a defined argument signature, a resume compatibility flag (whether it can be re-executed when resuming a saved session), and a specific function within the agent lifecycle. The following table provides the complete Claw Code command reference:

Command Arguments Resume? Description
/help none No Display help and available commands
/status none Yes Show current session status, turns, usage
/compact none Yes Compress conversation history
/model [model] No Switch or display current LLM model
/permissions [mode] No View or change permission mode
/clear [--confirm] Yes Clear conversation context
/cost none Yes Display token usage and cost breakdown
/resume <session-path> No Resume a previously saved session
/config [env|hooks|model] Yes View or modify runtime configuration
/memory none Yes Display agent memory state
/init none Yes Re-initialize project context
/diff none Yes Show uncommitted file changes
/version none Yes Display version information
/export [file] Yes Export conversation to file
/session [list|switch <id>] No Manage multiple sessions

Of the 15 total commands, 11 support resume — meaning they can be automatically re-executed when restoring a saved session. The four non-resumable commands (/help, /model, /permissions, /resume, and /session) are excluded because they either produce transient output, modify fundamental session parameters that should be set explicitly, or are themselves responsible for the resume mechanism.

Command Details

/help

Prints the full list of available slash commands, their argument signatures, and short descriptions. The output is generated dynamically from the CommandRegistry, so it always reflects the current set of enabled commands including any feature-gated or plugin-contributed entries. This is the recommended first command for new users exploring the Claw Code interface.

/status

Displays a summary of the current session state, including the number of conversation turns completed, the active LLM model, cumulative token usage, and whether compaction has been applied. Useful for monitoring long-running sessions and understanding resource consumption at a glance.

/compact

Triggers conversation history compression. When a session accumulates a large number of turns, the context window can become saturated. The /compact command summarizes older conversation history into a condensed representation, freeing context space for new interactions as part of the session management system while preserving the essential information the agent needs to maintain coherence. The compaction process preserves the most recent 4 messages verbatim and targets a maximum of 10,000 tokens for the compressed summary.

/model

When called without arguments, displays the currently active LLM model identifier. When called with a model name (e.g., /model claude-sonnet-4-20250514), switches the active model for subsequent turns. The model switch takes effect immediately and is reflected in /status output. This command is not resumable because model availability may change between sessions.

/permissions

Controls the agent's permission mode, which determines what operations the agent can perform autonomously. The three modes are: ReadOnly (the agent can only read files and display information), WorkspaceWrite (the agent can read and write files within the project directory), and DangerFullAccess (the agent can execute arbitrary shell commands and modify any file on the system). Defaults to WorkspaceWrite for safety.

/clear

Resets the conversation context, removing all previous messages and tool results from the active context window. Accepts an optional --confirm flag to skip the confirmation prompt. Unlike /compact, which preserves a summary, /clear provides a complete fresh start while maintaining the same session identity.

/cost

Provides a detailed breakdown of token usage and estimated cost for the current session. Shows input tokens, output tokens, cache read/write tokens, and the calculated cost based on the active model's pricing. The format_usd utility outputs costs in $X.XXXX format (four decimal places), providing precision even for sessions that consume relatively few tokens.

/resume

Loads a previously saved session from disk and restores the conversation state. Requires a <session-path> argument pointing to the saved session file. After loading, all resume-compatible commands from the original session are re-executed to rebuild the agent's context. This command cannot itself be resumed, as it is the mechanism that initiates the resume process.

/config

Provides access to runtime configuration settings. Subcommands include env (display environment variables), hooks (list registered hooks and their triggers), and model (show model configuration details). Without arguments, displays the full configuration summary.

/memory

Shows the current state of the agent's memory system, including session memory (current conversation), project memory (persistent per-project knowledge), and global memory (cross-project patterns). Displays memory utilization, stored entries, and the most recently accessed memory segments.

/init

Re-initializes the project context by re-scanning the working directory, reloading configuration files (including CLAUDE.md and .claude/ settings), and refreshing the tool registry. Useful after making changes to project structure or configuration files that the agent should pick up without starting a new session.

/diff

Displays uncommitted file changes in the current working directory, equivalent to running git diff plus git status. Shows both staged and unstaged modifications, providing a quick way to review the agent's file modifications before committing.

/version

Prints the current Claw Code version string, including the build hash and the active runtime (Python, Rust, or hybrid). Useful for bug reports and ensuring compatibility with documentation.

/export

Exports the current conversation to a file. Without arguments, writes to a timestamped file in the current directory. With a [file] argument, writes to the specified path. The export includes all messages, tool calls, and results in a structured format suitable for review, sharing, or archival.

/session

Manages multiple concurrent sessions. /session list shows all active and saved sessions with their identifiers, turn counts, and last-active timestamps. /session switch <id> switches to a different session, preserving the current session's state. This command is not resumable because session management is inherently a top-level navigation operation.

Command Graph: Claw Code Categorization System

Beyond the flat registry, Claw Code organizes its commands through a CommandGraph — a frozen dataclass that provides a structured, categorical view of the entire command surface. The CommandGraph is the primary mechanism through which the framework understands command relationships, generates documentation, and powers the /help output.

The CommandGraph dataclass defines three fields, each a tuple of PortingModule references:

# CommandGraph definition (frozen dataclass) @dataclass(frozen=True) class CommandGraph: builtins: tuple[PortingModule, ...] plugin_like: tuple[PortingModule, ...] skill_like: tuple[PortingModule, ...] def flattened(self) -> list[PortingModule]: """Return all modules across all categories.""" return [*self.builtins, *self.plugin_like, *self.skill_like] def as_markdown(self) -> str: """Render the command graph as formatted Markdown.""" sections = [] for label, group in [ ("Builtins", self.builtins), ("Plugin-like", self.plugin_like), ("Skill-like", self.skill_like), ]: sections.append(f"## {label}\n") for mod in group: sections.append(f"- {mod.name}") return "\n".join(sections)

The flattened() method returns all commands across all categories as a single list, useful for iteration, validation, and search operations. The as_markdown() method generates a human-readable markdown representation of the command graph, used by the /help command and documentation generation tooling to produce consistent output.

The graph is constructed by the build_command_graph() factory function, which reads the CommandRegistry, inspects each entry's source and metadata, and assigns it to the appropriate category. This function runs once at startup and the resulting graph is cached as an immutable frozen dataclass for the lifetime of the session, ensuring zero allocation overhead on subsequent lookups.

Claw Code CLI Subcommands

Beyond the 15 interactive slash commands, the Claw Code Python CLI (main.py) exposes 27 additional subcommands for development, debugging, and operational tasks. These subcommands are invoked directly from the shell (e.g., python main.py summary) rather than from within an active agent session. Together with the slash commands, they form the complete Claw Code command surface of 42 distinct operations.

summary

Generate a high-level summary of the current project state, including file counts, language breakdown, and detected frameworks.

manifest

Print the full command manifest as JSON, listing every registered command with its source, arguments, and resume compatibility flag.

parity-audit

Run a parity check between the Python command registry and the Rust command registry, reporting any discrepancies in command availability or behavior across the two runtimes.

setup-report

Generate a diagnostic report of the current installation, including Python version, Rust toolchain status, installed dependencies, and configuration file locations.

command-graph

Print the CommandGraph categorization, showing which commands are classified as builtins, plugin-like, or skill-like with their full metadata.

tool-pool

Display the current tool pool — the set of tools available to the agent in the active configuration, including any permission restrictions and gating status.

bootstrap-graph

Visualize the bootstrap dependency graph, showing the initialization order of subsystems during agent startup and the edges between dependent modules.

subsystems

List all registered subsystems with their initialization status, dependency chains, and health indicators for operational monitoring.

commands

List all available slash commands in a compact table format, equivalent to running /help outside of an active session. Useful for scripting and documentation generation.

tools

List all registered tools with their permission requirements, argument schemas, and current enabled/disabled status.

route

Test the command routing logic by providing a sample input string and displaying which command or tool would be selected by the dispatch router.

bootstrap

Run the full bootstrap sequence without entering the interactive REPL, useful for verifying that initialization completes successfully in CI environments.

turn-loop

Execute a single turn of the agent loop with a provided prompt, returning the result without entering interactive mode. Designed for programmatic agent invocation via the query engine.

flush-transcript

Write the current session transcript to disk, flushing any buffered messages that have not yet been persisted to the session file.

load-session

Load a saved session file and display its contents without entering resume mode. Useful for inspecting session state and debugging persistence issues.

remote-mode

Start the agent in remote mode, connecting to a remote compute backend for model execution while running the REPL locally for reduced latency.

ssh-mode

Start the agent with SSH tunneling, allowing secure remote access to the agent session from another machine over an encrypted channel.

teleport-mode

Transfer an active session to a different machine, preserving full conversation state, context, and tool registrations across the network hop.

direct-connect-mode

Establish a direct peer-to-peer connection to another Claw Code instance for collaborative multi-agent operation with shared context.

deep-link-mode

Start the agent from a deep link URL, pre-populating the session with context, configuration, and initial prompts encoded in the link parameters.

show-command

Display detailed information about a specific slash command, including its source, argument schema, resume compatibility, and implementation location in the codebase.

show-tool

Display detailed information about a specific tool, including its permission requirements, input/output schema, and usage examples for integration testing.

exec-command

Execute a slash command programmatically from the shell, bypassing the interactive REPL. Returns structured output suitable for scripting and CI/CD pipelines.

exec-tool

Execute a tool directly from the shell with JSON-encoded arguments, returning the tool result to stdout. Designed for testing and automation workflows.

These 27 subcommands — combined with the 15 interactive slash commands — give Claw Code a total command surface of 42 distinct operations, covering everything from interactive session management to programmatic automation, remote operation modes, and comprehensive system introspection.

Claw Code Command Execution Pipeline

When a user types a slash command in the Claw Code REPL, it passes through a multi-stage execution pipeline that spans both the Python orchestration layer and the Rust runtime core. Understanding this pipeline is essential for developers extending the command system or debugging unexpected command behavior.

The pipeline begins with the CommandExecution dataclass, which encapsulates the full lifecycle state of a command in flight:

@dataclass class CommandExecution: name: str # The slash command name (e.g., "compact") source_hint: CommandSource # Origin: Builtin, InternalOnly, FeatureGated prompt: str # The full user input string handled: bool # Whether execution completed successfully message: str # Result message or error description

The execution flow proceeds through five stages. First, the REPL input parser detects the leading / character and extracts the command name and any trailing arguments. Second, the CommandRegistry is consulted to verify the command exists and retrieve its CommandManifestEntry. If the command is not found, an error message is displayed and no CommandExecution is created.

Third, for commands handled in the Python layer, execution is dispatched directly to the corresponding handler function via execute_command(name, prompt). For commands that require Rust runtime support — such as /compact, which involves memory-intensive context manipulation, or /diff, which interfaces with the Git subsystem — the execution is forwarded to the Rust CLI binary (rusty-claude-cli) via an inter-process call. The Rust REPL handles these commands through its handle_slash_command function, which receives the current session context and compaction state as parameters.

Fourth, after execution completes, the handled flag is set to true and the message field is populated with the result. Finally, the REPL displays the message to the user and records the command in the session transcript for potential future resume.

Command Execution Pipeline
===========================

User Input: "/compact"
     |
     v
[REPL Input Parser] ── detect "/" prefix, extract name + args
     |
     v
[CommandRegistry] ── lookup "compact" -> CommandManifestEntry
     |
     v
[CommandExecution] ── create: name="compact", source=Builtin
     |
     v
[Dispatch Router] ── Python handler or Rust delegation?
     |                    |
     |                    v
     |            [Rust: handle_slash_command()]
     |                    |
     v                    v
[Python Handler]   [Rust Handler]
     |                    |
     v                    v
[Result] ── handled=true, message="Context compacted."
     |
     v
[Session Transcript] ── record for resume compatibility

This layered dispatch architecture ensures that performance-critical operations remain in Rust while complex orchestration logic stays in Python. The inter-process boundary is crossed only when necessary, minimizing overhead for commands that can be handled entirely within a single runtime.

Session Resume and Claw Code Command Persistence

One of the most powerful features of the Claw Code command system is its resume capability — the ability to save a session to disk and later restore it with full context reconstruction. This feature is critical for long-running development tasks that span multiple terminal sessions, workdays, or even machines.

The resume mechanism is built on the resume_session(path, commands) function, which takes two arguments: a file path pointing to the saved session file, and the current CommandRegistry (used to validate that all commands from the saved session are still available in the current installation). This validation step prevents resume failures caused by version mismatches or removed commands.

When a session is resumed, the function loads the serialized session state and iterates through the transcript of previously executed commands. For each command marked as resume-compatible, the function re-executes it against the current session context. This means that a resumed session will re-apply /compact to restore compressed context, re-display /status to verify state, reload /config settings, and re-initialize project context via /init — effectively reconstructing the agent's full working state from the command history.

The session state itself is tracked by the SessionState dataclass, which records four key fields:

@dataclass class SessionState: turns: int compacted_messages: list[str] last_model: str last_usage: UsageSnapshot def resume_session( path: Path, commands: CommandRegistry ) -> SessionState: """Load a saved session and re-execute resume-compatible commands.""" state = load_session_file(path) for cmd in state.transcript: if cmd.resumable and cmd.name in commands: execute_command(cmd, commands) return state

The four non-resumable commands are excluded for deliberate reasons: /help produces transient display output with no state effect; /model could fail if the previously selected model is no longer available or could incur unexpected costs; /permissions could inadvertently escalate privileges on resume without the user's explicit consent; /resume cannot resume itself (it is the entry point for the resume process); and /session operates at a level above individual sessions. This 11-of-15 resume ratio reflects a careful design balance between convenience and safety.

Session files are stored in a configurable directory (defaulting to .claude/sessions/) and use a JSON-based serialization format. Each file contains the full SessionState, the command transcript with timestamps, and metadata including the working directory and Claw Code version at the time of save. This comprehensive serialization ensures that sessions can be safely moved between machines or shared with collaborators, provided the same project context is available at the destination.

Resume Best Practice

When resuming a session that was saved with a specific model (e.g., claude-sonnet-4-20250514), the resume process does not automatically switch to that model. Use /model after resuming to explicitly set the desired model. This is by design — model availability and pricing may have changed between sessions, and automatic switching could lead to unexpected costs or failures.