Aleph
API Reference

Rust API

Core crate reference for embedding Aleph as a library

The alephcore crate is the Rust library that powers every Aleph component -- the Gateway daemon, CLI, desktop app, and messaging interfaces. You can also use it directly as a library to embed Aleph's AI agent capabilities in your own Rust applications.

# Cargo.toml
[dependencies]
alephcore = { path = "../Aleph/core" }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

Crate Metadata

FieldValue
Crate namealephcore
Edition2021
Minimum Rust1.92
Crate typesrlib, cdylib
Async runtimeTokio (multi-threaded)

Module Hierarchy

The crate is organized into domain-specific modules. All public modules are re-exported from lib.rs.

alephcore
  ├── agent_loop      # OTAF execution engine
  ├── agents          # Agent definitions, sub-agents, swarm
  ├── approval        # User approval workflows
  ├── browser         # CDP browser automation
  ├── builtin_tools   # Built-in tool implementations
  ├── capability      # Capability detection
  ├── cli             # CLI helpers (inquire prompts)
  ├── command         # Command definitions
  ├── components      # Reusable components
  ├── compressor      # Context compression
  ├── conversation    # Multi-turn conversation management
  ├── daemon          # Proactive AI daemon (worldmodel, perception)
  ├── desktop         # Desktop integration
  ├── discovery       # Service discovery
  ├── dispatcher      # Unified tool registry & dispatch
  ├── domain          # Domain modeling types
  ├── engine          # Engine coordination
  ├── event           # Event types
  ├── exec            # Command execution & security kernel
  ├── executor        # Task executors
  ├── extension       # Plugin/extension system
  ├── gateway*        # WebSocket JSON-RPC server (feature-gated)
  ├── generation      # Content generation providers
  ├── intent          # Intent routing
  ├── logging         # Structured logging with PII scrubbing
  ├── markdown        # Markdown processing
  ├── mcp             # Model Context Protocol integration
  ├── memory          # Memory storage & retrieval
  ├── metrics         # Performance telemetry
  ├── payload         # Request/response payloads
  ├── permission      # Permission management
  ├── pii             # PII detection & scrubbing
  ├── poe             # Principle-Operation-Evaluation tasks
  ├── prompt          # Prompt construction
  ├── providers       # AI provider abstraction
  ├── resilient       # Resilient task execution
  ├── routing         # Session key routing
  ├── runtimes        # Capability probe/ledger (detect & bootstrap external tools)
  ├── scheduler       # Task scheduling
  ├── search          # Search providers
  ├── secrets         # Secret management
  ├── skill           # Individual skill types
  ├── skills          # Skills registry & management
  ├── skill_evolution # Skill solidification & evolution
  ├── spec_driven     # Spec-driven development workflow
  ├── supervisor      # PTY process supervision
  ├── thinker         # LLM decision-making layer
  ├── tools           # Tool trait system
  ├── video           # Video transcript extraction
  ├── vision          # Vision/image processing
  └── wizard          # Configuration wizard flows

Modules marked with * are feature-gated. See Feature Flags below.

Key Public Types

Configuration

TypeModuleDescription
ConfigconfigMain configuration struct (parsed from config.toml)
FullConfigconfigComplete configuration including all sections
ProviderConfigconfigPer-provider settings (model, API key, base URL)
MemoryConfigconfigMemory system settings
BehaviorConfigconfigAgent behavior tuning
RoutingRuleConfigconfigIntent routing rules
GeneralConfigconfigGeneral application settings

Agent Loop

TypeModuleDescription
AgentLoopagent_loopCore OTAF execution engine
AgentLoopBuilderagent_loop::builderBuilder pattern for AgentLoop construction
LoopConfigagent_loop::configLoop execution parameters (max iterations, timeouts)
LoopResultagent_loopFinal result of an agent loop run
LoopStateagent_loop::stateMutable state carried across iterations
RequestContextagent_loop::statePer-request metadata (session, identity, attachments)
Messageagent_loop::message_builderChat message with role and content
ToolCallagent_loop::message_builderTool invocation record
Decisionagent_loop::decisionParsed LLM decision (respond, call tool, delegate, stop)

Thinker (LLM Layer)

