Introduction to Clawdius

Clawdius is a high-assurance AI coding assistant built in Rust. It combines the power of large language models with formal verification, secure sandboxing, and enterprise-grade features to provide a trustworthy development companion.

Why Clawdius?

Security First

Clawdius was designed from the ground up with security as a primary concern:

  • 5 Sandbox Backends (+ 2 Planned): From lightweight WASM to hardware-isolated Firecracker microVMs
  • 318 Formal Verification Theorems: Mathematically proven correctness for critical operations
  • Enterprise SSO: SAML 2.0, OIDC, Okta, Azure AD, and GitHub integration
  • Comprehensive Audit Logging: File, SQLite, Elasticsearch, webhook, and memory backends

Native Performance

Built in Rust for maximum performance:

  • <3ms cold boot: Faster than any competitor
  • Zero-copy streaming: Efficient real-time output
  • Memory-efficient: Minimal resource footprint
  • Cross-platform: Linux, macOS, Windows support

Extensible Architecture

  • Plugin System: WASM-based plugins with 26 hook types
  • Multiple LLM Providers: Anthropic, OpenAI, Google Gemini, xAI (Grok), Mistral, DeepSeek, OpenRouter, Ollama, Z.AI
  • Graph-RAG: Enhanced context through code graph analysis
  • Timeline & Checkpoints: Full session history and rollback

Feature Comparison

FeatureClawdiusCompetitors
Sandbox Backends5 (+ 2 planned)1-3
Formal Verification318 theoremsNone
Cold Boot Time<20ms100-500ms
Plugin SystemWASM + 26 hooksLimited or None
Enterprise SSOFull (SAML, OIDC)Limited
Audit Logging5 backendsBasic or None
Graph-RAGBuilt-inExternal add-on
LSP ServerBuilt-in (tower-lsp)External add-on
Self-HostedFull supportLimited

Quick Start

# Install from source (crate not yet published to crates.io)
cargo install --git https://github.com/WyattAu/clawdius

# Or build from source
git clone https://github.com/WyattAu/clawdius
cd clawdius
cargo build --release

# Run the interactive setup wizard
clawdius setup

# Or manually set your API key
clawdius config set api_key YOUR_ANTHROPIC_API_KEY

# Start chatting
clawdius chat

Interactive Setup Wizard

The interactive setup wizard guides you through:

  • Provider Selection: Choose from Anthropic, OpenAI, Google Gemini, xAI (Grok), Mistral, DeepSeek, OpenRouter, Ollama, Z.AI
  • API Key Configuration: Secure storage using your system keyring
  • Settings Presets: Balanced, Security-focused, Performance-optimized, or Development mode
  • Ollama Connectivity Check: Automatic TCP verification for local LLMs
# First-time setup
clawdius setup

# Quick setup with pre-selected provider
clawdius setup --quick --provider anthropic

Architecture Overview

+-----------------------------------------------------------------------------------------+
|                                  Clawdius CLI                                        |
+-----------------------------------------------------------------------------------------+
|  +-------------------------+  +-------------------------+  +-------------------------+  |
|  |       Session           |  |       Context           |  |       Timeline          |  |
|  |       Manager           |  |       Builder           |  |    & Checkpoints        |  |
|  +-------------------------+  +-------------------------+  +-------------------------+  |
+-----------------------------------------------------------------------------------------+
|  +-------------------------+  +-------------------------+  +-------------------------+  |
|  |        LLM              |  |       Graph-            |  |       Plugin            |  |
|  |      Providers          |  |         RAG             |  |       System            |  |
|  +-------------------------+  +-------------------------+  +-------------------------+  |
+-----------------------------------------------------------------------------------------+
|  +-------------------------+  +-------------------------+  +-------------------------+  |
|  |       Sandbox           |  |        Tool             |  |     Enterprise          |  |
|  |      Executors          |  |       Runner            |  |      Features           |  |
|  +-------------------------+  +-------------------------+  +-------------------------+  |
+-----------------------------------------------------------------------------------------+

What's Next?

Getting Help

License

Clawdius is licensed under the Apache 2.0 License.

Installation

Clawdius can be installed in several ways depending on your platform and preferences.

Quick Install

Linux and macOS

curl -fsSL https://clawdius.dev/install.sh | sh

Windows (PowerShell)

irm https://clawdius.dev/install.ps1 | iex

Package Managers

Homebrew (macOS/Linux)

brew tap clawdius/tap
brew install clawdius

Cargo (All Platforms)

cargo install clawdius

Arch Linux (AUR)

yay -S clawdius-bin
# Or build from source:
yay -S clawdius-git

Nix

# Using nixpkgs
nix-env -iA nixpkgs.clawdius

# Using flake
nix profile install github:WyattAu/clawdius

Pre-built Binaries

Download pre-built binaries from GitHub Releases:

PlatformArchitectureDownload
Linuxx86_64clawdius-linux-x86_64.tar.gz
Linuxaarch64clawdius-linux-aarch64.tar.gz
macOSx86_64clawdius-darwin-x86_64.tar.gz
macOSaarch64clawdius-darwin-aarch64.tar.gz
Windowsx86_64clawdius-windows-x86_64.zip

Manual Installation

# Download and extract
curl -LO https://github.com/WyattAu/clawdius/releases/download/v1.0.0/clawdius-linux-x86_64.tar.gz
tar xzf clawdius-linux-x86_64.tar.gz

# Move to PATH
sudo mv clawdius /usr/local/bin/

# Verify installation
clawdius --version

Build from Source

Prerequisites

  • Rust 1.92+ (recommended: latest stable)
  • C compiler (gcc, clang, or MSVC)
  • pkg-config (Linux)

Build Steps

# Clone the repository
git clone https://github.com/WyattAu/clawdius.git
cd clawdius

# Build release binary
cargo build --release

# Install locally
cargo install --path crates/clawdius

# Or copy binary manually
cp target/release/clawdius /usr/local/bin/

Build Features

Clawdius supports optional features:

# Enable all features
cargo build --release --all-features

# Enable only enterprise features
cargo build --release --features enterprise

# Minimal build (no plugins, basic sandbox)
cargo build --release --no-default-features
FeatureDescription
defaultCore features, WASM sandbox, basic tools
enterpriseSSO, audit logging, compliance
pluginsPlugin system with WASM runtime
all-sandboxesAll available sandbox backends
self-hostedSelf-hosted LLM support

Docker

# Pull official image
docker pull clawdius/clawdius:latest

# Run with current directory mounted
docker run -it --rm \
  -v $(pwd):/workspace \
  -v ~/.config/clawdius:/root/.config/clawdius \
  clawdius/clawdius:latest chat

Docker Compose

version: '3.8'
services:
  clawdius:
    image: clawdius/clawdius:latest
    volumes:
      - ./:/workspace
      - clawdius-config:/root/.config/clawdius
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
volumes:
  clawdius-config:

Verification

After installation, verify everything works:

# Check version
clawdius --version

# Run the interactive setup wizard (recommended for first-time users)
clawdius setup

# Or run diagnostics
clawdius doctor

# Quick test (requires API key)
clawdius chat --message "Hello, Clawdius!"

First-Time Setup

New in v1.0.0-rc.2: Use the interactive setup wizard to configure Clawdius:

clawdius setup

The wizard will guide you through:

  1. Provider Selection - Choose your LLM provider (Anthropic, OpenAI, Ollama, Zhipu AI)
  2. API Key Configuration - Enter and securely store your API key
  3. Settings Preset - Choose a configuration preset:
    • Balanced: Good defaults for most users
    • Security: Maximum sandboxing and audit logging
    • Performance: Optimized for speed
    • Development: Verbose logging and debugging features

Quick Setup Options

# Skip welcome screen
clawdius setup --quick

# Pre-select provider
clawdius setup --provider anthropic
clawdius setup --provider ollama  # For local LLMs

Shell Completion

Enable shell completion for your shell:

Bash

clawdius completion bash > /etc/bash_completion.d/clawdius
# Or for user-only:
clawdius completion bash > ~/.local/share/bash-completion/completions/clawdius

Zsh

clawdius completion zsh > "${fpath[1]}/_clawdius"

Fish

clawdius completion fish > ~/.config/fish/completions/clawdius.fish

PowerShell

clawdius completion powershell | Out-String | Invoke-Expression

Next Steps

Configuration

Clawdius is highly configurable. This guide covers the essential configuration options.

New in v1.0.0-rc.2: Use the interactive setup wizard for first-time configuration:

clawdius setup

The wizard provides:

  • Guided provider selection with descriptions
  • Secure API key storage using your system keyring
  • Preset configurations for common use cases
  • Connectivity verification for local LLMs (Ollama)
  • Quick start examples after setup completes

Setup Presets

PresetUse CaseKey Settings
BalancedGeneral developmentStandard sandboxing, moderate caching
SecurityProduction/sensitive codeMaximum sandboxing, full audit logging
PerformanceSpeed-critical workflowsAggressive caching, streaming enabled
DevelopmentPlugin/core developmentVerbose logging, debug features

Configuration File Location

Clawdius looks for configuration in the following locations (in order):

  1. CLAWDIUS_CONFIG environment variable (if set)
  2. ./.clawdius/config.toml (project-local)
  3. ~/.config/clawdius/config.toml (user-level)
  4. /etc/clawdius/config.toml (system-wide)

Quick Setup

Set API Key

# Using CLI
clawdius config set api_key sk-ant-xxxxx
# Or set environment variable
export ANTHROPIC_API_KEY=sk-ant-xxxxx

Set Default Provider

clawdius config set provider anthropic

Configuration File

Create ~/.config/clawdius/config.toml:

# General Settings
[general]
provider = "anthropic"
model = "claude-sonnet-4-20250514"
max_tokens = 4096
temperature = 0.7

# API Keys (stored securely in keyring)
# Use: clawdius config set api_key YOUR_KEY

# Session Settings
[session]
auto_save = true
max_history = 1000
compaction_threshold = 50000

# Sandbox Settings
[sandbox]
default_tier = "standard"
allow_network = false
allowed_paths = ["~/projects"]

# Output Settings
[output]
format = "streaming"
theme = "dark"
show_token_count = true

# Graph-RAG Settings
[graph_rag]
enabled = true
max_files = 10000
embedding_model = "text-embedding-3-small"

# Plugin Settings
[plugins]
enabled = true
auto_update = false
trusted_sources = ["https://plugins.clawdius.dev"]

# Telemetry
[telemetry]
enabled = false
# Set to true to help improve Clawdius

Environment Variables

VariableDescriptionDefault
ANTHROPIC_API_KEYAnthropic API key-
OPENAI_API_KEYOpenAI API key-
CLAWDIUS_CONFIGCustom config path-
CLAWDIUS_LOGLog level (debug, info, warn)info
CLAWDIUS_CACHE_DIRCache directory~/.cache/clawdius
CLAWDIUS_DATA_DIRData directory~/.local/share/clawdius

Provider Configuration

Anthropic Claude

[providers.anthropic]
api_key_env = "ANTHROPIC_API_KEY"
model = "claude-sonnet-4-20250514"
base_url = "https://api.anthropic.com"

[providers.anthropic.options]
max_tokens = 4096
temperature = 0.7

OpenAI

[providers.openai]
api_key_env = "OPENAI_API_KEY"
model = "gpt-4o"

[providers.openai.options]
max_tokens = 4096
temperature = 0.7

Ollama (Local)

[providers.ollama]
base_url = "http://localhost:11434"
model = "llama3.2"

[providers.ollama.options]
num_ctx = 4096
temperature = 0.7

Custom Provider

[providers.custom]
name = "my-provider"
base_url = "https://api.example.com/v1"
api_key_env = "MY_API_KEY"
model = "my-model"

[providers.custom.headers]
X-Custom-Header = "value"

Sandbox Configuration

Sandbox Tiers

TierIsolationUse Case
minimalNoneTrusted code only
standardWASM + seccompNormal development
hardenedBubblewrapUntrusted code
containerDocker/PodmanStrong isolation
gvisorgVisor runscStrong isolation
firecrackerMicroVMMaximum isolation
[sandbox]
default_tier = "standard"

# Per-tier configuration
[sandbox.tiers.standard]
backend = "wasm"
memory_limit_mb = 512
cpu_limit_percent = 50

[sandbox.tiers.hardened]
backend = "bubblewrap"
network = false
filesystem = "readonly"

[sandbox.tiers.container]
backend = "docker"
image = "clawdius/sandbox:latest"

Path Allowlisting

[sandbox]
allowed_paths = [
    "~/projects",
    "~/src",
    "/tmp/clawdius"
]

# Read-only paths
read_only_paths = [
    "/usr/include",
    "~/.cargo/registry"
]

# Denied paths (always blocked)
denied_paths = [
    "~/.ssh",
    "~/.gnupg",
    "~/.config/clawdius/keys"
]

Session Configuration

[session]
# Auto-save sessions
auto_save = true
auto_save_interval_secs = 60

# History limits
max_history = 1000
max_context_tokens = 100000

# Compaction settings
compaction_threshold = 50000
compaction_strategy = "sliding_window"  # or "summarize"

Output Configuration

[output]
# Output format: streaming, batch, json
format = "streaming"

# Theme: dark, light, ansi
theme = "dark"

# Display options
show_token_count = true
show_timing = false
show_model = true

# Markdown rendering
markdown = true
code_highlighting = true

Plugin Configuration

[plugins]
enabled = true
directory = "~/.local/share/clawdius/plugins"
auto_update = false

# Trusted plugin sources
trusted_sources = [
    "https://plugins.clawdius.dev"
]

# Disabled plugins (by ID)
disabled = []

# Plugin-specific settings
[plugins.settings."my-plugin"]
option1 = "value1"
option2 = true

Enterprise Configuration

SSO

[enterprise.sso]
enabled = true
provider = "okta"  # okta, azure, github, custom

[enterprise.sso.okta]
domain = "your-company.okta.com"
client_id = "your-client-id"

[enterprise.sso.azure]
tenant_id = "your-tenant-id"
client_id = "your-client-id"

Audit Logging

[enterprise.audit]
enabled = true
backend = "sqlite"  # sqlite, elasticsearch, webhook

[enterprise.audit.sqlite]
path = "/var/log/clawdius/audit.db"

[enterprise.audit.elasticsearch]
url = "https://elasticsearch.example.com"
index = "clawdius-audit"

CLI Commands

# View current configuration
clawdius config list

# Set a value
clawdius config set <key> <value>

# Get a value
clawdius config get <key>

# Edit configuration file
clawdius config edit

# Reset to defaults
clawdius config reset

Next Steps

First Chat

Now that Clawdius is installed and configured, let's start your first conversation.

Starting a Chat Session

Interactive Mode

clawdius chat

This opens an interactive REPL where you can have a conversation:

+-----------------------------------------------------------------+
|  Clawdius v1.0.0 - High-Assurance AI Coding Assistant |
|  Provider: Anthropic (claude-sonnet-4-20250514) |
|  Sandbox: standard (WASM) |
+-----------------------------------------------------------------+

You: Hello! Can you help me write a Rust function to parse JSON?

Clawdius: I'd be happy to help! Here's a function that parses JSON using
serde_json:

