Overview
OpenFang is built as a modular Rust workspace with 14 crates (13 code crates + xtask). The architecture follows a layered design where dependencies flow downward — lower crates depend on nothing above them. The entire system compiles to a single ~32MB binary with:- 137,728 lines of code
- 1,767+ passing tests
- Zero clippy warnings
- Cold start < 200ms
- 40 MB idle memory usage
14-Crate Structure
The
openfang-types crate sits at the bottom and contains no business logic — only shared type definitions used across all other crates.Crate Responsibilities
openfang-types — Core Types
openfang-types — Core Types
Foundation crate defining all shared data structures:
- Agent types:
AgentManifest,AgentId,SessionId,AgentEntry - Capability types:
Capabilityenum with pattern matching - Event types:
Eventenum for system-wide event bus - Tool types:
ToolDefinition,ToolResult, tool compatibility mappings - Config types:
KernelConfig,ModelConfig,ResourceQuota - Security types:
TaintLabel,TaintSet, Ed25519 manifest signing - Model catalog:
ModelCatalogEntry,ProviderInfo,ModelTier - Error types:
OpenFangErrorwith variant for every failure mode
#[serde(default)] for forward-compatible TOML parsing.Key files: agent.rs, capability.rs, config.rs, tool.rs, taint.rsopenfang-memory — Memory Substrate
openfang-memory — Memory Substrate
SQLite-backed memory substrate (schema v5) providing six layers:
- Structured KV Store: Per-agent JSON key-value storage with shared namespace
- Semantic Search: Vector embeddings with cosine similarity matching
- Knowledge Graph: Entity-relation storage with graph traversal
- Session Manager: Conversation history with token tracking
- Task Board: Shared task queue for multi-agent collaboration
- Usage Store: Token counts, cost estimates, model usage tracking
Arc<Mutex<Connection>> with spawn_blocking for async bridge. Runs five schema migrations automatically on boot.Key files: substrate.rs, structured.rs, session.rs, knowledge.rs, usage.rsopenfang-runtime — Agent Execution
openfang-runtime — Agent Execution
Agent execution engine containing:
- Agent loop:
run_agent_loop,run_agent_loop_streaming - 3 LLM drivers: Anthropic (native), Gemini (native), OpenAI-compatible (18+ providers)
- 23 built-in tools: File ops, web search, web fetch, shell exec, memory ops, etc.
- WASM sandbox: Wasmtime with dual fuel+epoch metering, watchdog thread
- MCP client/server: JSON-RPC 2.0 over stdio/SSE
- A2A protocol: AgentCard, task management
- Web search: 4-provider cascade (Tavily → Brave → Perplexity → DuckDuckGo)
- Loop guard: SHA256-based tool loop detection with circuit breaker
- Session repair: 7-phase message history validation
- Compactor: Block-aware session compaction
- Audit trail: Merkle hash chain for tamper-evident logging
KernelHandle trait for inter-agent tools without circular dependencies.Key files: agent_loop.rs, llm_driver.rs, tool_runner.rs, sandbox.rs, mcp.rsopenfang-kernel — Central Coordinator
openfang-kernel — Central Coordinator
The kernel assembles all subsystems:
- AgentRegistry: DashMap-based concurrent agent store
- AgentScheduler: Quota tracking per agent, hourly window reset
- CapabilityManager: DashMap-based capability grants with inheritance validation
- EventBus: Async broadcast channel for system events
- Supervisor: Health monitoring, panic/restart counters
- WorkflowEngine: Pipeline execution, run eviction cap 200
- TriggerEngine: Event pattern matching for automation
- BackgroundExecutor: Continuous/periodic agent loops
- ModelCatalog: 51 builtin models, 20+ aliases, 20 providers
- MeteringEngine: Cost tracking with USD estimates
- ModelRouter: TaskComplexity scoring for auto-selection
- AuthManager: RBAC with channel identity resolution
- HeartbeatMonitor: Agent health checks with anomaly detection
- SetupWizard: Natural language agent configuration
- SkillRegistry: 60 bundled skills + user-installed
KernelHandle for runtime to call back into kernel.Key files: kernel.rs, registry.rs, scheduler.rs, capabilities.rs, workflow.rsopenfang-api — HTTP API Server
openfang-api — HTTP API Server
Axum 0.8-based API server with 76 endpoints:
- REST routes: Agents, workflows, triggers, memory, channels, templates, models, providers, skills, ClawHub, MCP, health, status, version, shutdown
- WebSocket handler: Real-time agent chat with streaming
- SSE endpoint: Server-sent events for streaming responses
- OpenAI-compatible:
POST /v1/chat/completions,GET /v1/models - A2A endpoints:
/.well-known/agent.json,/a2a/*
- Bearer token auth
- Request ID injection
- Structured request logging
- GCRA rate limiter (cost-aware)
- Security headers (CSP, X-Frame-Options, HSTS, etc.)
- Health endpoint redaction
server.rs, routes.rs, middleware.rs, websocket.rsopenfang-channels — 40 Channel Adapters
openfang-channels — 40 Channel Adapters
Messaging platform integration with 40 adapters:Core (7): Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email
Enterprise (6): Teams, Mattermost, Google Chat, Webex, Feishu, Zulip
Social (8): LINE, Viber, Messenger, Mastodon, Bluesky, Reddit, LinkedIn, Twitch
Community (7): IRC, XMPP, Guilded, Revolt, Keybase, Discourse, Gitter
Privacy (7): Threema, Nostr, Mumble, Nextcloud Talk, Rocket.Chat, Ntfy, Gotify
Workplace (5): Pumble, Flock, Twist, DingTalk, WebhooksFeatures:
Enterprise (6): Teams, Mattermost, Google Chat, Webex, Feishu, Zulip
Social (8): LINE, Viber, Messenger, Mastodon, Bluesky, Reddit, LinkedIn, Twitch
Community (7): IRC, XMPP, Guilded, Revolt, Keybase, Discourse, Gitter
Privacy (7): Threema, Nostr, Mumble, Nextcloud Talk, Rocket.Chat, Ntfy, Gotify
Workplace (5): Pumble, Flock, Twist, DingTalk, WebhooksFeatures:
AgentRouterfor message routingBridgeManagerfor lifecycle coordinationChannelRateLimiterwith per-user DashMap trackingformatter.rsconverts Markdown → TelegramHTML/SlackMrkdwn/PlainTextChannelOverridesfor per-channel model/system_prompt/DM_policy/group_policy- DM/group policy enforcement
- Threading support for platforms that support it
bridge.rs, router.rs, formatter.rs, adapters in channels/openfang-wire — OFP Networking
openfang-wire — OFP Networking
OpenFang Protocol (OFP) for peer-to-peer agent communication:
- JSON-framed messages over TCP
- HMAC-SHA256 mutual auth: Nonce-based, constant-time verification
- PeerNode: Listens for connections and manages peers
- PeerRegistry: Tracks known remote peers and their agents
- Message types: Discover, Advertise, RouteMessage, Ping
NetworkConfig.shared_secret (required) and PeerConfig.Key files: peer.rs, registry.rs, auth.rs, protocol.rsopenfang-cli — Command-Line Interface
openfang-cli — Command-Line Interface
Clap-based CLI with:
- Commands:
init,start,status,doctor,agent,workflow,trigger,migrate,skill,channel,config,chat,mcp - Daemon auto-detect: Checks
~/.openfang/daemon.jsonand pings health endpoint. Uses HTTP when daemon is running, boots in-process kernel as fallback. - Built-in MCP server mode:
openfang mcp - Shell completions: Bash, Zsh, Fish
main.rs, commands/*.rs, daemon.rsopenfang-desktop — Tauri 2.0 App
openfang-desktop — Tauri 2.0 App
Native desktop application:
- Boots kernel in-process (no separate daemon)
- Runs Axum server on background thread with random port
- WebView points at
http://127.0.0.1:{random_port} - System tray: Show Window, Open in Browser, Status, Quit
- Single-instance enforcement: Prevents multiple app launches
- Desktop notifications: Via
tauri-plugin-notification - Hide to tray: Window close hides instead of quitting
- Mobile ready:
#[cfg(desktop)]guards +#[cfg_attr(mobile, tauri::mobile_entry_point)]
main.rs, server_thread.rs, tray.rsopenfang-migrate — Migration Engine
openfang-migrate — Migration Engine
Migration engine for importing from other frameworks:
- OpenClaw support: Converts YAML → TOML, maps tool names, imports agents/memory/channels
- LangChain/AutoGPT: Planned
- Migration reports: Imported items, skipped items, warnings
openclaw.rs, langchain.rs, report.rsopenfang-skills — Skill System
openfang-skills — Skill System
Pluggable tool bundles:
- 60 bundled skills compiled via
include_str!() - Skill types: Python, Node.js, WASM, PromptOnly
- SkillManifest: Metadata, runtime config, provided tools, requirements
- SkillRegistry: Manages installed and bundled skills
- FangHubClient: Native marketplace
- ClawHubClient: Cross-ecosystem compatibility with clawhub.ai
- SKILL.md parser: OpenClaw YAML frontmatter + Markdown body
- Security pipeline: SHA256 verification + prompt injection scanner
registry.rs, bundled.rs, fanghub.rs, clawhub.rs, verify.rsopenfang-hands — Autonomous Agents
openfang-hands — Autonomous Agents
7 bundled autonomous capability packages:
- Clip: YouTube → vertical shorts pipeline (8 phases)
- Lead: Daily lead generation with ICP matching
- Collector: OSINT-grade intelligence monitoring
- Predictor: Superforecasting with Brier scores
- Researcher: Deep research with CRAAP credibility checks
- Twitter: Autonomous X/Twitter account management
- Browser: Web automation with mandatory purchase approval
- Manifest declaring tools, settings, requirements, dashboard metrics
- System prompt (500+ word operational playbook)
- SKILL.md domain expertise reference
- Guardrails for sensitive actions
registry.rs, bundled.rs, lib.rs (HandDefinition types)openfang-extensions — Extensions & Vault
openfang-extensions — Extensions & Vault
Extensions system:
- 25 MCP templates: Pre-configured MCP server setups
- AES-256-GCM credential vault: Encrypted secret storage
- OAuth2 PKCE flow: For third-party integrations
vault.rs, mcp_templates.rs, oauth.rsxtask — Build Automation
xtask — Build Automation
Cargo-xtask pattern for build tasks:
cargo xtask test— run full test suitecargo xtask release— build optimized releasecargo xtask bundle— package for distribution
main.rsKernel Boot Sequence
WhenOpenFangKernel::boot_with_config() is called:
Arc:
Cold start time: < 200ms from process start to first API request.
Subsystem Diagram
Key Architectural Principles
- Dependency flows downward — lower crates never depend on upper crates
- Types crate is foundational — contains no business logic, only shared types
- KernelHandle trait — runtime can call back into kernel without circular deps
- Arc<Mutex<Connection>> — thread-safe SQLite access with async bridge
- DashMap everywhere — lock-free concurrent data structures for hot paths
- #[serde(default)] — forward-compatible config parsing
Performance Characteristics
| Metric | Value | Notes |
|---|---|---|
| Cold start | < 200ms | Process start → first API request |
| Idle memory | 40 MB | With 0 active agents |
| Install size | ~32 MB | Single statically-linked binary |
| Test suite | 1,767+ tests | All passing, 0 warnings |
| LOC | 137,728 | Across 14 crates |
| Agent spawn | ~5ms | New agent creation |
| Message dispatch | ~10ms | RBAC + quota check + routing |
Performance measured on Apple M1 Pro (2021). Your mileage may vary.
Next Steps
Agent Lifecycle
Learn how agents are spawned, execute, and communicate
Memory System
Explore the 6-layer SQLite memory substrate
Security Model
Understand the 16 security systems
Hands System
Deep dive into autonomous capability packages