TypeModuleDescription
Thinker<P>thinkerGeneric LLM decision engine parameterized over ProviderRegistry
ThinkerConfigthinkerPrompt, filter, routing, and compression settings
ProviderRegistrythinkerTrait for provider lookup and selection
SingleProviderRegistrythinkerSimple registry wrapping a single AiProvider
PromptBuilderthinker::prompt_builderBuilds system + user prompts from context
ThinkerModelSelectorthinker::model_routerRoutes requests to models based on rules

Tool System

TypeModuleDescription
AlephTooltoolsStatic dispatch trait -- compile-time typed tools
AlephToolDyntoolsDynamic dispatch trait -- runtime-loaded tools (MCP, plugins)
AlephToolServertoolsHot-reload enabled tool server
AlephToolServerHandletoolsThread-safe handle to a running tool server
ToolRegistrydispatcherUnified registry aggregating all tool sources
ToolDefinitiondispatcherTool metadata (name, description, JSON Schema, category)
UnifiedTooldispatcherWrapper unifying native, MCP, skill, and plugin tools
ToolResultdispatcherExecution result from any tool

Providers

TypeModuleDescription
AiProviderprovidersCore trait for AI backends (process, process_with_tools, stream)
HttpProviderproviders::http_providerProtocol-agnostic HTTP provider
OllamaProviderproviders::ollamaNative Ollama integration
FailoverProviderproviders::failoverAutomatic provider failover
AuthProfileManagerproviders::profile_managerMulti-profile credential rotation

Error Handling

TypeModuleDescription
AlephErrorerrorUnified error enum with 20+ variants
Result<T>errorType alias for std::result::Result<T, AlephError>

Every AlephError variant carries an optional suggestion field with user-friendly remediation advice. Call .suggestion() to retrieve it, or .user_friendly_message() for a formatted display string.

Core Traits

AlephTool -- Static Tool Trait

#[async_trait]
pub trait AlephTool: Clone + Send + Sync + 'static {
    const NAME: &'static str;
    const DESCRIPTION: &'static str;

    type Args: Serialize + DeserializeOwned + JsonSchema + Send;
    type Output: Serialize + Send;

    async fn call(&self, args: Self::Args) -> Result<Self::Output>;

    // Provided methods
    fn category(&self) -> ToolCategory { ToolCategory::Builtin }
    fn requires_confirmation(&self) -> bool { false }
    fn examples(&self) -> Option<Vec<String>> { None }
    fn definition(&self) -> ToolDefinition { /* auto-generates JSON Schema */ }
}

A blanket implementation converts any AlephTool into AlephToolDyn, so static tools can be stored in dynamic collections:

let tools: Vec<Box<dyn AlephToolDyn>> = vec![
    Box::new(SearchTool::new()),
    Box::new(WebFetchTool::new()),
];

AiProvider -- LLM Backend Trait

pub trait AiProvider: Send + Sync {
    fn process(&self, input: &str, system_prompt: Option<&str>)
        -> Pin<Box<dyn Future<Output = Result<String>> + Send + '_>>;

    fn process_with_tools(&self, messages: Vec<Message>, tools: Vec<ToolDefinition>, ...)
        -> Pin<Box<dyn Future<Output = Result<LlmResponse>> + Send + '_>>;

    fn name(&self) -> &str;
    fn color(&self) -> &str;
    fn model_id(&self) -> &str;
}

Aleph ships adapters for OpenAI-compatible, Anthropic, Gemini, and Ollama protocols. Add new providers by implementing this trait or by registering a YAML-defined protocol adapter.

LoopCallback -- Agent Loop Events

pub trait LoopCallback: Send + Sync {
    fn on_event(&self, event: LoopEvent);
}

Implement this trait to receive real-time events during agent execution: iteration start/end, tool calls, thinking steps, errors, and final results. Built-in implementations include LoggingCallback, CollectingCallback, and NoOpLoopCallback.

Feature Flags

FeatureDescriptionDependencies
gateway (default)WebSocket JSON-RPC servertokio-tungstenite, axum, clap
telegramTelegram bot interfaceteloxide
discordDiscord bot interfaceserenity
whatsappWhatsApp interface(gateway)
all-channelsAll messaging channelstelegram + discord + whatsapp
cronCron job schedulercron, chrono-tz
cliInteractive CLI promptsinquire
control-planeEmbedded web UIrust-embed
plugin-wasmWebAssembly plugin runtimeextism
plugin-nodejsNode.js plugin runtime(placeholder)
plugin-allAll plugin runtimesplugin-wasm + plugin-nodejs
test-helpersTest utilities--