```rust
use serde_json::Value;

fn parse_json(input: &str) -> Result<Value, serde_json::Error> {
    serde_json::from_str(input)
}

You can use it like this: ...


### One-shot Mode

For quick questions:

```bash
clawdius chat --message "What is the difference between Vec and VecDeque in Rust?"

With File Context

# Include files for context
clawdius chat --file src/main.rs --file src/lib.rs

# Or include entire directory
clawdius chat --dir src/

Basic Commands

Inside the chat session:

CommandDescription
/helpShow available commands
/clearClear conversation history
/save [name]Save current session
/load <name>Load a saved session
/model <name>Switch model
/mode <mode>Switch mode (code, architect, review)
/checkpointCreate a checkpoint
/undoUndo last action
/redoRedo last undone action
/exitExit the session

Using @mentions

Clawdius supports @mentions to reference files, directories, or previous context:

You: Please review @src/main.rs and suggest improvements

You: What patterns are used in @src/ directory?

You: Based on our @previous discussion, implement the feature

You: Use @commit:abc123 as reference

Available Mentions

MentionDescription
@file.rsReference a file
@directory/Reference all files in directory
@previousReference previous context
@commit:hashReference a git commit
@issue:123Reference a GitHub issue
@pr:456Reference a GitHub PR
@url:https://...Reference a URL

Modes

Clawdius has different modes optimized for different tasks:

Code Mode (default)

Optimized for writing and editing code:

clawdius chat --mode code

Architect Mode

High-level system design and planning:

clawdius chat --mode architect

Review Mode

Code review and quality analysis:

clawdius chat --mode review

Debug Mode

Debugging and troubleshooting:

clawdius chat --mode debug

File Operations

Clawdius can read, create, edit, and delete files:

You: Read the file src/main.rs and explain what it does

Clawdius: I'll read the file...

[Reads src/main.rs]

This file contains the main entry point for your application...

You: Create a new file src/utils.rs with helper functions

Clawdius: I'll create src/utils.rs with some utility functions...

[Creates src/utils.rs]

Created src/utils.rs with the following helper functions:
- `truncate_string` - Truncates a string to max length
- `format_bytes` - Formats bytes as human-readable string
...

You: Add a function to validate email addresses in src/utils.rs

Clawdius: I'll add an email validation function...

[Edits src/utils.rs]

Added `validate_email` function at line 45.

Git Operations

Clawdius can interact with git:

You: What changes have been made since the last commit?

Clawdius: I'll check the git status...

[Runs git status and git diff]

Modified files:
- src/main.rs (3 additions, 1 deletion)
- src/utils.rs (15 additions)

You: Commit these changes with a descriptive message

Clawdius: I'll commit these changes...

[Runs git add and git commit]

Committed: "Add utility functions and update main"
Commit hash: abc1234

Checkpoints and Undo

Clawdius tracks all changes and allows undo/redo:

You: /checkpoint

Clawdius: Created checkpoint "before-refactor" at 2024-01-15 10:30:00

You: Refactor the authentication module

Clawdius: I'll refactor the authentication module...

[Refactors auth module]

You: Actually, let me undo that

Clawdius: Undid the refactoring changes. Restored to checkpoint "before-refactor"

You: /redo

Clawdius: Redid the refactoring changes.

Session Management

Save Session

You: /save auth-feature

Clawdius: Session saved as "auth-feature"

Load Session

You: /load auth-feature

Clawdius: Loaded session "auth-feature" from 2024-01-15 10:30:00
Restored context: 5 files, 12 messages

List Sessions

clawdius session list

Export Session

clawdius session export auth-feature --format markdown

Tips for Effective Chats

  1. Be specific: Provide context and clarify your requirements
  2. Use @mentions: Reference relevant files and context
  3. Use checkpoints: Create checkpoints before major changes
  4. Review changes: Always review code changes before applying
  5. Iterate: Start simple and refine through conversation

Next Steps

  • Basic Usage - Learn more about daily workflows
  • Tools - Understand available tools
  • Modes - Deep dive into different modes

Basic Usage

This page covers common CLI patterns for day-to-day use of Clawdius.

Chatting with Clawdius

Interactive Chat

Start an interactive session with the default provider (Anthropic):

clawdius chat

The interactive mode supports multi-turn conversation. Type your message and press Enter. Use Ctrl+C to exit.

Single-Shot Messages

Pass a message directly on the command line:

clawdius chat "Explain this codebase"
clawdius chat "Write tests for src/lib.rs"

Composing Long Prompts

Open your system editor to compose a message:

clawdius chat --editor
clawdius chat --editor --extension rs

Piping from Stdin

echo "Explain this function" | clawdius chat -
cat error.log | clawdius chat "What caused this error?"

Selecting Providers and Models

Override the default provider and model for any command:

clawdius chat "Hello" --provider openai --model gpt-4o
clawdius chat "Hello" --provider anthropic --model claude-sonnet-4-20250514
clawdius chat "Hello" --provider ollama --model llama3.2
clawdius chat "Hello" --provider deepseek
clawdius chat "Hello" --provider zai

Agent Modes

Clawdius ships with built-in agent modes that change the system prompt and tool behavior:

ModePurpose
codeDefault coding assistant (default)
architectHigh-level system design
askQ&A without code execution
debugDebugging and error diagnosis
reviewCode review
refactorRefactoring guidance
testTest generation
autoFully autonomous execution
clawdius chat --mode architect "Design a microservice for auth"
clawdius chat --mode debug "Why is this test failing?"
clawdius chat --mode review "Review src/main.rs"
clawdius chat --mode auto "Fix the failing CI pipeline"

Session Management

Continuing a Session

Resume a previous conversation by session ID:

clawdius chat "Continue where we left off" --session abc123

Listing Sessions

clawdius sessions
clawdius sessions --search "error handling"

Deleting a Session

clawdius sessions --delete abc123

Autonomous Mode

Run tasks without human interaction:

clawdius auto "fix failing tests" --run-tests --fail-on-test-failure
clawdius auto "implement user auth" --auto-commit
clawdius auto "resolve lint errors" --output-format json

The --auto-approve flag on chat enables autonomous tool execution within interactive mode:

clawdius chat --auto-approve "Refactor this module"

Code Generation

Generate code with different strategies:

# Single-pass generation (fastest)
clawdius generate "create REST API handlers"

# Iterative generation with refinement
clawdius generate "add validation" --mode iterative --max-iterations 5

# Agent mode (plan, execute, verify)
clawdius generate "implement feature X" --mode agent

# Target specific files
clawdius generate "add error handling" --files src/api.rs,src/lib.rs

# Dry run (preview only)
clawdius generate "refactor database layer" --dry-run

Git Integration

AI-Generated Commits

# Stage all and generate commit message
clawdius git commit

# Stage specific files
clawdius git commit src/lib.rs src/config.rs

# Provide a message hint
clawdius git commit -m "fix: resolve null pointer in parser"

Viewing Diffs

clawdius git diff
clawdius git diff --staged
clawdius git diff --file src/lib.rs

Git Status

clawdius git status

Agentic Sprint

Run a multi-phase sprint (think, plan, build, review, test, ship, reflect):

clawdius sprint "implement user authentication" --max-iterations 3
clawdius sprint "add search feature" --real-execution --auto-approve

Output Formats

All commands support JSON output for scripting:

clawdius chat "Analyze this code" -f json
clawdius sessions -f json
clawdius metrics -f json -o metrics.json

Stream JSON for real-time processing:

clawdius chat -f stream-json

Global Flags

FlagShortDescription
--no-tui-nRun without TUI (headless mode)
--cwd-wWorking directory
--output-format-fOutput format: text, json, stream-json
--quiet-qSuppress progress indicators
--config-CPath to config file
--lang-LOutput language (en, zh, ja, ko, de, fr, es, it, pt, ru)

Quick Reference

# Daily workflow
clawdius chat                              # Start interactive session
clawdius chat "question" --provider openai  # Quick question
clawdius git commit                        # Commit with AI message
clawdius sessions                          # List sessions
clawdius checkpoint create "milestone"     # Save state
clawdius auto "task" --run-tests           # Autonomous task
clawdius metrics                           # Check performance

Migrating from Claw Code

Clawdius provides a compatible CLI experience with significantly stronger security, formal verification, and multi-provider support.

Why Migrate

FeatureClaw CodeClawdius
LLM Providers2 (Anthropic, xAI)9 (Anthropic, OpenAI, Gemini, xAI, Mistral, DeepSeek, Ollama, ZAI, OpenRouter)
SandboxingContainer detection5 backends (WASM, filtered, bubblewrap, container, sandbox-exec)
Formal VerificationNone209 Lean4 theorems
Open SourceMITApache 2.0
EnterpriseNoneSSO, audit logging, compliance
MessagingNone9 platform adapters
Tool CallingLimited8 providers with tool support

Quick Start

1. Install Clawdius

cargo install --locked clawdius

2. Copy Your Configuration

Claw Code uses ~/.claude/ for settings. Clawdius uses ~/.config/clawdius/:

# Your existing API keys work with Clawdius
export ANTHROPIC_API_KEY="sk-ant-..."   # Claude Code's key works directly
export OPENAI_API_KEY="sk-..."          # If you added OpenAI
export XAI_API_KEY="xai-..."            # Claw Code's key works directly

3. Configure Clawdius

# Interactive setup wizard
clawdius setup

# Or create config manually
mkdir -p ~/.config/clawdius
cat > ~/.config/clawdius/config.toml << 'EOF'
[llm]
default_provider = "anthropic"

[llm.anthropic]
model = "claude-sonnet-4-20250514"
api_key_env = "ANTHROPIC_API_KEY"
EOF

4. Verify

clawdius chat "Hello from Clawdius" --provider anthropic

Command Mapping

Claw CodeClawdiusNotes
claude "prompt"clawdius chat "prompt"Different subcommand
claude --model MODELclawdius chat -m MODELSame model selection
claude --allowedToolsclawdius chat --toolsTools enabled by default
claude configclawdius configDifferent config format (TOML)
claude mcpclawdius mcpBoth support MCP

Configuration Differences

Provider Configuration

Claw Code:

// ~/.claude/settings.json
{
  "model": "claude-sonnet-4-20250514",
  "apiKeyHelper": "environment"
}

Clawdius:

# ~/.config/clawdius/config.toml
[llm]
default_provider = "anthropic"

[llm.anthropic]
model = "claude-sonnet-4-20250514"
api_key_env = "ANTHROPIC_API_KEY"

Multi-Provider (Clawdius Advantage)

[llm]
default_provider = "anthropic"

[llm.openai]
model = "gpt-4o"
api_key_env = "OPENAI_API_KEY"

[llm.google]
model = "gemini-2.5-flash"
api_key_env = "GOOGLE_API_KEY"

[llm.xai]
model = "grok-3"
api_key_env = "XAI_API_KEY"

[llm.ollama]
model = "llama3.2"
base_url = "http://localhost:11434"

Tool Calling

Clawdius supports tool calling across 8 providers. Enable in your mode config:

[modes.code]
tools = true

Tools work with any provider that supports function calling (Anthropic, OpenAI, Google, xAI, Mistral).

What You Keep

  • All API keys (environment variables work identically)
  • Your project files (Clawdius reads from the same working directory)
  • Git integration (Clawdius has full git support)
  • Markdown formatting (both use markdown for code blocks)

What Changes

  • Config file format: JSON -> TOML
  • Config location: ~/.claude/ -> ~/.config/clawdius/
  • CLI entry point: claude -> clawdius chat
  • Additional security features are enabled by default (sandboxing, command filtering)

Troubleshooting

"Config not found"

# Clawdius uses a different config path
ls ~/.config/clawdius/config.toml
clawdius config --show

"Provider not found"

Clawdius uses different provider identifiers. Check available providers:

clawdius config --show

"Tools not working"

Ensure tools are enabled in your mode:

clawdius modes
clawdius mode code --tools on

Architecture Overview

Clawdius is a Rust monorepo with multiple crates, organized around a zero-trust security model and a 24-phase R&D lifecycle engine.

Monorepo Structure

clawdius/
├── crates/
│   ├── clawdius/              # CLI binary
│   ├── clawdius-core/         # Core library
│   ├── clawdius-code/         # VSCode extension helper
│   ├── clawdius-gateway/      # HTTP gateway
│   └── clawdius-mcp/          # Model Context Protocol
├── editors/vscode/            # VSCode extension (TypeScript)
├── .docs/                     # Internal documentation
└── Cargo.toml                 # Workspace root

Crate Responsibilities

CrateTypePurpose
clawdiusBinaryCLI, TUI (ratatui), command orchestration
clawdius-coreLibraryLLM, sessions, tools, sandboxing, Graph-RAG
clawdius-codeBinaryJSON-RPC server for VSCode extension
clawdius-gatewayBinaryHTTP API server
clawdius-mcpBinaryModel Context Protocol server

Dependency Graph

clawdius (CLI) ──────────┐
                         ├──> clawdius-core
clawdius-code (VSCode) ──┘         │
                                  (external deps)
clawdius-gateway ──────────────────┘

clawdius-core is the single shared library. All binaries depend on it, and it depends only on external crates.

System Architecture

┌───────────────────────────────────────────────────────────┐
│                       Clawdius CLI                        │
│  ┌─────────────┐ ┌─────────────┐ ┌────────────────────┐  │
│  │ Session Mgr │ │ Context     │ │ Timeline           │  │
│  │             │ │ Builder     │ │ & Checkpoints      │  │
│  └─────────────┘ └─────────────┘ └────────────────────┘  │
│  ┌─────────────┐ ┌─────────────┐ ┌────────────────────┐  │
│  │ LLM         │ │ Graph-RAG   │ │ Plugin System      │  │
│  │ Providers   │ │             │ │                    │  │
│  └─────────────┘ └─────────────┘ └────────────────────┘  │
│  ┌─────────────┐ ┌─────────────┐ ┌────────────────────┐  │
│  │ Sandbox     │ │ Tool Runner │ │ Enterprise Features │  │
│  │ Executors   │ │             │ │                    │  │
│  └─────────────┘ └─────────────┘ └────────────────────┘  │
└───────────────────────────────────────────────────────────┘

Core Design Principles

PrincipleDescription
Zero TrustAll external code runs in sandboxes
Typestate SafetyInvalid states unrepresentable at compile time
Defense in DepthMultiple isolation layers
Local FirstFull functionality without internet

Nexus FSM

The Nexus FSM is a 24-phase state machine that enforces structured development through quality gates. Each phase must pass its quality gates before transitioning to the next.

Phases include Context Discovery, Requirements Engineering, Security Engineering, Performance Engineering, CI/CD Engineering, and more. See the sessions page for lifecycle details.

Cross-Crate Communication

CLI to Core

Direct Rust function calls:

#![allow(unused)]
fn main() {
use clawdius_core::{Config, SessionManager};

let config = Config::load_default()?;
let manager = SessionManager::new(&config)?;
}

VSCode to Core

JSON-RPC over stdio via clawdius-code:

VSCode Extension (TypeScript)
    │ JSON-RPC (stdio)
    ▼
