Skip to main content

Architecture Overview

ClawDesk is a multi-channel AI agent gateway built in Rust. It routes conversations from any messaging platform through a unified agent pipeline, executes tool calls, manages memory, and streams responses—all while enforcing security, observability, and fault tolerance guarantees.

Design Philosophy

ClawDesk follows five core architectural principles:

PrincipleDescriptionEnforcement
Hexagonal ArchitectureBusiness logic is isolated from I/O via port traits and adapter implementationsclawdesk-storage defines ports; clawdesk-sochdb provides adapters
Type-Driven CorrectnessAlgebraic sum types make illegal states unrepresentableInboundMessage enum, ValidatedConfig, ClawDeskError
Structured ConcurrencyEvery spawned task is owned, tracked, and cancellableCancellationToken trees, JoinSet scoping
Zero-Trust SecurityFour-layer cascade: ACL → allowlist → content scan → auditclawdesk-security crate
Compilation-Unit Isolation27 fine-grained crates maximize parallel compilation and enforce boundariesWorkspace Cargo.toml

System Context

High-Level Message Flow

Every inbound message follows a deterministic path through the system:

Subsystem Map

ClawDesk is composed of seven major subsystems, each implemented across one or more crates:

1. Channel Subsystem

Handles all inbound/outbound communication with messaging platforms.

CrateRole
clawdesk-typesInboundMessage sum type, ChannelId, ChannelMeta
clawdesk-channelLayered trait hierarchy (Channel → Threaded → RichChannel)
clawdesk-channelsConcrete adapter implementations (Slack, Discord, etc.)

2. Agent Subsystem

Core AI inference pipeline with tool execution.

CrateRole
clawdesk-agents6-stage pipeline, AgentRunner, ToolRegistry
clawdesk-providersProvider trait + implementations (Anthropic, OpenAI, etc.)
clawdesk-skillsComposable skill system with knapsack selector
clawdesk-runtimeDurable agent runtime with state persistence

3. Storage Subsystem

Persistent state with ACID guarantees and vector search.

CrateRole
clawdesk-storagePort traits: SessionStore, ConversationStore, VectorStore
clawdesk-sochdbSochDB adapter: MVCC, WAL, HNSW, TOON queries
clawdesk-memoryHybrid search (BM25 + embedding), reranking, batch ingest

4. Security Subsystem

Defense-in-depth with audit trail.

CrateRole
clawdesk-securityACL, allowlist, content scanner, hash-chained audit, tokens

5. Gateway Subsystem

HTTP/WebSocket server and API surface.

CrateRole
clawdesk-gatewayAxum server, 24+ routes, middleware, hot-reload
clawdesk-acpAgent Communication Protocol
clawdesk-tunnelSecure webhook tunneling

6. Plugin Subsystem

Extensibility through sandboxed plugins.

CrateRole
clawdesk-pluginPlugin host, dependency resolver, sandbox, registry

7. Observability Subsystem

Full-stack telemetry and monitoring.

CrateRole
clawdesk-observabilityOpenTelemetry tracing + metrics integration
clawdesk-telemetryOTLP export, structured events

Client Applications

ClawDesk ships three client binaries:

BinaryCrateTechnologyPurpose
clawdeskclawdesk-cliClap + TokioCommand-line interface
ClawDesk Desktopclawdesk-tauriTauri 2.0 + WebViewNative desktop application
ClawDesk TUIclawdesk-tuiRatatuiTerminal UI

All three connect to the same gateway server and share the same storage layer.

Utility & Infrastructure Crates

CrateRole
clawdesk-domainBusiness rules: auth, routing, fallback FSM, prompt building
clawdesk-infraInfrastructure utilities, platform abstractions
clawdesk-cronScheduled task execution with heartbeat monitoring
clawdesk-mediaMedia processing and transcoding
clawdesk-autoreplyAutomated reply rules and templates
clawdesk-browserHeadless browser integration
clawdesk-discoveryService discovery and registration

Crate Dependency Overview

The workspace contains 27 crates organized in a directed acyclic graph with a critical path depth of 6:

Critical Path

The longest compilation chain is: clawdesk-typesclawdesk-storageclawdesk-domainclawdesk-channelclawdesk-channelsclawdesk-gatewayclawdesk-cli (depth 6). All other crates compile in parallel branches.

Key Architectural Decisions

ADR-1: Hexagonal Architecture Over Layered

Context: ClawDesk must support multiple storage backends and channel adapters without coupling business logic to specific implementations.

Decision: Adopt hexagonal (ports-and-adapters) architecture. All I/O boundaries are defined as Rust traits in clawdesk-storage and clawdesk-channel.

Consequence: Any storage or channel implementation can be swapped without modifying business logic.

ADR-2: Fine-Grained Crate Decomposition

Context: A monolithic crate would lead to long compile times and unclear boundaries.

Decision: Decompose into 27 crates with explicit dependency edges.

Consequence: Maximum parallelism during cargo build. The critical path depth is only 6, enabling crates on independent branches to compile simultaneously.

ADR-3: Embedded Database Over External

Context: Requiring users to install and manage PostgreSQL or similar would increase operational complexity.

Decision: Embed SochDB as the primary storage engine, providing ACID transactions, vector search, and full-text search in a single binary.

Consequence: Zero external dependencies for storage. Single-binary deployment. Trade-off: no horizontal scaling of the database layer.

ADR-4: Algebraic Error Types

Context: Error handling must be exhaustive and composable across crate boundaries.

Decision: Use thiserror-derived enums with per-crate error types that compose via #[from] into ClawDeskError.

Consequence: The compiler enforces exhaustive error handling. No unwrap() in production code paths.

ADR-5: Tokio Single-Runtime

Context: Multiple runtimes would complicate task management and cancellation.

Decision: Single tokio::runtime::Runtime with structured concurrency via CancellationToken hierarchy.

Consequence: Clean shutdown propagation. All spawned tasks are trackable and cancellable.

Performance Characteristics

MetricTargetMechanism
Message latency (p99)< 50ms (excluding LLM)Zero-copy normalization, pre-allocated buffers
Concurrent channels1,000+Tokio task-per-channel, bounded channel backpressure
Memory per session< 8 KB baselineArena allocation, lazy context loading
Cold start< 500msLazy initialization, parallel crate loading
Hot reload< 100msArcSwap config, watcher-triggered
Vector search (10K docs)< 10msHNSW index with SochDB

What's Next

Explore each subsystem in detail: