Architecture Overview

xbot is a pure Rust autonomous agent runtime built on tokio async runtime and axum HTTP framework. Core design principles: single binary, no GPU dependency, unified message bus architecture.

Architecture Diagram

CLI / TUI (Ratatui) / Gateway (Axum) — Entry Layer
Engine — AgentLoop / Orchestrator / Subagents / Memory / Skills / Hooks
Tools — Registry / Executor (12 built-in + MCP dynamic)
Providers — LLM Abstraction (26 providers, OpenAI-compatible + Anthropic native)
Channels — 13 backends (ChannelManager + plugin registry)
Storage — MessageBus / SessionManager (JSONL persistence)

Module Structure

51 Rust source files, 19 integration test files.

tree
src/
├── main.rs              # CLI entry, clap command routing
├── lib.rs               # Library root
├── config.rs            # Configuration loading/saving/validation
├── tools.rs             # Tool definitions, registry, execution engine
├── cron.rs              # Cron scheduling service (At/Every/Cron)
├── observability.rs     # Prometheus metrics, CPU/memory snapshots
├── security.rs          # URL validation, workspace sandboxing
├── diff.rs              # Diff rendering for file edit approval
├── util.rs              # Utility functions
├── cli/                 # CLI subcommands
│   ├── config_cli.rs    # Interactive provider/channel config
│   ├── channels_cli.rs  # Channel management commands
│   └── skills_cli.rs    # Skill management commands
├── tui/                 # Ratatui TUI
│   ├── app.rs           # TUI application state
│   ├── ui.rs            # Terminal rendering
│   └── markdown.rs      # Markdown-to-TUI rendering
├── channels/            # 13 channel implementations
│   ├── slack.rs         # Socket Mode + Webhook
│   ├── telegram.rs      # Webhook + REST
│   ├── discord.rs       # Gateway v10 WebSocket
│   ├── feishu.rs        # Webhook + REST
│   ├── dingtalk.rs      # Stream gateway WebSocket
│   ├── matrix.rs        # CS API v3 long-poll
│   ├── whatsapp.rs      # Baileys WebSocket bridge
│   ├── qq.rs            # QQ Bot API WebSocket
│   ├── wecom.rs         # Enterprise WeChat WebSocket
│   ├── weixin.rs        # HTTP long-poll (QR login)
│   ├── mochat.rs        # HTTP polling
│   └── email.rs         # IMAP + SMTP
├── engine/              # Agent core
│   ├── orchestrator.rs  # Main agent orchestration
│   ├── context.rs       # Context window management
│   ├── memory.rs        # Memory consolidation engine
│   ├── skills.rs        # Skill loading and matching
│   ├── subtasks.rs      # Subagent spawn/wait
│   └── hook.rs          # AgentHook trait + CallbackHook
├── providers/           # LLM abstractions
│   ├── registry.rs      # 26-provider registry + auto-detect
│   ├── anthropic.rs     # Native Anthropic Messages API
│   └── transcription.rs # Groq audio transcription
├── runtime/             # Runtime services
│   ├── bootstrap.rs     # Startup orchestration
│   ├── worker.rs        # AgentRuntime with semaphore
│   ├── http.rs          # Axum HTTP server + webhooks
│   └── heartbeat.rs     # Periodic autonomous review
├── storage/             # Persistence
│   ├── message_bus.rs   # Inbound/outbound message queues
│   └── session_store.rs # JSONL session persistence
└── integrations/        # External integrations
    └── mcp.rs           # MCP stdio protocol client

Message Processing Flow

  1. Channel receives message → InboundMessage → MessageBus

  2. AgentRuntime (global semaphore + per-session mutex) → AgentLoop

  3. Agent builds context (memory + skills + history) → calls LLM

  4. LLM returns tool calls → ToolRegistry parallel execution (max 5 concurrent)

  5. Agent persists session → OutboundMessage → MessageBus → ChannelManager (retry + streaming)

Development Setup

  1. curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

  2. git clone https://github.com/guoqingbao/xbot.git && cd xbot

  3. cargo build --release && cargo run --release -- --help

Testing

19 integration test files using wiremock for HTTP mocking and serial_test for mutual exclusion.

bash
cargo test                                          # All tests
cargo test --test test_config -- load_config         # Single test
cargo test --lib config                               # Module tests
cargo test -- --nocapture                             # Show output
cargo check                                          # Fast compile check

Code Style

bash
cargo fmt                             # Format all code
cargo fmt --check                      # Check formatting
cargo clippy -- -D warnings            # Lint (warnings = errors)

Naming: modules snake_case, types PascalCase, functions/variables snake_case, constants SCREAMING_SNAKE_CASE.

Custom Skills

Skills live in skills/<name>/SKILL.md with YAML frontmatter for metadata:

bash
xbot skills init my-skill
yaml
---
name: my-skill
description: Brief description of the skill
metadata:
  rbot:
    triggers: [pattern1, pattern2]
    priority: 50
---

# Instructions for the agent follow here...

Hook System

Implement the AgentHook trait to inject custom behavior into the agent lifecycle:

CallbackWhen
before_iterationBefore each agent iteration
on_streamEach delta of LLM streaming response
on_stream_endEnd of LLM streaming response
before_execute_toolsBefore tool execution
after_iterationAfter each agent iteration
finalize_contentBefore final content output

Developing New Channels

Add a new module in src/channels/ implementing ingress and delivery interfaces. Reference existing channels (slack.rs, discord.rs) for the pattern. Register with ChannelManager or use the register_plugin() API.

Deployment Pattern

  1. Use a stable workspace path (~/.xbot/workspace or dedicated project directory)

  2. Use a process supervisor (systemd, launchd, Docker, Kubernetes)

  3. Point webhook channels at a stable public URL

  4. Expose /metrics to Prometheus monitoring

  5. Review .xbot/HEARTBEAT.md and cron jobs regularly

Concurrency & Safety

MechanismDescription
Global semaphoremaxConcurrentRequests (default: 3)
Per-session mutexMessages for same session serialized
Parallel tool executionmaxConcurrentTools (default: 5)
Subagent concurrencyMax 3 concurrent subagents
Message retry backoffsendMaxRetries (default: 3, 1s/2s/4s...)
Memory consolidationLLM-driven + raw archive after 3 failures

Observability

xbot provides Prometheus-format metrics, CPU/memory snapshots, provider model catalog probing, and structured logging.

bash
# Prometheus metrics
curl http://localhost:18790/metrics

# Runtime status
curl http://localhost:18790/status | jq

# CLI status
xbot status