clawdius-code Binary
    │ Direct calls
    ▼
clawdius-core Library

Performance

ComponentTarget
Cold boot< 20ms
FSM transition< 1ms
Graph-RAG query< 50ms

The release profile uses fat LTO, single codegen unit, and symbol stripping for optimal binary size and performance.

Feature Flags

Feature flags propagate across crates. Key flags:

FeatureDescription
keyringSystem keyring for API keys
vector-dbLanceDB vector search (Graph-RAG)
embeddingsLocal ML embeddings
local-llmLocal LLM inference with Candle
browserBrowser automation with chromiumoxide
postgresPostgreSQL session storage
redis-queueRedis-backed orchestrator queue
crash-reportingSentry crash reporting

Sandboxing

Clawdius provides multi-tier execution isolation to protect your system from untrusted code and LLM-generated commands.

Overview

All tool execution in Clawdius passes through the sandbox system. Shell commands are checked against blocked patterns, subject to timeouts, and can be restricted to the project directory.

Shell Sandbox

The shell sandbox is configured in .clawdius/config.toml:

[shell_sandbox]
blocked_commands = [
    "rm -rf /",
    "mkfs",
    "dd if=/dev/zero",
    "dd if=/dev/urandom",
    ":(){ :|:& };:",
    "chmod -R 777 /",
    "chown -R",
    "> /dev/sda",
    "mv /* /dev/null",
    "wget",
    "curl -X POST",
]
timeout_secs = 120
max_output_bytes = 1048576    # 1 MB
restrict_to_cwd = true

Blocked Commands

Commands matching any pattern in blocked_commands are rejected before execution. The default list includes destructive system commands and network exfiltration attempts.

Timeout

All shell commands are killed after timeout_secs seconds (default: 120). This prevents runaway processes from consuming resources.

Output Limits

Output is truncated at max_output_bytes (default: 1 MB). This prevents memory exhaustion from commands that produce large output.

Directory Restriction

When restrict_to_cwd is true (default), commands cannot access files outside the project directory.

Sandbox Tiers

Clawdius defines four trust tiers for execution:

TierTrust LevelUse CaseTechnology
1TrustedAuditedRust/C++ compilationBubblewrap passthrough
2TrustedPython/Node.js scriptsContainer (Podman)
3UntrustedLLM reasoningWASM (Wasmtime)
4HardenedUnknown codeHardened container

WASM Sandbox (Brain)

The Brain module runs LLM reasoning in an isolated WASM runtime (Wasmtime):

  • No filesystem access
  • No network access
  • Fuel-based execution limits
  • Memory isolation

Wasmtime is a compile-time dependency and always available. The WASI sandbox provides capability-based security.

Platform Support

FeatureLinuxmacOSWSL2
Shell sandboxYesYesYes
BubblewrapYes (runtime dep)N/AYes
sandbox-execN/ABuilt-inN/A
WASM (Wasmtime)YesYesYes
Containers (Podman)OptionalOptionalOptional

Error Handling

When a sandbox violation occurs, Clawdius returns a Sandbox error:

Sandbox violation: blocked command pattern detected

This command was blocked for security.
Check .clawdius/config.toml for allowed commands.

Security Model

The security model follows a zero-trust approach:

  1. Trust boundaries separate the host kernel from untrusted code
  2. Capability tokens are derived hierarchically (root -> child -> leaf)
  3. Secrets are never exposed to sandboxed processes or WASM modules
  4. Audit logging tracks all sandbox operations

Sessions

Clawdius manages conversation state through a session system backed by SQLite.

Overview

Every chat interaction belongs to a session. Sessions store the full conversation history, metadata, and can be resumed across invocations.

Session Storage

Sessions are stored in SQLite at .clawdius/sessions.db (configurable via storage.sessions_path).

[storage]
sessions_path = ".clawdius/sessions.db"

Session Lifecycle

Creating a Session

A session is created automatically when you start chatting:

clawdius chat
# Session ID is printed on start

Continuing a Session

Resume a previous session with --session:

clawdius chat "continue the refactoring" --session abc123

Listing Sessions

clawdius sessions

Output includes session IDs, timestamps, and message counts.

Searching Sessions

clawdius sessions --search "error handling"

Deleting a Session

clawdius sessions --delete abc123

Session Configuration

[session]
compact_threshold = 0.85    # Auto-compact at 85% of context limit
keep_recent = 4             # Keep last 4 messages when compacting
min_messages = 10           # Minimum messages before compacting
auto_save = true            # Automatically save after each message

Context Compaction

When a session approaches the model's context limit (controlled by compact_threshold), Clawdius automatically compacts the conversation. The keep_recent setting determines how many recent messages are preserved in full.

Manual Compaction

Start a fresh context while preserving the session metadata:

clawdius chat "compact" --session abc123

Active Session

When you start clawdius chat without specifying a session, the most recently active session is resumed. If no sessions exist, a new one is created.

Multi-Provider Sessions

You can switch providers within a session:

clawdius chat "quick question" --provider openai --session abc123
clawdius chat "deep analysis" --provider anthropic --session abc123

Headless Mode

For programmatic usage, Clawdius can read from stdin in headless mode:

clawdius --no-tui
# Type messages, press Enter
# Ctrl+D to exit

Or pipe messages:

echo "analyze src/lib.rs" | clawdius --no-tui

Session Internals

Each session contains:

  • Messages: Full conversation history (user, assistant, system roles)
  • Metadata: Provider, model, creation time, update time
  • Context items: Files and mentions attached to the conversation
  • Checkpoints: Session-level file snapshots

The SessionManager in clawdius-core provides the API:

#![allow(unused)]
fn main() {
use clawdius_core::SessionManager;

let manager = SessionManager::new(&config)?;
let session = manager.get_or_create_active()?;
manager.add_message(&mut session, message).await?;
}

Tools

Clawdius provides a set of built-in tools that the LLM can invoke during a session.

Overview

Tools extend the LLM's capabilities beyond text generation. When the LLM determines it needs to execute a command, read a file, or perform an action, it invokes the appropriate tool. The tool executes (within the sandbox) and returns the result to the LLM.

Built-in Tools

Shell Tool

Execute shell commands with sandboxing:

#![allow(unused)]
fn main() {
pub struct ShellParams {
    pub command: String,
    pub timeout: u64,       // Default: 120000ms
    pub cwd: Option<String>,
}

pub struct ShellResult {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
    pub timed_out: bool,
}
}

The shell tool enforces all sandbox rules: blocked commands, timeouts, output limits, and directory restrictions.

File Tool

File system operations:

  • Read: Read file contents
  • Write: Write file contents
  • List: List directory contents
  • Search: Search files by pattern

Git Tool

Git repository operations:

  • Status: Get current repository status
  • Stage/Unstage: Stage or unstage files
  • Commit: Create commits
  • Diff: View staged or working diffs
  • History: Get file change history

Browser Tool

Browser automation for testing and web interaction (requires browser feature):

  • Navigate to URLs
  • Interact with page elements
  • Capture screenshots
  • Extract page content

Web Search Tool

Search the web for information to supplement the LLM's knowledge.

Tool Definition Format

Each tool is defined with a name, description, and JSON Schema parameters:

#![allow(unused)]
fn main() {
pub struct Tool {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,  // JSON Schema
}

pub struct ToolResult {
    pub success: bool,
    pub content: String,
    pub is_error: bool,
    pub metadata: Option<serde_json::Value>,
}
}

Auto-Approve Mode

By default, tool executions require user confirmation. In autonomous mode, tools execute without prompting:

clawdius chat --auto-approve "refactor this module"
clawdius auto "fix failing tests" --run-tests

Sandboxed Execution

All tool execution passes through the sandbox system. See Sandboxing for details on how commands are restricted.

Custom Tools via MCP

Clawdius supports the Model Context Protocol for extending available tools. See the clawdius-mcp crate for MCP server implementation.

Tool Errors

When a tool fails, the error is returned to the LLM with context:

#![allow(unused)]
fn main() {
Error::ToolExecution {
    tool: "shell",
    reason: "blocked command pattern detected: rm -rf /",
}
}

The LLM can then adjust its approach and try a different action.

Graph-RAG

Clawdius uses a Graph-RAG (Retrieval-Augmented Generation) system to provide the LLM with deep codebase context.

Overview

Graph-RAG combines two complementary approaches:

  1. Structural understanding via AST (Abstract Syntax Tree) parsing with tree-sitter
  2. Semantic search via vector embeddings stored in LanceDB

This gives the LLM both precise code structure knowledge and fuzzy semantic matching capability.

Components

AST Index (SQLite)

tree-sitter parses source files into ASTs, which are stored in a SQLite database at .clawdius/graph/index.db.

Supported languages:

LanguageParser
Rusttree-sitter-rust
Pythontree-sitter-python
JavaScripttree-sitter-javascript
TypeScripttree-sitter-typescript
Gotree-sitter-go

The AST index enables structural queries like "find all function definitions" or "list imports in this module."

Vector Store (LanceDB)

Code is embedded into vector representations and stored in LanceDB at .clawdius/graph/vectors.lance.

Semantic search allows queries like "find error handling patterns" or "locate database connection code" without exact keyword matching.

Graph Analysis

The petgraph crate powers the code relationship graph, tracking:

  • Function call relationships
  • Import/dependency chains
  • Module hierarchies
  • Type usage patterns

Configuration

[storage]
database_path = ".clawdius/graph/index.db"
vector_path = ".clawdius/graph/vectors.lance"

Feature Flags

Graph-RAG has two levels of activation:

FeatureDescription
vector-dbEnable LanceDB vector search
embeddingsEnable local ML embeddings (tokenizers + HuggingFace)
local-llmFull local inference (Candle + embeddings + vector-db)

Indexing

Index your workspace:

# Requires vector-db feature
clawdius index .
clawdius index . --watch    # Watch for changes and re-index

Context Queries

Query the indexed workspace:

# Requires vector-db feature
clawdius context "how does authentication work"
clawdius context "error handling patterns" --max-tokens 8000

Performance

Graph-RAG queries are optimized for speed:

OperationTarget
AST parse (per file)< 10ms
Vector search< 50ms
Graph traversal< 5ms

How It Works in Practice

When you ask Clawdius a question about your codebase:

  1. The query is analyzed to determine what context is needed
  2. The AST index is queried for structural matches
  3. The vector store is searched for semantic matches
  4. Results are ranked and merged into a context window
  5. The context is sent to the LLM along with your question

This produces more accurate, grounded responses compared to sending raw file contents.

LLM Providers Overview

Clawdius supports multiple LLM providers through a unified interface powered by the genai crate.

Supported Providers

ProviderIdentifierDefault ModelAPI Key Required
Anthropicanthropicclaude-sonnet-4-20250514Yes
OpenAIopenaigpt-4oYes
Google Geminigooglegemini-2.5-flashYes
xAI Grokxaigrok-3Yes
Mistral AImistralmistral-large-latestYes
DeepSeekdeepseekdeepseek-coderYes
Ollamaollamallama3.2No (local)
ZAIzaizai-defaultYes
OpenRouteropenrouter(varies)Yes

Selecting a Provider

Via CLI Flag

clawdius chat "Hello" --provider anthropic
clawdius chat "Hello" --provider openai --model gpt-4o

Via Configuration

[llm]
default_provider = "anthropic"

Per-Provider Settings

[llm.anthropic]
model = "claude-sonnet-4-20250514"
api_key_env = "ANTHROPIC_API_KEY"

[llm.openai]
model = "gpt-4o"
api_key_env = "OPENAI_API_KEY"

API Key Priority

Keys are resolved in this order:

  1. Environment variable (e.g., ANTHROPIC_API_KEY)
  2. System keyring (via clawdius auth set)
  3. Config file api_key field (not recommended)

Retry Logic

All providers share a common retry system:

[llm.retry]
max_retries = 3
initial_delay_ms = 1000
max_delay_ms = 30000
exponential_base = 2.0
retry_on = ["rate_limit", "timeout", "server_error", "network_error"]

Retries use exponential backoff with jitter. Rate limit errors (HTTP 429) are automatically retried.

Provider-Specific Pages

Switching Providers

You can switch providers per-command:

# Quick question with OpenAI
clawdius chat "explain this regex" --provider openai

# Deep analysis with Claude
clawdius chat "review architecture" --provider anthropic

# Local development with Ollama
clawdius chat "write tests" --provider ollama --model llama3.2

Anthropic Claude

Anthropic's Claude models are the default provider in Clawdius.

Setup

Environment Variable

export ANTHROPIC_API_KEY="sk-ant-..."

Add to your shell profile for persistence:

# ~/.bashrc or ~/.zshrc
export ANTHROPIC_API_KEY="sk-ant-..."

System Keyring

clawdius auth set anthropic
# Prompts for key input securely

Configuration File

[llm]
default_provider = "anthropic"

[llm.anthropic]
model = "claude-sonnet-4-20250514"
api_key_env = "ANTHROPIC_API_KEY"

Available Models

ModelIDBest For
Claude Sonnet 4claude-sonnet-4-20250514General coding (default)
Claude 3.5 Sonnetclaude-3-5-sonnet-20241022Balanced speed/quality
Claude 3 Opusclaude-3-opus-20240229Complex reasoning

Usage

# Default (Claude Sonnet 4)
clawdius chat "explain this code"

# Specific model
clawdius chat "review architecture" --provider anthropic --model claude-3-opus-20240229

# With explicit provider
clawdius chat "write tests" -P anthropic -m claude-sonnet-4-20250514

Configuration Reference

[llm.anthropic]
model = "claude-sonnet-4-20250514"          # Model to use
api_key_env = "ANTHROPIC_API_KEY"            # Env var for API key
# api_key = "sk-ant-..."                    # Inline key (not recommended)
# base_url = "https://custom-proxy.example" # Custom endpoint

Rate Limiting

Anthropic enforces rate limits per API key. Clawdius handles HTTP 429 responses automatically through the retry system:

[llm.retry]
max_retries = 3
initial_delay_ms = 1000
max_delay_ms = 30000
retry_on = ["rate_limit", "timeout", "server_error", "network_error"]

If you hit rate limits frequently, consider:

  • Increasing max_delay_ms
  • Using clawdius auth get anthropic to verify your key
  • Switching to a different model tier

Troubleshooting

"API key not set"

echo $ANTHROPIC_API_KEY    # Check env var
clawdius auth get anthropic  # Check keyring
clawdius setup --provider anthropic  # Re-run setup

"Retry exhausted"

Increase retry settings in config.toml:

[llm.retry]
max_retries = 5
initial_delay_ms = 2000
max_delay_ms = 60000

OpenAI

Clawdius supports OpenAI's GPT models as an alternative LLM provider.

Setup

Environment Variable

export OPENAI_API_KEY="sk-..."

System Keyring

clawdius auth set openai

Configuration File

[llm]
default_provider = "openai"

[llm.openai]
model = "gpt-4o"
api_key_env = "OPENAI_API_KEY"

Available Models

ModelIDBest For
GPT-4ogpt-4oGeneral coding (default)
GPT-4 Turbogpt-4-turboLong context
GPT-3.5 Turbogpt-3.5-turboFast, cost-effective
o1o1Complex reasoning
o3-minio3-miniReasoning, cost-effective