Use feature combinations to control binary size:

# Minimal library usage (no server, no channels)
alephcore = { path = "...", default-features = false }

# Gateway + Telegram only
alephcore = { path = "...", features = ["gateway", "telegram"] }

# Everything
alephcore = { path = "...", features = ["gateway", "all-channels", "cron", "plugin-all"] }

Usage Example

Running an Agent Loop

use alephcore::{
    AgentLoop, AgentLoopConfig, RequestContext,
    Thinker, ThinkerConfig, SingleProviderRegistry,
    ContextCompressor,
};
use alephcore::agent_loop::NoOpLoopCallback;
use alephcore::providers::{create_provider, ProviderConfig};
use std::sync::Arc;

#[tokio::main]
async fn main() -> alephcore::Result<()> {
    // 1. Initialize logging
    alephcore::init_logging();

    // 2. Create an AI provider
    let config = ProviderConfig::test_config("claude-sonnet-4-20250514");
    let provider = create_provider("anthropic", config)?;

    // 3. Build the Thinker (LLM layer)
    let registry = SingleProviderRegistry::new(provider);
    let thinker = Thinker::new(
        Arc::new(registry),
        ThinkerConfig::default(),
    );

    // 4. Create the Agent Loop
    let loop_config = AgentLoopConfig::default();
    let compressor = ContextCompressor;
    let agent = AgentLoop::new(thinker, compressor, loop_config);

    // 5. Run
    let result = agent.run(
        "What is the weather in Tokyo?".to_string(),
        RequestContext::empty(),
        vec![], // tools
        NoOpLoopCallback,
    ).await;

    println!("Result: {:?}", result);
    Ok(())
}

Implementing a Custom Tool

use alephcore::tools::AlephTool;
use alephcore::error::Result;
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
struct WeatherTool;

#[derive(Serialize, Deserialize, JsonSchema)]
struct WeatherArgs {
    /// City name to check weather for
    city: String,
    /// Temperature unit (celsius or fahrenheit)
    unit: Option<String>,
}

#[derive(Serialize)]
struct WeatherOutput {
    temperature: f64,
    condition: String,
    city: String,
}

#[async_trait]
impl AlephTool for WeatherTool {
    const NAME: &'static str = "weather";
    const DESCRIPTION: &'static str = "Get current weather for a city";

    type Args = WeatherArgs;
    type Output = WeatherOutput;

    async fn call(&self, args: Self::Args) -> Result<Self::Output> {
        // Your implementation here
        Ok(WeatherOutput {
            temperature: 22.0,
            condition: "Sunny".into(),
            city: args.city,
        })
    }

    fn examples(&self) -> Option<Vec<String>> {
        Some(vec![
            "weather(city='Tokyo')".into(),
            "weather(city='London', unit='celsius')".into(),
        ])
    }
}

Error Handling

AlephError is a thiserror-based enum. Every variant includes structured context:

match result {
    Err(AlephError::AuthenticationError { provider, message, suggestion }) => {
        eprintln!("Auth failed for {}: {}", provider, message);
        if let Some(hint) = suggestion {
            eprintln!("Hint: {}", hint);
        }
    }
    Err(AlephError::RateLimitError { .. }) => {
        tokio::time::sleep(Duration::from_secs(60)).await;
        // retry...
    }
    Err(e) => eprintln!("{}", e.user_friendly_message()),
    Ok(val) => { /* success */ }
}

Key error variants: NetworkError, AuthenticationError, RateLimitError, ProviderError, Timeout, NoProviderAvailable, InvalidConfig, ConfigError, ToolNotFound, Cancelled, RuntimeError, ExecutionTimeout, SandboxUnavailable.

Async Runtime

Aleph uses Tokio with the rt-multi-thread feature. All public async APIs return Send futures compatible with Tokio's multi-threaded runtime. Key Tokio features used:

  • rt-multi-thread -- Work-stealing thread pool
  • sync -- Channels, mutexes, RwLocks, semaphores
  • time -- Timeouts, intervals, sleep
  • process -- Child process management
  • fs -- Async filesystem operations
  • signal -- Unix signal handling
  • net -- TCP/UDP networking

See Also

On this page