Usage

# Default (GPT-4o)
clawdius chat "explain this code" --provider openai

# Specific model
clawdius chat "review architecture" --provider openai --model o1

# With explicit flags
clawdius chat "write tests" -P openai -m gpt-4o

Configuration Reference

[llm.openai]
model = "gpt-4o"                            # Model to use
api_key_env = "OPENAI_API_KEY"               # Env var for API key
# api_key = "sk-..."                       # Inline key (not recommended)
# base_url = "https://custom-proxy.example" # Custom endpoint or proxy

Using a Proxy

If you need to route requests through a proxy or use a compatible API:

[llm.openai]
model = "gpt-4o"
base_url = "https://your-proxy.example.com/v1"
api_key_env = "PROXY_API_KEY"

Rate Limiting

OpenAI rate limits vary by model and tier. The retry system handles HTTP 429 automatically:

[llm.retry]
max_retries = 3
initial_delay_ms = 1000
max_delay_ms = 30000
retry_on = ["rate_limit", "timeout", "server_error", "network_error"]

Troubleshooting

"API key not set"

echo $OPENAI_API_KEY
clawdius auth get openai

"Model not available"

Verify the model name matches OpenAI's current API. Check available models at OpenAI's documentation.

Google Gemini

Google's Gemini models offer large context windows and strong multimodal capabilities.

Setup

Environment Variable

export GOOGLE_API_KEY="..."

Add to your shell profile for persistence:

# ~/.bashrc or ~/.zshrc
export GOOGLE_API_KEY="..."

Configuration File

[llm]
default_provider = "google"

[llm.google]
model = "gemini-2.5-flash"
api_key_env = "GOOGLE_API_KEY"

Available Models

ModelIDBest For
Gemini 2.5 Flashgemini-2.5-flashFast coding (default)
Gemini 2.5 Progemini-2.5-proComplex reasoning
Gemini 2.0 Flashgemini-2.0-flashBalanced speed/quality

Usage

# Default (Gemini 2.5 Flash)
clawdius chat "explain this code"

# Specific model
clawdius chat "review architecture" --provider google --model gemini-2.5-pro

Configuration Reference

[llm.google]
model = "gemini-2.5-flash"                   # Model to use
api_key_env = "GOOGLE_API_KEY"                # Env var for API key
# base_url = "https://generativelanguage.googleapis.com" # Custom endpoint

Tool Calling

Gemini 2.5 Flash and Pro support function/tool calling. Enable tools in your config:

[modes.code]
tools = true

Troubleshooting

"API key not set"

echo $GOOGLE_API_KEY       # Check env var
clawdius setup --provider google  # Re-run setup

xAI Grok

xAI's Grok models provide fast inference with strong coding capabilities.

Setup

Environment Variable

export XAI_API_KEY="xai-..."

Configuration File

[llm]
default_provider = "xai"

[llm.xai]
model = "grok-3"
api_key_env = "XAI_API_KEY"

Available Models

ModelIDBest For
Grok 3grok-3General coding (default)
Grok 3 Minigrok-3-miniFast responses

Usage

clawdius chat "explain this code" --provider xai
clawdius chat "review" --provider xai --model grok-3-mini

Tool Calling

Grok models support function/tool calling. Enable in config:

[modes.code]
tools = true

Mistral AI

Mistral provides high-quality open-weight models with competitive performance.

Setup

Environment Variable

export MISTRAL_API_KEY="..."

Configuration File

[llm]
default_provider = "mistral"

[llm.mistral]
model = "mistral-large-latest"
api_key_env = "MISTRAL_API_KEY"

Available Models

ModelIDBest For
Mistral Largemistral-large-latestGeneral coding (default)
Codestralcodestral-latestCode generation
Mistral Smallmistral-small-latestFast responses

Usage

clawdius chat "explain this code" --provider mistral
clawdius chat "write a parser" --provider mistral --model codestral-latest

Tool Calling

Mistral Large supports function/tool calling. Enable in config:

[modes.code]
tools = true

Ollama (Local)

Ollama provides fully local LLM inference with no API key required and no data leaving your machine.

Prerequisites

Install Ollama:

# macOS / Linux
curl -fsSL https://ollama.ai/install.sh | sh

# Start the server
ollama serve

Setup

Default Configuration

No API key is needed. The default Ollama URL is http://localhost:11434.

Configuration File

[llm]
default_provider = "ollama"

[llm.ollama]
model = "llama3.2"
base_url = "http://localhost:11434"

Environment Variable (Remote Server)

export OLLAMA_BASE_URL="http://your-server:11434"

Available Models

Pull models from the Ollama registry:

ollama pull llama3.2
ollama pull codellama
ollama pull mistral
ollama pull deepseek-coder
ModelIDSizeBest For
Llama 3.2llama3.23.2BGeneral (default)
Code Llamacodellama13BCode generation
Mistralmistral7BBalanced
DeepSeek Coderdeepseek-coder6.7BCode

Usage

# Default (llama3.2)
clawdius chat "explain this code" --provider ollama

# Specific model
clawdius chat "write tests" --provider ollama --model codellama

# Manage models via CLI
clawdius models list
clawdius models pull llama3.2
clawdius models health
clawdius models current

Managing Models

# List available local models
clawdius models list

# Pull a new model
clawdius models pull mistral

# Check server health
clawdius models health

# Custom server
clawdius models list --host 192.168.1.100 --port 11434

Configuration Reference

[llm.ollama]
model = "llama3.2"                       # Model to use
base_url = "http://localhost:11434"       # Ollama server URL

Connectivity Check

The setup wizard checks Ollama connectivity:

clawdius setup --provider ollama

If the server is unreachable, verify:

curl http://localhost:11434/api/tags

Performance Tips

  • Use models with fewer parameters for faster responses
  • Ensure sufficient RAM (at least 8GB for 7B models)
  • Use llama3.2 for the best speed/quality tradeoff on consumer hardware
  • Consider GPU acceleration for larger models

Troubleshooting

"Connection refused"

# Verify Ollama is running
ollama serve
curl http://localhost:11434/api/tags

"Model not found"

ollama pull llama3.2
clawdius models list

Custom Providers

Clawdius supports custom LLM endpoints through the base_url configuration.

OpenAI-Compatible Endpoints

Any server implementing the OpenAI chat completions API can be used by setting base_url:

[llm.openai]
model = "your-model-name"
base_url = "https://your-endpoint.example.com/v1"
api_key_env = "YOUR_API_KEY"

This works with:

  • Local inference servers (vLLM, llama.cpp, text-generation-webui)
  • Cloud proxies (LiteLLM, Helicone)
  • Enterprise gateways

DeepSeek

[llm]
default_provider = "deepseek"

[llm.deepseek]
model = "deepseek-coder"
api_key_env = "DEEPSEEK_API_KEY"
export DEEPSEEK_API_KEY="your-key"
clawdius chat "write code" --provider deepseek

ZAI (Zhipu AI)

[llm]
default_provider = "zai"

[llm.zai]
model = "zai-default"
api_key_env = "ZAI_API_KEY"
export ZAI_API_KEY="your-key"
clawdius chat "write code" --provider zai

Google Gemini

[llm]
default_provider = "google"

[llm.google]
model = "gemini-pro"
api_key_env = "GOOGLE_API_KEY"

OpenRouter

OpenRouter provides multi-provider routing. Configure it as an OpenAI-compatible endpoint:

[llm.openai]
model = "anthropic/claude-sonnet-4-20250514"
base_url = "https://openrouter.ai/api/v1"
api_key_env = "OPENROUTER_API_KEY"
export OPENROUTER_API_KEY="your-key"
clawdius chat "Hello" --provider openai --model anthropic/claude-sonnet-4-20250514

Local Inference Servers

vLLM

[llm.openai]
model = "your-model"
base_url = "http://localhost:8000/v1"

llama.cpp Server

[llm.openai]
model = "your-model"
base_url = "http://localhost:8080/v1"

Custom Provider via Environment

You can override any provider's base URL via environment variables. The provider identifier must match a known provider name in the CLI:

clawdius chat "Hello" --provider openai --model custom-model

Combined with base_url in the config, this routes requests to your custom endpoint while using OpenAI's message format.

Retry Configuration

Custom endpoints benefit from the same retry system:

[llm.retry]
max_retries = 5
initial_delay_ms = 2000
max_delay_ms = 60000
exponential_base = 2.0
retry_on = ["rate_limit", "timeout", "server_error", "network_error"]

Checkpoints and Timeline

Clawdius provides two complementary systems for tracking file changes and enabling rollback.

Overview

  • Session Checkpoints: Per-session snapshots of file state
  • Timeline: Project-level version history with diffing and rollback

Session Checkpoints

Creating a Checkpoint

clawdius checkpoint create "before refactoring"

Listing Checkpoints

clawdius checkpoint list
clawdius checkpoint list --verbose    # Show file details
clawdius checkpoint list --session abc123

Restoring a Checkpoint

clawdius checkpoint restore <checkpoint-id>

Comparing Checkpoints

clawdius checkpoint compare <id1> <id2>

Deleting Checkpoints

clawdius checkpoint delete <checkpoint-id>

Cleanup

Keep only the most recent checkpoints:

clawdius checkpoint cleanup --keep 10
clawdius checkpoint cleanup --session abc123 --keep 5

Timeline

The timeline system provides project-level file version tracking independent of sessions.

Creating Timeline Entries

clawdius timeline create "v1.0 release"
clawdius timeline create "pre-refactor" --description "Before major refactor"

Listing Timeline Entries

clawdius timeline list

Rollback

Restore your project to a previous state:

clawdius timeline rollback <checkpoint-id>

Diffing

Compare two points in time:

clawdius timeline diff <from-id> <to-id>

File History

View the change history for a specific file:

clawdius timeline history src/lib.rs

Watch Mode

Automatically create checkpoints when files change:

clawdius timeline watch
clawdius timeline watch --debounce-secs 60 --max-per-hour 60
clawdius timeline watch --ignore "*.log" --ignore "node_modules"

Cleanup

clawdius timeline cleanup --keep 100

Timeline Data Structure

Each checkpoint stores:

FieldTypeDescription
idStringUnique checkpoint identifier
nameStringHuman-readable name
descriptionOption<String>Optional description
tagOption<String>Optional tag
timestampDateTimeCreation time
files_changedusizeNumber of files
checksumStringContent hash (BLAKE3)

Diff Format

The diff between checkpoints includes:

FieldDescription
files_addedNewly created files
files_modifiedChanged files with additions/deletions
files_deletedRemoved files
statsAggregate change statistics

Typical Workflow

# 1. Create checkpoint before making changes
clawdius timeline create "before-auth-feature"

# 2. Make changes...
# 3. Create intermediate checkpoint
clawdius timeline create "auth-models-done"

# 4. Review what changed
clawdius timeline diff "before-auth-feature" "auth-models-done"

# 5. If something went wrong, rollback
clawdius timeline rollback "before-auth-feature"

Storage

Timeline data is stored in SQLite. Metadata (timestamps, file lists, checksums) lives in the database, while file snapshots are stored on the filesystem.

[storage]
database_path = ".clawdius/graph/index.db"

@mentions

Clawdius supports @mentions to include files, directories, and other context in your messages.

Overview

When composing a message, use @mentions to attach files to the conversation context. The mention resolver reads the referenced files and includes their contents in the LLM's context window.

Syntax

@path/to/file.rs     Include a specific file
@src/                Include a directory (all files)
@lib.rs              Relative path to a file

Examples

# Reference a file in your message
clawdius chat "explain @src/main.rs"

# Reference multiple files
clawdius chat "compare @src/old.rs and @src/new.rs"

# Reference a directory
clawdius chat "review the API handlers in @src/api/"

How It Works

  1. The mention resolver scans your message for @ prefixed paths
  2. It resolves each path relative to the current working directory
  3. File contents are read and included as context items
  4. The context is sent to the LLM along with your message

Context Items

Mentions are resolved into ContextItem objects:

#![allow(unused)]
fn main() {
pub struct ContextItem {
    pub path: PathBuf,
    pub content: String,
    pub item_type: ContextItemType,
}
}

Limitations

  • Large files may exceed context limits. Use specific files or functions rather than entire directories.
  • Binary files cannot be included via mentions.
  • Paths are resolved relative to the project root (or --cwd if specified).

Combining with Editor Mode

# Compose in editor with file references
clawdius chat --editor
# Write your message with @mentions in the editor

Integration with Graph-RAG

When the vector-db feature is enabled, @mentions are supplemented with semantic context from the Graph-RAG index, providing related code even from files not explicitly mentioned.

Modes

Agent modes change the LLM's system prompt and behavior to specialize for different tasks.

Built-in Modes

ModeDescription
codeGeneral-purpose coding assistant (default)
architectSystem design and high-level architecture
askQ&A without executing tools
debugDebugging and error diagnosis
reviewCode review and quality analysis
refactorRefactoring guidance and execution
testTest generation
autoFully autonomous execution

Usage

clawdius chat --mode architect "Design a payment system"
clawdius chat --mode debug "Why does this test fail?"
clawdius chat --mode review "Review src/main.rs"
clawdius chat --mode test "Write tests for the auth module"
clawdius chat --mode auto "Fix the CI pipeline"

Listing Modes

clawdius modes list

Showing Mode Details

clawdius modes show architect

Custom Modes

Create your own agent mode:

clawdius modes create security-review

This creates a mode configuration file that you can customize with:

  • System prompt
  • Allowed tools
  • Temperature and other model parameters
  • Custom instructions

Save to a specific path:

clawdius modes create security-review --output .clawdius/modes/

Mode Behavior

Each mode configures:

  • System prompt: Instructions that guide the LLM's behavior
  • Tool access: Which tools are available
  • Auto-approve: Whether tools execute without confirmation
  • Output style: How responses are formatted

The code mode is the default and provides full tool access with confirmation prompts. The auto mode enables auto-approve for all tool executions. The ask mode disables tool execution entirely.

Using Custom Modes

Once created, use a custom mode like a built-in one:

clawdius chat --mode security-review "Audit the authentication flow"

Streaming

Clawdius supports real-time streaming of LLM responses for immediate feedback.

Overview

Instead of waiting for the full response, streaming delivers tokens as they are generated. This provides a responsive experience, especially for long-running responses.

Stream JSON Mode

Use the stream-json output format for real-time processing:

clawdius chat -f stream-json

Each line in the output is a self-contained JSON object containing a token or status update. This is suitable for piping to other tools or processing in real time.

Output Formats

FormatFlagDescription
TexttextStandard formatted output (default)
JSONjsonComplete JSON response after processing
Stream JSONstream-jsonReal-time JSON token stream

Usage Examples

Standard Streaming

clawdius chat "explain this code"
# Response streams token by token in the TUI

JSON Output

clawdius chat "explain this code" -f json
# Complete response as JSON after generation finishes

Stream JSON for Scripts

clawdius chat "analyze code" -f stream-json | jq '.content'
# Process tokens in real time

Programmatic Consumption

# Pipe to a file
clawdius chat "generate docs" -f json -o response.json

# Watch mode for continuous output
clawdius chat "monitor" -f stream-json

Performance

Streaming uses zero-copy patterns for efficient data transfer:

  • Tokens are emitted as soon as they arrive from the LLM
  • No buffering delay between the provider and the terminal
  • The TUI renders at 60 FPS using ratatui

Headless Streaming

In headless mode (no TUI), streaming output goes to stdout:

clawdius --no-tui
# Type a message, see tokens stream to stdout

Metrics Output

Metrics also support streaming/watch mode:

clawdius metrics --watch
clawdius metrics -f json --watch

Keyring Storage

Clawdius can securely store API keys in your operating system's native keyring, keeping them out of config files and environment variables.

Overview

The keyring feature uses the keyring crate to interface with platform-specific secret storage:

PlatformBackend
Linuxlibsecret / Secret Service (GNOME Keyring, KDE Wallet)
macOSKeychain
WindowsCredential Manager

Enabling Keyring

The keyring feature must be enabled at compile time:

cargo install clawdius --features keyring

Or when building from source:

cargo build --features keyring

CLI Commands

Store an API Key

clawdius auth set anthropic
# Prompts securely for the key (input is hidden)

Retrieve a Stored Key

clawdius auth get anthropic
# Shows first 8 characters: sk-ant-a...

Delete a Stored Key

clawdius auth delete anthropic

Supported Providers

ProviderKey Name
anthropicAnthropic API key
openaiOpenAI API key
zaiZ.AI API key

API Key Priority

When Clawdius resolves an API key, it checks sources in order:

  1. Environment variable (e.g., ANTHROPIC_API_KEY)
  2. System keyring (via clawdius auth set)
  3. Config file api_key field (least secure)

If a key is found in an earlier source, later sources are not checked.

Programmatic API

#![allow(unused)]
fn main() {
use clawdius_core::config::KeyringStorage;

let storage = KeyringStorage::global();

// Store
storage.set_api_key("anthropic", "sk-ant-...")?;

// Retrieve
if let Some(key) = storage.get_api_key("anthropic")? {
    println!("Key found: {}***", &key[..8]);
}

// Delete
storage.delete_api_key("anthropic")?;
}

The KeyringStorage::global() method returns a lazily-initialized singleton, so you can call it from anywhere without managing lifetimes.

Security Notes

  • Keys are stored in the OS keyring, which is encrypted at rest
  • Keys are never written to log files or traces
  • Keys are never exposed to sandboxed processes or WASM modules
  • The clawdius auth get command masks the key, showing only the prefix

Troubleshooting

"Failed to access keyring"

On Linux, ensure a secret service is running:

# GNOME
gnome-keyring-daemon --start

# KDE
# Wallet should auto-start; check kwalletmanager5

On headless Linux servers without a desktop environment, you may need:

# Install and configure gnome-keyring
sudo apt install gnome-keyring

Feature not available

Ensure the keyring feature is compiled in:

clawdius auth set anthropic
# If this fails with "unknown command", rebuild with --features keyring

Sandbox Overview

This section is under development.

Refer to the repository for current implementation details.

Sandbox Tiers

This section is under development.

Refer to the repository for current implementation details.

Backend Configuration

This section is under development.

Refer to the repository for current implementation details.

WASM Sandbox

This section is under development.

Refer to the repository for current implementation details.

Bubblewrap Sandbox

This section is under development.

Refer to the repository for current implementation details.

Container Sandbox

This section is under development.

Refer to the repository for current implementation details.

gVisor Sandbox

This section is under development.

Refer to the repository for current implementation details.

Firecracker Sandbox

This section is under development.

Refer to the repository for current implementation details.

SSO Integration

This section is under development.

Refer to the repository for current implementation details.

Audit Logging

This section is under development.

Refer to the repository for current implementation details.

Compliance

This section is under development.

Refer to the repository for current implementation details.

Team Management

This section is under development.

Refer to the repository for current implementation details.

Plugin Overview

This section is under development.

Refer to the repository for current implementation details.

Creating Plugins

This section is under development.

Refer to the repository for current implementation details.

Plugin API

This section is under development.

Refer to the repository for current implementation details.

Hooks

This section is under development.

Refer to the repository for current implementation details.

Plugin Marketplace

This section is under development.

Refer to the repository for current implementation details.

VSCode Integration

This section is under development.

Refer to the repository for current implementation details.

Vim/Neovim Integration

This section is under development.

Refer to the repository for current implementation details.

Emacs Integration

This section is under development.

Refer to the repository for current implementation details.

CLI Reference

This section is under development.

Refer to the repository for current implementation details.

LSP Server

Clawdius includes a built-in Language Server Protocol server (clawdius-lsp) that provides code intelligence to any LSP-compatible editor.

Installation

# Build from source
cargo build --release -p clawdius-lsp

# Binary location
./target/release/clawdius-lsp

Supported Features

LSP MethodStatusBackend
textDocument/didOpenWorkingTree-sitter indexing
textDocument/didChangeWorkingIncremental re-index
textDocument/documentSymbolWorkingTree-sitter extraction
textDocument/hoverPlannedGraph-RAG integration
textDocument/definitionPlannedSymbol index
textDocument/referencesPlannedSymbol index
clawdius/analyze (custom)WorkingReturns index summary
clawdius/verify (custom)WorkingReturns proof stats

Languages

Symbol extraction via Tree-sitter (inherited from clawdius-core):

  • Rust, Python, JavaScript, TypeScript, TSX, Go, Java, C++, PHP, Ruby

Editor Configuration

Neovim (nvim-lspconfig)

require('lspconfig').clawdius_lsp.setup {
  cmd = { 'clawdius-lsp' },
  filetypes = { 'rust', 'python', 'javascript', 'typescript', 'go' },
}

VSCode

Install the Clawdius extension from extensions/clawdius/. The extension communicates with clawdius-code (JSON-RPC over stdio), which delegates to the same core library.

Emacs (lsp-mode)

(lsp-register-client
 (make-lsp-client
  :new-connection (lsp-stdio-connection "clawdius-lsp")
  :major-modes '(rust-mode python-mode go-mode js-mode typescript-mode)
  :server-id 'clawdius-lsp))

Helix

# .helix/languages.toml
[language-server.clawdius-lsp]
command = "clawdius-lsp"

Architecture

Editor (LSP client)
    |
    | JSON-RPC over stdio
    v
clawdius-lsp (tower-lsp)
    |
    | clawdius-core graph_rag module
    v
Tree-sitter parsers (10 languages) + symbol index

The LSP server is a thin layer over clawdius-core's existing Tree-sitter parsing infrastructure. No additional indexing step is required -- documents are parsed on open and change events.

Custom Methods

clawdius/analyze

Returns a summary of the current symbol index:

{
  "documents": 15,
  "symbols": 342
}

clawdius/verify

Returns Lean4 proof verification status:

{
  "status": "ok",
  "theorems": 318,
  "proof_files": 22,
  "lake_jobs": "21 libs + 1 exe"
}

Messaging Adapters

Clawdius Gateway connects to messaging platforms through adapters -- pluggable modules that translate between each platform's API and Clawdius's internal message protocol.

Available Adapters

AdapterTransportFeature FlagStatus
TelegramLong-polling (teloxide)telegramStable
DiscordGateway (serenity)discordStable
SlackSocket Mode / Event APIslackStable
MatrixClient-Server sync (matrix-sdk)matrixStable
SignalREST API (signal-cli)--Stable
TeamsBot Framework REST API--Stable
WhatsAppMeta Cloud API--Stable
Rocket.ChatREST / Real-Time API--Stable
WebhookHTTP POST--Stable

Common Configuration Pattern

All adapters share the same PlatformConfig structure. Required fields are resolved from environment variables or the TOML config file:

[gateways.telegram]
api_token = "..."          # Maps to TELEGRAM_BOT_TOKEN
enabled = true

[gateways.telegram.settings]
# Adapter-specific key-value pairs

Each adapter reads api_token as its primary credential and uses the settings map for additional configuration.

Message Flow

Platform API --> Adapter --> Gateway (MessageHandler) --> LLM
                                                       |
Platform API <-- Adapter <-- Gateway (OutgoingMessage) <+

All adapters implement the PlatformAdapter trait which provides:

  • start() / stop() -- lifecycle management
  • send_message() -- deliver responses
  • edit_message() -- streaming edits (where supported)
  • download_attachment() -- file retrieval

Health Checking

Every adapter exposes a health() method returning:

FieldTypeDescription
healthyboolWhether the adapter is active
messagestringStatus summary (e.g. "polling", "syncing")
messages_processedu64Total messages handled
errorsu64Total errors encountered

Feature Gate Caveat

Telegram, Discord, Slack, and Matrix adapters are behind Cargo feature flags. Enable them at build time:

cargo build --features telegram,discord,slack,matrix

Signal, Teams, WhatsApp, Rocket.Chat, and Webhook adapters are always available.

Telegram Adapter

Overview

Connects Clawdius to Telegram via a bot using the teloxide SDK. Handles incoming messages, file downloads, and response delivery including streaming edits through Telegram's message editing API.

Configuration

VariableRequiredDefaultDescription
TELEGRAM_BOT_TOKENYes--Bot token from @BotFather

The token is read from the api_token field in the platform config or from the TELEGRAM_BOT_TOKEN environment variable.

Setup

  1. Open Telegram and search for @BotFather
  2. Send /newbot and follow the prompts to create your bot
  3. Copy the bot token (format: 123456789:ABCdefGHIjklMNOpqrSTUvwxYZ)
  4. Enable the telegram feature flag:
    cargo build --features telegram
    
  5. Set the token in your config:
    [gateways.telegram]
    api_token = "123456789:ABCdefGHIjklMNOpqrSTUvwxYZ"
    enabled = true
    
    Or export the environment variable:
    export TELEGRAM_BOT_TOKEN="123456789:ABCdefGHIjklMNOpqrSTUvwxYZ"
    

Features

  • Full message handling (text, commands, replies, forwards)
  • File and attachment download
  • Message editing for streaming responses
  • Markdown v2 formatting in outgoing messages
  • Long-polling with 35-second timeout per request
  • Rate limit awareness with automatic retry-after handling
  • Graceful shutdown via tokio::sync::Notify

Limitations

  • Only text messages are processed; stickers, photos without captions, and other non-text content are silently dropped
  • Long-polling only -- no webhook mode is supported in the current implementation
  • Message edits use edit_message_text which requires the original message to still be accessible by the bot

Troubleshooting

"TELEGRAM_BOT_TOKEN not set"

Ensure the api_token field is set under [gateways.telegram] or that the TELEGRAM_BOT_TOKEN environment variable is exported.

"failed to verify bot token"

The token is invalid or expired. Regenerate it through @BotFather with /revoke.

Rate limit warnings in logs

The adapter automatically handles Telegram's Retry-After responses by sleeping for the requested duration. These are informational warnings.

Network errors

The adapter retries after 2 seconds on network errors and 5 seconds on other errors. Check your network connectivity if errors persist.

Discord Adapter

Overview

Connects Clawdius to Discord via a bot using the serenity SDK. Handles incoming messages, file attachments, and response delivery including streaming edits through Discord's REST API.

Configuration

VariableRequiredDefaultDescription
DISCORD_BOT_TOKENYes--Bot token from the Discord Developer Portal

The token is read from the api_token field in the platform config or from the DISCORD_BOT_TOKEN environment variable.

Setup

  1. Go to the Discord Developer Portal
  2. Click "New Application" and give it a name
  3. Navigate to the "Bot" tab and click "Add Bot"
  4. Copy the bot token
  5. Enable the Privileged Gateway Intents you need (Message Content Intent is required for reading message text)
  6. Invite the bot to your server using the OAuth2 URL generator with the bot scope and appropriate permissions
  7. Enable the discord feature flag:
    cargo build --features discord
    
  8. Set the token in your config:
    [gateways.discord]
    api_token = "MTk2Njg1.xxxxxx.xxxxxx"
    enabled = true
    

Features

  • Full message handling (text, replies, embeds)
  • File and attachment download from Discord CDN
  • Message editing for streaming responses
  • Markdown formatting (Discord-flavored)
  • Role-based admin detection (checks MANAGE_MESSAGES permission)
  • Bot messages are automatically ignored

Limitations

  • The adapter uses Discord REST API v10 directly for send/edit operations rather than the serenity Client's gateway. The serenity Client is used for receiving events via DiscordEventHandler.
  • Message edits require the message ID to be formatted as channel_id:message_id to resolve the target channel.
  • No slash command support -- commands are parsed from plain text messages.

Troubleshooting

"DISCORD_BOT_TOKEN not set"

Ensure the api_token field is set under [gateways.discord] or that the DISCORD_BOT_TOKEN environment variable is exported.

401 Unauthorized on send

The bot token is invalid. Regenerate it in the Discord Developer Portal under the Bot tab.

403 Forbidden on send

The bot lacks permissions in the target channel. Ensure it has been invited with the correct permissions (Send Messages, Manage Messages).

Bot not receiving messages

Verify that the Message Content Intent is enabled in the Developer Portal under your bot's Privileged Gateway Intents.

Slack Adapter

Overview

Connects Clawdius to Slack via a Slack App using the Slack Web API. Handles incoming messages via Socket Mode or the Events API, file downloads, and response delivery including threaded replies.

Configuration

VariableRequiredDefaultDescription
SLACK_BOT_TOKENYes--Bot OAuth token (starts with xoxb-)
SLACK_APP_TOKENNo--App-Level token for Socket Mode (starts with xapp-)

The bot token is read from the api_token field. The app token is read from settings.app_token.

Setup

  1. Go to the Slack App settings
  2. Click "Create New App" and choose "From scratch"
  3. Under OAuth & Permissions, add these Bot Token Scopes:
    • chat:write
    • channels:history
    • files:read
    • groups:history
    • im:history
    • mpim:history
  4. Install the app to your workspace and copy the Bot User OAuth Token (xoxb-...)
  5. For Socket Mode (recommended for self-hosted):
    • Go to Settings > Basic Information > App-Level Tokens
    • Generate a new token with the connections:write scope
    • Copy the App-Level Token (xapp-...)
  6. Enable the slack feature flag:
    cargo build --features slack
    
  7. Configure:
    [gateways.slack]
    api_token = "xoxb-your-bot-token"
    enabled = true
    
    [gateways.slack.settings]
    app_token = "xapp-your-app-token"
    

Features

  • Message handling (text, threaded replies, bot mentions)
  • File and attachment download (with Bearer auth for private files)
  • Threaded conversations using Slack's thread_ts field
  • Markdown formatting (mrkdwn)
  • Message editing via chat.update

Limitations

  • Block Kit support is planned but not yet implemented
  • Socket Mode listener runs separately from the adapter; the adapter itself handles send/edit/download via the Web API
  • Message edits require the message ID to be formatted as channel_id:timestamp
  • Without Socket Mode, you must configure an Events API request URL pointing to the gateway

Troubleshooting

"SLACK_BOT_TOKEN not set"

Ensure the api_token field is set under [gateways.slack]. The token must start with xoxb-.

"missing_scope" error from Slack API

Re-check your Bot Token Scopes under OAuth & Permissions. The most common missing scope is chat:write.

"channel_not_found" when sending

The bot has not been added to the channel. Invite it with /invite @botname.

Socket Mode not connecting

Verify the app token starts with xapp- and has the connections:write scope.

Matrix Adapter

Overview

Connects Clawdius to a Matrix homeserver via a bot account using the matrix-sdk. Handles incoming messages, file uploads/downloads, and response delivery including edits via m.replace relations.

Configuration

VariableRequiredDefaultDescription
MATRIX_HOMESERVER_URLYes--Full URL of the Matrix homeserver
MATRIX_ACCESS_TOKENYes--Access token for the bot account
MATRIX_USER_IDNo@clawdius:matrix.orgFull Matrix ID of the bot

The homeserver URL is read from settings.homeserver_url. The access token is read from api_token. The user ID is read from settings.user_id.

Setup

  1. Create a bot account on your Matrix homeserver (e.g., register at matrix.org or use your own Synapse/Conduit server)
  2. Obtain an access token by logging in:
    curl -X POST https://matrix.org/_matrix/client/v3/login \
      -d '{"type":"m.login.password","identifier":{"type":"m.id.user","user":"clawdius"},"password":"your-password"}'
    
  3. Note the access_token from the response
  4. Enable the matrix feature flag:
    cargo build --features matrix
    
  5. Configure:
    [gateways.matrix]
    api_token = "syt_abc123_xxx"
    enabled = true
    
    [gateways.matrix.settings]
    homeserver_url = "https://matrix.org"
    user_id = "@clawdius:matrix.org"
    

Features

  • Message handling (text, replies, edits, formatted body)
  • File upload and download (with mxc:// URI resolution)
  • Threaded replies via m.in_reply_to relations
  • Message editing via m.replace relations
  • Markdown to Matrix HTML formatting
  • Idempotent sends using transaction IDs (clawdius_<uuid>)
  • E2EE support when the e2e-encryption feature is enabled

Limitations

  • Message edits require the message ID to be formatted as room_id:event_id to resolve the target room
  • E2EE requires a matching rusqlite version for the crypto store; enable with --features matrix,e2e-encryption
  • The Matrix sync loop runs separately via the matrix-sdk Client; the adapter handles send/edit/download via the Client-Server API
  • mxc:// media URLs are converted to HTTP download URLs using the configured homeserver

Troubleshooting

"MATRIX_HOMESERVER_URL not set"

Add homeserver_url to [gateways.matrix.settings].

"MATRIX_ACCESS_TOKEN not set"

Add the api_token field under [gateways.matrix].

401 Unauthorized on API calls

The access token has expired. Log in again to obtain a fresh token. Consider using a long-lived token for bot accounts.

Media download fails for mxc:// URIs

Verify the homeserver URL is correct and the homeserver's media endpoint is accessible. The adapter constructs: {homeserver_url}/_matrix/media/v3/download/{server_name}/{media_id}.

Signal Adapter

Overview

Connects Clawdius to Signal via a running signal-cli daemon with its REST API enabled. Handles text message sending and receiving, group messages, and attachment downloads.

This adapter requires a local signal-cli instance as an intermediary -- Clawdius does not connect to the Signal servers directly.

Configuration

VariableRequiredDefaultDescription
SIGNAL_ACCOUNT_NUMBERYes--Phone number registered with signal-cli
SIGNAL_REST_URLNohttp://localhost:7583Base URL of the signal-cli REST API

The account number is read from api_token. The REST URL is read from settings.rest_url.

Setup

  1. Install and configure signal-cli:
    # Debian/Ubuntu
    sudo apt install signal-cli
    
    # Or via AUR on Arch, Homebrew on macOS, etc.
    
  2. Register your phone number with signal-cli:
    signal-cli -u +1234567890 register
    
  3. Complete verification with the SMS or voice code:
    signal-cli -u +1234567890 verify 123-456
    
  4. Start the REST API daemon:
    signal-cli -u +1234567890 daemon --socket localhost:7583
    
  5. Configure:
    [gateways.signal]
    api_token = "+1234567890"
    enabled = true
    
    [gateways.signal.settings]
    rest_url = "http://localhost:7583"
    

Features

  • Text message sending and receiving
  • Group message support
  • Attachment download
  • Automatic retry on network errors

Limitations

  • Signal does NOT support message editing. When the gateway attempts to edit a message (e.g., during streaming), the adapter sends a new message with an (edited) prefix instead.
  • Rate limited by signal-cli's internal throttling
  • Reaction support is planned but not yet implemented
  • Requires a running signal-cli daemon; it is not embedded in Clawdius

Troubleshooting

"SIGNAL_ACCOUNT_NUMBER not set"

Set api_token under [gateways.signal] to your registered phone number (e.g., +1234567890).

Connection refused to signal-cli

Ensure the signal-cli daemon is running:

signal-cli -u +1234567890 daemon --socket localhost:7583

Signal API errors with 4xx status

Check that the account number matches the registered signal-cli account. Verify signal-cli is properly registered and not in an error state.

Streaming responses arrive as multiple messages

This is expected behavior. Since Signal lacks message editing, streaming edits are sent as individual messages. The adapter prefixes edits with (edited) to indicate updates.

Microsoft Teams Adapter

Overview

Connects Clawdius to Microsoft Teams via the Bot Framework REST API. Handles incoming messages from Teams channels and delivers responses with OAuth token management.

Configuration

VariableRequiredDefaultDescription
TEAMS_APP_IDYes--Microsoft App ID from Azure
TEAMS_APP_PASSWORDNo--Microsoft App Password from Azure
TEAMS_SERVICE_URLNohttps://smba.trafficmanager.net/amerBot Framework service URL

The App ID is read from api_token. The App Password is read from settings.app_password. The service URL is read from settings.service_url.

Setup

  1. Go to the Azure Portal and sign in
  2. Navigate to Azure Active Directory > App registrations > New registration
  3. Give the app a name and register it
  4. Under Certificates & secrets, create a new client secret and copy the value (this is the App Password)
  5. Copy the Application (client) ID (this is the App ID)
  6. Create a Bot Channels Registration in Azure and link it to the app registration
  7. Configure the Teams channel in the Azure Portal
  8. Configure:
    [gateways.teams]
    api_token = "your-microsoft-app-id"
    enabled = true
    
    [gateways.teams.settings]
    app_password = "your-client-secret"
    service_url = "https://smba.trafficmanager.net/amer"
    

Features

  • Text message sending and receiving
  • Message editing for streaming responses
  • OAuth access token caching (obtained automatically from the Bot Framework)
  • Teams-specific channel data extraction
  • Attachment download

Limitations

  • Message editing is limited in Teams -- edits are visible but Teams does not notify users of edits
  • Requires Azure infrastructure for production use
  • Message IDs are formatted as service_url:conversation_id:activity_id for edit operations
  • Adaptive Card support is planned but not yet implemented
  • Proactive messaging support is planned but not yet implemented

Troubleshooting

"TEAMS_APP_ID not set"

Set api_token under [gateways.teams] to your Microsoft Application (client) ID.

"TEAMS_APP_PASSWORD not set"

Add app_password to [gateways.teams.settings] with your client secret value from Azure.

OAuth token request fails

Verify the App ID and App Password are correct. Ensure the app registration has the https://api.botframework.com/.default scope configured.

Service URL errors

The default service URL (https://smba.trafficmanager.net/amer) is for the Americas region. Use https://smba.trafficmanager.net/emea for Europe/Middle East/Africa or https://smba.trafficmanager.net/apac for Asia-Pacific. You can also set a custom URL via settings.service_url.

WhatsApp Adapter

Overview

Connects Clawdius to WhatsApp via the Meta Cloud API (WhatsApp Business Platform). Handles text message sending and receiving through webhook-based incoming messages and the Graph API for outgoing messages.

Configuration

VariableRequiredDefaultDescription
WHATSAPP_ACCESS_TOKENYes--Permanent access token from Meta Developer Portal
WHATSAPP_PHONE_NUMBER_IDYes--Phone number ID for sending messages
WHATSAPP_VERIFY_TOKENNo--Token for webhook verification (HMAC)

The access token is read from api_token. The phone number ID is read from settings.phone_number_id. The verify token is read from webhook_secret.

Setup

  1. Create a Meta Developer account at developers.facebook.com
  2. Create a new app and add the WhatsApp product
  3. Add a phone number to the WhatsApp Business Platform
  4. Copy the Permanent Access Token and Phone Number ID
  5. Configure the webhook callback URL in the Meta Developer Portal pointing to your Clawdius gateway
  6. Configure:
    [gateways.whatsapp]
    api_token = "EAAxxxxxxxx"
    webhook_secret = "your-verify-token"
    enabled = true
    
    [gateways.whatsapp.settings]
    phone_number_id = "1234567890"
    

Features

  • Text message sending and receiving
  • Webhook-based incoming message processing
  • Webhook verification challenge handling
  • Contact profile extraction (wa_id, name)
  • Attachment download via Media API
  • Media message type detection in metadata

Limitations

  • WhatsApp does NOT support message editing. When the gateway attempts to edit a message, the adapter sends a new message with a (corrected) prefix instead.
  • 24-hour response window -- WhatsApp requires responses within 24 hours of the user's message. After this window closes, only pre-approved message templates can be sent.
  • Rate limited by Meta's API tier
  • Interactive messages are planned but not yet implemented
  • Message template support is planned but not yet implemented

Troubleshooting

"WHATSAPP_ACCESS_TOKEN not set"

Set api_token under [gateways.whatsapp] to your permanent access token from the Meta Developer Portal.

"WHATSAPP_PHONE_NUMBER_ID not set"

Add phone_number_id to [gateways.whatsapp.settings].

Webhook verification fails

Ensure the webhook_secret matches the verify token configured in the Meta Developer Portal. The webhook mode must be subscribe.

"send failed with 401"

The access token has expired or is invalid. Generate a new permanent token in the Meta Developer Portal.

Messages not received

Verify the webhook callback URL in the Meta Developer Portal is pointing to the correct Clawdius endpoint and that the gateway is publicly accessible.

Rocket.Chat Adapter

Overview

Connects Clawdius to a Rocket.Chat server via its REST API. Handles incoming messages from channels and direct messages, with support for message editing and threaded replies.

Configuration

VariableRequiredDefaultDescription
ROCKETCHAT_URLYes--Base URL of the Rocket.Chat server
ROCKETCHAT_TOKENYes--Personal access token or API key
ROCKETCHAT_USER_IDYes--Rocket.Chat user ID for the bot account

The server URL is read from settings.server_url. The auth token is read from api_token. The user ID is read from settings.rc_user_id.

Setup

  1. Log in to your Rocket.Chat server as an administrator
  2. Navigate to Administration > Integrations > Personal Access Tokens
  3. Create a new token for the bot user
  4. Note the token and the bot user's user ID
  5. Alternatively, create a dedicated bot user account and generate an API token for it
  6. Configure:
    [gateways.rocketchat]
    api_token = "your-auth-token"
    enabled = true
    
    [gateways.rocketchat.settings]
    server_url = "https://rocketchat.example.com"
    rc_user_id = "bot-user-id"
    

Features

  • Text message sending and receiving
  • Channel and direct message support
  • Message editing for streaming responses (via chat.update)
  • File attachment download (with auth headers)
  • Threaded replies via tmid field
  • Authentication via X-Auth-Token and X-User-Id headers

Limitations

  • Message edits require the message ID to be formatted as room_id:msg_id to resolve the target room and message
  • Real-time updates via WebSocket (DDP protocol) are planned but not yet implemented; currently relies on REST API polling
  • File upload support is planned but not yet implemented

Troubleshooting

"ROCKETCHAT_URL not set"

Add server_url to [gateways.rocketchat.settings] with the full base URL of your Rocket.Chat server (e.g., https://rocketchat.example.com).

"ROCKETCHAT_TOKEN not set"

Set api_token under [gateways.rocketchat] to your personal access token.

"ROCKETCHAT_USER_ID not set"

Add rc_user_id to [gateways.rocketchat.settings] with the Rocket.Chat user ID of the bot account.

401 Unauthorized on API calls

Verify that the auth token is valid and matches the user ID. Tokens can expire; regenerate one from the Personal Access Tokens admin page.

Bot not receiving messages

Ensure the bot user has joined the target channels or groups. For direct messages, the bot must be allowed to receive DMs.

Webhook Adapter

Overview

Provides a generic HTTP endpoint that accepts incoming messages via POST requests and delivers responses via configured outgoing webhooks. Useful for custom integrations, CI/CD notifications, ChatOps pipelines, and any platform without a dedicated adapter.

Configuration

VariableRequiredDefaultDescription
WEBHOOK_URLYes--URL to POST outgoing messages to
WEBHOOK_SECRETNo--Secret for HMAC-SHA256 signature verification
WEBHOOK_LISTEN_PORTNo8080Port for incoming webhook listener
WEBHOOK_OUTGOING_HEADERSNo{}Custom headers for outgoing requests (JSON object)

The outgoing URL is read from webhook_url. The secret is read from webhook_secret. The listen port is read from settings.listen_port. Custom headers are read from settings.outgoing_headers.

Setup

  1. Configure the outgoing webhook URL where responses will be delivered:

    [gateways.webhook]
    webhook_url = "https://your-app.example.com/webhook"
    webhook_secret = "shared-secret-for-signing"
    enabled = true
    
    [gateways.webhook.settings]
    listen_port = 8080
    
  2. (Optional) Configure a custom listen port:

    [gateways.webhook.settings]
    listen_port = 9090
    
  3. (Optional) Add custom headers to outgoing requests:

    [gateways.webhook.settings]
    outgoing_headers = { "X-API-Key" = "your-api-key", "X-Source" = "clawdius" }
    

Protocol

Incoming Messages (POST to Clawdius)

{
  "chat_id": "optional-channel-id",
  "user": {
    "id": "user-123",
    "name": "Alice",
    "username": "alice",
    "is_admin": false
  },
  "text": "message content",
  "reply_to": "optional-parent-id",
  "message_id": "optional-custom-id"
}

All fields except text are optional. If chat_id is omitted, it defaults to "default". If user is omitted, it defaults to anonymous.

Outgoing Messages (POST from Clawdius)

{
  "chat_id": "...",
  "text": "response content",
  "reply_to": "optional-parent-id",
  "message_id": "wh_550e8400-e29b-41d4-a716-446655440000",
  "edit_message_id": "optional-original-id"
}

The edit_message_id field is present only for edit operations.

HMAC Signatures

When WEBHOOK_SECRET is configured, outgoing requests include an X-Clawdius-Signature header with the HMAC-SHA256 digest:

X-Clawdius-Signature: sha256=abcdef0123456789...

Verify the signature by computing HMAC-SHA256 of the raw request body using your shared secret.

Features

  • Generic HTTP POST interface for any platform
  • HMAC-SHA256 payload signing for outgoing messages
  • Custom outgoing headers
  • Configurable listen port for incoming webhooks
  • Message ID generation (wh_<uuid>)
  • Edit support via edit_message_id field
  • Fallback for platforms without a dedicated adapter

Limitations

  • No built-in retry logic for failed outgoing webhooks
  • The HTTP listener spawns a background task; the listener handle is not currently persisted for clean shutdown
  • Edit messages do not carry the original chat_id -- the target URL must handle routing edits to the correct context
  • No support for file uploads in outgoing webhooks

Troubleshooting

"WEBHOOK_URL not set"

Set webhook_url under [gateways.webhook] to the URL where outgoing messages should be POSTed.

"failed to bind to 0.0.0.0:8080"

The port is already in use. Change the listen port in settings.listen_port or stop the conflicting service.

Webhook target returns non-2xx

Check the chat_id and ensure the target endpoint accepts the payload format. Inspect the outgoing body and headers for debugging.

Signature verification fails on receiver side

Ensure both sides use the same secret. The signature is computed over the raw JSON body bytes using HMAC-SHA256.

API Stability

Clawdius follows semantic versioning for its public APIs.

Versioning

The current version is 1.0.0-rc.1. The crate versions are managed at the workspace level in Cargo.toml:

[workspace.package]
version = "1.0.0-rc.1"

Stability Guarantees

Public API Surface

The following types and modules are considered part of the stable public API:

ModuleExports
clawdius_core::ConfigConfiguration loading and saving
clawdius_core::SessionManagerSession lifecycle management
clawdius_core::error::ErrorUnified error type
clawdius_core::error::ResultResult type alias
clawdius_core::llmLLM client and configuration
clawdius_core::sessionSession types and storage
clawdius_core::contextContext building and mentions
clawdius_core::output::OutputFormatOutput format enum
clawdius_core::diffDiff types and rendering
clawdius_core::timelineTimeline and checkpoints
clawdius_core::completionsCode completion handler
clawdius_core::config::KeyringStorageKeyring storage (feature-gated)

Breaking Changes

Breaking changes to the public API will only occur with a major version bump (following SemVer). The project is currently at rc.1, indicating the API is nearing stability but may still change.

Unsafe Code Policy

[workspace.lints.rust]
unsafe_code = "deny"

All unsafe code is denied at the workspace level. This is a hard constraint across all crates.

Lint Policy

[workspace.lints.rust]
missing_docs = "warn"
rust_2018_idioms = { level = "warn", priority = -1 }

[workspace.lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "warn"
expect_used = "warn"
panic = "warn"
todo = "warn"

CI enforces stricter checks than the baseline workspace lints.

Feature Flags

Feature flags are considered part of the API contract. Adding a new feature flag is not a breaking change. Removing or changing the behavior of an existing flag requires a major version bump.

See the Rust API page for the full feature flag reference.

Error Type Stability

The Error enum is extended with new variants as non-breaking additions. Existing variants and their Display messages are stable.

CLI Stability

CLI command names, flags, and argument formats are part of the public API. Changes follow SemVer conventions.

Deprecation Policy

Deprecated APIs will emit warnings for at least one minor version before removal. Deprecated items are documented in the changelog.

Rust API

The clawdius-core crate provides the programmatic interface to Clawdius.

Adding the Dependency

[dependencies]
clawdius-core = "1.0.0-rc.1"

Quick Start

use clawdius_core::{Config, SessionManager};
use clawdius_core::llm::{create_provider, LlmConfig, ChatMessage, ChatRole};
use clawdius_core::tools::shell::{ShellTool, ShellParams};
use clawdius_core::config::ShellSandboxConfig;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> clawdius_core::Result<()> {
    let config = Config::load_default()?;

    let llm_config = LlmConfig::from_config(&config.llm, "anthropic")?;
    let provider = create_provider(&llm_config)?;

    let messages = vec![ChatMessage {
        role: ChatRole::User,
        content: "Hello, Clawdius!".into(),
    }];

    let response = provider.chat(messages).await?;
    println!("Response: {}", response);

    Ok(())
}

Core Modules

Configuration (config)

#![allow(unused)]
fn main() {
use clawdius_core::Config;

let config = Config::load_default()?;
let config = Config::load(Path::new("custom.toml"))?;
let config = Config::load_or_default();
config.save(Path::new("output.toml"))?;
}

Sessions (session)

#![allow(unused)]
fn main() {
use clawdius_core::SessionManager;

let manager = SessionManager::new(&config)?;
let mut session = manager.get_or_create_active()?;
manager.add_message(&mut session, msg).await?;
}

LLM (llm)

#![allow(unused)]
fn main() {
use clawdius_core::llm::{create_provider, create_provider_with_retry, LlmConfig};

let config = LlmConfig::from_env("anthropic")?;
let provider = create_provider(&config)?;

let with_retry = create_provider_with_retry(&config, None)?;
}

Context (context)

#![allow(unused)]
fn main() {
use clawdius_core::MentionResolver;

let resolver = MentionResolver::new(project_dir);
let items = resolver.resolve_all("@src/main.rs explain this").await?;
}

Timeline (timeline)

#![allow(unused)]
fn main() {
use clawdius_core::timeline::TimelineManager;

let manager = TimelineManager::new(PathBuf::from("./project"))?;
let checkpoint = manager.create_checkpoint("before-refactor", None, None)?;
let history = manager.get_file_history("src/main.rs", Some(20))?;
}

Completions (completions)

use clawdius_core::completions::{CompletionHandler, CompletionConfig, CompletionRequest};

let mut handler = CompletionHandler::new(CompletionConfig::default());
let result = handler.complete(CompletionRequest {
    code: "fn main() { let x = ".into(),
    language: "rust".into(),
    cursor_position: 26,
    file_path: None,
    context: None,
})?;

Feature Flags

FeatureDescriptionDependencies
keyringSystem keyring for API keyskeyring
vector-dbLanceDB vector searchlancedb, arrow
embeddingsLocal ML embeddingstokenizers, hf-hub
local-llmLocal LLM inferencecandle-core, candle-nn
browserBrowser automationchromiumoxide
crash-reportingSentry crash reportssentry
postgresPostgreSQL sessionstokio-postgres
mariadbMariaDB sessionsmysql_async
redis-queueRedis orchestrator queueredis

Error Handling

#![allow(unused)]
fn main() {
use clawdius_core::Error;

match result {
    Ok(data) => { /* ... */ },
    Err(Error::RateLimited { retry_after_ms }) => {
        println!("Wait {}ms", retry_after_ms);
    },
    Err(Error::ContextLimit { current, limit }) => {
        println!("Context full: {}/{}", current, limit);
    },
    Err(e) => eprintln!("Error: {}", e.user_message()),
}
}

Check retryability:

#![allow(unused)]
fn main() {
if error.is_retryable() {
    if let Some(ms) = error.retry_after_ms() {
        tokio::time::sleep(Duration::from_millis(ms)).await;
    }
}
}

Docs

API documentation is available at docs.rs/clawdius-core.

JSON-RPC Protocol

Clawdius uses JSON-RPC for communication between editor extensions and the core engine.

Overview

The clawdius-code binary acts as a JSON-RPC server, communicating with editor extensions over stdio. The protocol follows the JSON-RPC 2.0 specification.

Transport

JSON-RPC messages are exchanged over standard input/output:

Editor Extension (TypeScript)
    │ stdin/stdout
    ▼
clawdius-code Binary
    │ Rust API calls
    ▼
clawdius-core Library

Request Format

{
  "jsonrpc": "2.0",
  "method": "semantic_search",
  "params": {
    "query": "error handling",
    "limit": 10
  },
  "id": 1
}

Response Format

Success

{
  "jsonrpc": "2.0",
  "result": {
    "matches": [...]
  },
  "id": 1
}

Error

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32600,
    "message": "Invalid params"
  },
  "id": 1
}

Standard Methods

MethodDescriptionParams
semantic_searchSearch codebase by queryquery, limit
get_contextGet context for a filepath, line, column
chatSend a chat messagemessage, session_id, mode
get_sessionGet session detailssession_id
list_sessionsList all sessions-
create_checkpointCreate a checkpointdescription
get_completionGet code completionfile, line, column, language
git_statusGet git status-
git_diffGet git diffstaged

JSON-RPC Server (Gateway)

The clawdius-gateway crate provides an HTTP-based JSON-RPC server using jsonrpsee:

clawdius server --host 0.0.0.0 --port 8080

This exposes the same methods over HTTP/WebSocket for remote access.

Library

The jsonrpsee crate provides both server and client implementations:

[workspace.dependencies]
jsonrpsee = { version = "0.24", features = ["server", "client", "ws-client"] }

Error Codes

CodeMeaning
-32700Parse error
-32600Invalid request
-32601Method not found
-32602Invalid params
-32603Internal error

VSCode Extension Commands

The VSCode extension communicates via JSON-RPC:

CommandDescription
Clawdius: Ask a questionOpen chat input
Clawdius: Chat with selectionChat about selected code
Clawdius: Add file to contextAdd file to conversation
Clawdius: Create checkpointSave current state
Clawdius: Open chat viewOpen sidebar chat

Plugin API

Clawdius supports a WASM-based plugin system with 26 hook types.

Overview

Plugins extend Clawdius's functionality by running custom logic in an isolated WASM runtime. This ensures plugins cannot compromise the host system.

Plugin Architecture

┌─────────────────────────┐
│    Clawdius Host         │
│  ┌───────────────────┐  │
│  │  Plugin Manager   │  │
│  │  ┌─────────────┐  │  │
│  │  │  WASM Runtime│  │  │
│  │  │  (Wasmtime)  │  │  │
│  │  └─────────────┘  │  │
│  └───────────────────┘  │
└─────────────────────────┘

Hook Types

Plugins can register handlers for 26 different lifecycle hooks:

CategoryHooks
Sessionsession_start, session_end, message_sent, message_received
Tooltool_before_execute, tool_after_execute, tool_error
LLMllm_before_request, llm_after_response, llm_error
Filefile_read, file_write, file_delete
Checkpointcheckpoint_created, checkpoint_restored
Gitgit_commit, git_push, git_checkout
Sandboxsandbox_enter, sandbox_exit, sandbox_violation
Configconfig_loaded, config_changed
Systemstartup, shutdown, error

Creating a Plugin

Plugins are WASM modules written in Rust (or any language that compiles to WASM):

#![allow(unused)]
fn main() {
// plugin/src/lib.rs
use clawdius_plugin_api::{register_hook, HookContext, HookResult};

#[register_hook("tool_after_execute")]
fn log_tool_usage(ctx: &HookContext) -> HookResult {
    println!("Tool {} executed in {}ms",
        ctx.params["tool"],
        ctx.params["duration_ms"]);
    HookResult::ok()
}
}

Plugin Configuration

Plugins are configured in .clawdius/config.toml or a separate plugins file:

[plugins]
load = ["./plugins/my-plugin.wasm"]

[plugins.hooks]
tool_after_execute = ["my-plugin"]

Plugin API Surface

Plugins receive a HookContext containing:

FieldTypeDescription
hook_name&strName of the triggered hook
paramsMap<String, Value>Hook-specific parameters
session_idOption<&str>Active session ID
config&ValueCurrent configuration

Plugins return a HookResult:

VariantDescription
ok()Allow the operation to proceed
block(reason)Block the operation
modify(data)Modify the operation's data

Security Model

  • Plugins run in WASM with capability-based permissions
  • No filesystem access unless explicitly granted
  • No network access unless explicitly granted
  • Fuel-based execution limits prevent infinite loops
  • Memory isolation prevents host memory corruption

Distribution

Plugins can be distributed as .wasm files and loaded from:

  • Local filesystem paths
  • The plugin marketplace (planned)
  • Remote URLs (with integrity verification)

Performance Tuning

This section is under development.

Refer to the repository for current implementation details.

Security Hardening

This section is under development.

Refer to the repository for current implementation details.

Self-Hosted Deployment

This section is under development.

Refer to the repository for current implementation details.

Formal Verification

This section is under development.

Refer to the repository for current implementation details.

Configuration Schema

The Clawdius configuration file is a TOML document with the following schema.

File Locations

Clawdius looks for configuration in this order (later overrides earlier):

  1. .clawdius/config.toml (default)
  2. clawdius.toml (in current directory)
  3. Path specified by --config / -C flag

Top-Level Schema

[project]
name = "my-project"
rigor_level = "high"           # low | medium | high
lifecycle_phase = "context_discovery"

[workspace]
name = "default"
storage = "sqlite"              # sqlite | postgres | mariadb
database_path = ".clawdius/workspace.db"
postgres_url = ""               # For postgres backend
mariadb_url = ""                # For mariadb backend
per_project_tokens = 2000
max_total_tokens = 8000

[storage]
database_path = ".clawdius/graph/index.db"
vector_path = ".clawdius/graph/vectors.lance"
sessions_path = ".clawdius/sessions.db"

[llm]
default_provider = "anthropic"  # anthropic | openai | ollama | zai | deepseek | google
max_tokens = 4096

[llm.anthropic]
model = "claude-sonnet-4-20250514"
api_key_env = "ANTHROPIC_API_KEY"
api_key = ""                    # Not recommended
base_url = ""                   # Custom endpoint

[llm.openai]
model = "gpt-4o"
api_key_env = "OPENAI_API_KEY"

[llm.ollama]
model = "llama3.2"
base_url = "http://localhost:11434"

[llm.retry]
max_retries = 3
initial_delay_ms = 1000
max_delay_ms = 30000
exponential_base = 2.0
retry_on = ["rate_limit", "timeout", "server_error", "network_error"]

[session]
compact_threshold = 0.85
keep_recent = 4
min_messages = 10
auto_save = true

[output]
show_progress = true
format = "text"                # text | json | stream-json

[shell_sandbox]
blocked_commands = [
    "rm -rf /",
    "mkfs",
    "dd if=/dev/zero",
]
timeout_secs = 120
max_output_bytes = 1048576
restrict_to_cwd = true

Section Reference

[project]

KeyTypeDefaultDescription
namestring"clawdius"Project name
rigor_levelstring"high"Rigor level: low, medium, high
lifecycle_phasestring"context_discovery"Current Nexus FSM phase

[storage]

KeyTypeDefaultDescription
database_pathpath.clawdius/graph/index.dbSQLite database path
vector_pathpath.clawdius/graph/vectors.lanceLanceDB vector store path
sessions_pathpath.clawdius/sessions.dbSessions database path

[llm]

KeyTypeDefaultDescription
default_providerstring(none)Default LLM provider
max_tokensinteger4096Maximum response tokens

[session]

KeyTypeDefaultDescription
compact_thresholdfloat0.85Auto-compact at this context fraction
keep_recentinteger4Messages to keep when compacting
min_messagesinteger10Minimum messages before compacting
auto_savebooleantrueAuto-save sessions

[shell_sandbox]

KeyTypeDefaultDescription
blocked_commandsarray of strings(see defaults)Blocked command patterns
timeout_secsinteger120Command timeout in seconds
max_output_bytesinteger1048576Maximum output size in bytes
restrict_to_cwdbooleantrueRestrict to project directory

[llm.retry]

KeyTypeDefaultDescription
max_retriesinteger3Maximum retry attempts
initial_delay_msinteger1000Initial delay in ms
max_delay_msinteger30000Maximum delay cap in ms
exponential_basefloat2.0Backoff multiplier
retry_onarray of strings(all)Conditions: rate_limit, timeout, server_error, network_error

Viewing Configuration

clawdius config show       # Show current config (API keys masked)
clawdius config path       # Show config file path
clawdius config list       # List available keys
clawdius config get llm.default_provider
clawdius config set llm.default_provider openai

Environment Variable Overrides

API keys can be set via environment variables (highest priority):

VariableProvider
ANTHROPIC_API_KEYAnthropic
OPENAI_API_KEYOpenAI
DEEPSEEK_API_KEYDeepSeek
ZAI_API_KEYZ.AI
OLLAMA_BASE_URLOllama server URL

CLI Commands

Complete reference for all Clawdius CLI commands.

Global Flags

FlagShortDescription
--no-tui-nRun without TUI (headless mode)
--cwd-wWorking directory (default: .)
--output-format-fOutput format: text, json, stream-json
--quiet-qSuppress progress indicators
--config-CPath to config file
--lang-LOutput language (en, zh, ja, ko, de, fr, es, it, pt, ru)

Commands

clawdius chat [MESSAGE]

Send a message to the LLM.

FlagShortDescriptionDefault
--provider-PLLM provideranthropic
--model-mModel to useProvider default
--session-sSession ID to continueNew session
--mode-MAgent modecode
--editor-eOpen external editorDisabled
--exitNon-interactive modeAuto
--quietSuppress output except responseDisabled
--auto-approveAuto-approve tool executionsDisabled

clawdius auto <TASK>

Autonomous CI/CD mode.

FlagDescriptionDefault
--providerLLM provideranthropic
--modelModelProvider default
--max-iterationsMax iterations50
--run-testsRun tests after changesDisabled
--auto-commitCommit automaticallyDisabled
--fail-on-test-failureFail on test failureDisabled
--output-formatCI output formattext

clawdius init [NAME]

Initialize a Clawdius project.

clawdius setup [--quick] [--provider]

Interactive setup wizard.

clawdius sessions [--delete ID] [--search QUERY]

List and manage sessions.

clawdius generate <PROMPT>

Generate code with AI.

FlagShortDescriptionDefault
--files-fTarget files (comma-separated)None
--mode-Msingle-pass, iterative, agentsingle-pass
--trust-Tlow, medium, highmedium
--max-iterations-iMax iterations5
--dry-runPreview onlyDisabled
--provider-PLLM provideranthropic
--model-mModelProvider default

clawdius git <COMMAND>

CommandDescription
commit [FILES...]Stage and commit with AI message
diffShow working diff
diff --stagedShow staged diff
statusShow git status

clawdius checkpoint <COMMAND>

CommandDescription
create <desc>Create a checkpoint
listList checkpoints
show <id>Show checkpoint details
restore <id>Restore a checkpoint
compare <id1> <id2>Compare two checkpoints
delete <id>Delete a checkpoint
cleanup --keep NKeep only N most recent

clawdius timeline <COMMAND>

CommandDescription
create <name>Create timeline entry
listList entries
watchAuto-create on file changes
rollback <id>Rollback to checkpoint
diff <from> <to>Compare checkpoints
history <file>File change history

clawdius auth <COMMAND> (requires keyring feature)

CommandDescription
set <provider>Store API key
get <provider>Retrieve API key
delete <provider>Delete API key

clawdius modes <COMMAND>

CommandDescription
listList all modes
create <name>Create custom mode
show <name>Show mode details

clawdius models <COMMAND>

CommandDescription
listList local models
pull <model>Pull a model
healthCheck Ollama server
currentShow current model

clawdius sprint <TASK>

Run a multi-phase agentic sprint.

FlagDescriptionDefault
--max-iterationsMax build-test iterations3
--real-executionEnable real executionDisabled
--auto-approveSkip confirmationsDisabled
--providerLLM providerdeepseek
--modelModelProvider default
--resumeResume from saved stateDisabled

clawdius config <COMMAND>

CommandDescription
showShow current config (keys masked)
get <key>Get a config value
set <key> <value>Set a config value
pathShow config file path
listList available keys

Other Commands

CommandDescription
clawdius refactor --from LANG --to LANG [PATH]Cross-language refactoring
clawdius test <FILE>Generate tests
clawdius doc <FILE>Generate documentation
clawdius analyze [PATH]Architecture drift analysis
clawdius watch [PATH]Watch files for changes
clawdius editEdit prompt in external editor
clawdius memoryManage project memory
clawdius webhookManage webhooks
clawdius metricsShow performance metrics
clawdius telemetryConfigure telemetry
clawdius complete <FILE> <LINE> <COL>Code completions
clawdius verify --proof PATHLean 4 proof verification
clawdius server --host H --port PHTTP server
clawdius shipPre-ship checks and commit messages
clawdius skillList and execute skills

Error Codes

Reference for Clawdius error types and their meanings.

Core Error Type

The clawdius_core::Error enum is the top-level error type. It is defined in crates/clawdius-core/src/error/mod.rs.

Error Variants

Configuration

VariantMessage TemplateRetryableDescription
Config(msg)Configuration error: {msg}NoInvalid or missing configuration

LLM

VariantMessage TemplateRetryableDescription
Llm(msg)LLM error: {msg}NoGeneral LLM failure
LlmProvider { message, provider }LLM provider error from {provider}: {message}NoProvider-specific error
RateLimited { retry_after_ms }Rate limited. Retry after {retry_after_ms}msYesHTTP 429 rate limit
ContextLimit { current, limit }Context limit exceeded: {current}/{limit} tokensNoToken budget exceeded
RetryExhausted(n)Retry exhausted after {n} attemptsNoAll retries failed
CircuitBreakerOpen { service, last_error }Circuit breaker open for {service}YesService circuit open
QuotaExceeded(msg)Quota exceeded: {msg}NoAPI quota limit reached

Tool Execution

VariantMessage TemplateRetryableDescription
ToolExecution { tool, reason }Tool execution failed '{tool}': {reason}NoTool failed
Tool(msg)Tool error: {msg}NoTool configuration error
Sandbox(msg)Sandbox error: {msg}NoSandbox violation

Session

VariantMessage TemplateRetryableDescription
Session(msg)Session error: {msg}NoGeneral session error
SessionNotFound { id }Session not found: {id}NoInvalid session ID

I/O and Serialization

VariantMessage TemplateRetryableDescription
Io(err)IO error: {err}NoFile system error
Serialization(err)Serialization error: {err}NoJSON error
TomlDe(err)TOML deserialization error: {err}NoConfig parse error
TomlSer(err)TOML serialization error: {err}NoConfig write error
Database(err)Database error: {err}NoSQLite error
Network(msg)Network error: {msg}NoNetwork failure

System

VariantMessage TemplateRetryableDescription
Timeout(duration)Operation timed out after {duration:?}YesOperation timeout
CancelledOperation cancelledNoUser cancelled
Internal(msg)Internal error: {msg}NoBug in Clawdius
NotFound(msg)Not found: {msg}NoResource not found
InvalidInput(msg)Invalid input: {msg}NoBad user input
ParseError(msg)Parse error: {msg}NoParse failure
UnsupportedLanguage(msg)Unsupported language: {msg}NoLanguage not supported

Additional

VariantMessage TemplateRetryableDescription
Auth(msg)Authentication error: {msg}NoAuth failure
Checkpoint(msg)Checkpoint error: {msg}NoCheckpoint failure
Brain(msg)Brain runtime error: {msg}NoWASM runtime error
Rpc(msg)RPC error: {msg}NoJSON-RPC error
Model(msg)Model error: {msg}NoModel loading error
Processing(msg)Processing error: {msg}NoData processing error
Sprint(msg)Sprint error: {msg}NoSprint execution error

Error Helper Methods

#![allow(unused)]
fn main() {
use clawdius_core::Error;

let error = Error::RateLimited { retry_after_ms: 5000 };

error.is_retryable();       // true
error.retry_after_ms();      // Some(5000)
error.is_rate_limited();     // true
error.is_timeout();          // false
error.is_circuit_breaker();  // false
error.user_message();        // Human-friendly message
}

Retry Logic

Errors are retryable when is_retryable() returns true. The retry system uses exponential backoff:

delay = min(initial_delay * base^attempt + jitter, max_delay)

Default values: initial_delay = 1000ms, base = 2.0, max_delay = 30000ms.

Enhanced Errors

The EnhancedError type provides rich, actionable error messages with context, suggestions, and documentation links:

#![allow(unused)]
fn main() {
use clawdius_core::error::ErrorHelpers;

let error = ErrorHelpers::file_not_found("/path/to/file");
println!("{}", error.format_pretty());
}

Glossary

This section is under development.

Refer to the repository for current implementation details.

Contributing

Contributions to Clawdius are welcome. This guide covers the development workflow.

Getting Started

Prerequisites

  • Rust 1.92+ (see rust-version in Cargo.toml)
  • A C compiler (for bundled SQLite)
  • Git

Building from Source

git clone https://github.com/WyattAu/clawdius
cd clawdius
cargo build --release

Running Tests

# All tests
cargo test --all

# Specific crate
cargo test -p clawdius-core

# With verbose output
cargo test --all -- --nocapture

Development Commands

# Check all crates compile
cargo check --all

# Run clippy (warnings allowed in dev)
cargo clippy --all-targets --all-features

# Format code
cargo fmt --all

# Check formatting
cargo fmt --all -- --check

# Run benchmarks
cargo bench --all

Code Style

The project enforces strict linting rules:

LintLevel
unsafe_codedeny
missing_docswarn
pedanticwarn
unwrap_usedwarn
expect_usedwarn
panicwarn
todowarn

CI runs with stricter flags (-D warnings).

Commit Messages

Follow Conventional Commits format:

type(scope): description

feat(core): add retry logic for rate limits
fix(cli): handle missing session ID gracefully
docs(api): update error codes reference
refactor(sandbox): extract sandbox config into struct

Pull Request Process

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run cargo test --all and cargo clippy --all-targets --all-features
  5. Run cargo fmt --all
  6. Open a pull request

Project Structure

clawdius/
├── crates/
│   ├── clawdius/          # CLI binary
│   ├── clawdius-core/     # Core library
│   ├── clawdius-code/     # VSCode helper
│   ├── clawdius-gateway/  # HTTP gateway
│   └── clawdius-mcp/      # MCP server
├── editors/vscode/        # VSCode extension
├── docs/book/src/         # mdBook documentation
├── .docs/                 # Internal docs
└── Cargo.toml             # Workspace root

Adding a New Crate

mkdir crates/clawdius-newfeature
cd crates/clawdius-newfeature
cargo init --lib

Then add to workspace Cargo.toml:

members = [
    # ...existing...
    "crates/clawdius-newfeature",
]

Feature Flags

When adding new functionality, consider whether it should be behind a feature flag. See crates/clawdius-core/Cargo.toml for existing patterns.

Reporting Issues

Use the GitHub issue tracker at https://github.com/WyattAu/clawdius/issues.

Include:

  • Rust version (rustc --version)
  • Clawdius version (clawdius --version)
  • Operating system
  • Steps to reproduce
  • Expected vs actual behavior
  • Relevant log output (RUST_LOG=clawdius=debug)

Code of Conduct

Our Pledge

We are committed to providing a welcoming and inclusive experience for everyone. All participants in the Clawdius project are expected to adhere to the following standards of conduct.

Standards

  • Be respectful in all interactions (issues, PRs, discussions, documentation).
  • Accept constructive criticism gracefully.
  • Focus on what is best for the project and its users.
  • Show empathy toward other community members.

Unacceptable Behavior

  • Harassment, discrimination, or exclusionary language.
  • Personal attacks, insults, or trolling.
  • Publishing private information without consent.
  • Any conduct that would be inappropriate in a professional setting.

Enforcement

Instances of unacceptable behavior may be reported by contacting team@clawdius.dev. The maintainers will review and respond to all reports.

Scope

This code of conduct applies to all project spaces (GitHub, Discord, documentation, conferences) and to all project participants (maintainers, contributors, users).

Attribution

Adapted from the Contributor Covenant, version 2.1.

Changelog

All notable changes to the Clawdius project are documented here.

[1.0.0-rc.1] - Current

Added

  • Interactive setup wizard (clawdius setup)
  • Agentic sprint system (clawdius sprint)
  • Ship command for pre-ship checks and commit messages
  • Skill system for markdown-based skills
  • HTTP server (clawdius server)
  • Config management commands (clawdius config)
  • Project memory system (clawdius memory)
  • Webhook management (clawdius webhook)
  • Multi-language output support (en, zh, ja, ko, de, fr, es, it, pt, ru)
  • Messaging gateway with multi-platform support (Telegram, Discord, Slack, Matrix, Signal, WhatsApp, Rocket.Chat)
  • Multi-tenant configuration
  • Audit logging with multiple backends (file, SQLite, Elasticsearch, webhook)
  • PII redaction in logs
  • State store encryption at rest (AES-256-GCM)
  • API key rotation with JWT auth
  • IP allowlisting for webhook requests
  • Redis-backed orchestrator queue
  • PostgreSQL and MariaDB session storage backends
  • Stripe billing integration
  • Browser automation (chromiumoxide)
  • Enhanced code completions with LRU caching
  • File watching with auto-analysis
  • LSP client integration

Changed

  • Migrated to deny(unsafe_code) workspace-wide
  • Updated minimum Rust version to 1.88
  • Improved retry system with jitter and dead letter queues
  • Enhanced error messages with user-friendly suggestions

Security

  • Fixed RUSTSEC-2026-0037 (quinn-proto via reqwest chain)
  • Fixed RUSTSEC-2026-0044, RUSTSEC-2026-0048, RUSTSEC-2026-0049 (lancedb)
  • Fixed RUSTSEC-2025-0052 (async-std via chromiumoxide)
  • Fixed RUSTSEC-2026-0002 (unsound IterMut)

[0.7.0]

Added

  • Nexus 24-phase FSM engine
  • Quality gate system
  • Artifact tracking with SQLite
  • Graph-RAG with AST index and vector store
  • Multi-tier sandboxing (WASM, bubblewrap, containers)
  • Timeline and checkpoint system
  • Session management with auto-compaction
  • Shell tool with command blocking
  • File and git tools
  • JSON output format for all commands
  • Keyring-based API key storage

[0.6.0]

Added

  • Initial CLI with chat, init, status commands
  • Anthropic Claude support
  • OpenAI support
  • Ollama local model support
  • Basic configuration via TOML
  • tree-sitter code analysis (Rust, Python, JS, TS, Go)

Earlier Versions

See git history for detailed changes before version 0.6.0.

Support

Reporting Issues

Bug reports and feature requests should be filed on the GitHub issue tracker.

When filing a bug report, include:

  • Clawdius version (clawdius --version)
  • Rust toolchain version (rustc --version)
  • Operating system and architecture
  • Minimal reproduction steps
  • Relevant log output (enable with RUST_LOG=debug)

Security Vulnerabilities

Do not report security vulnerabilities via public issues. See SECURITY.md for the responsible disclosure process.

Community

Professional Support

Enterprise support contracts are available. Contact team@clawdius.dev for details.