Skip to main content

ares/
lib.rs

1//! # A.R.E.S - Agentic Retrieval Enhanced Server
2//!
3//! A production-grade agentic chatbot server built in Rust with multi-provider
4//! LLM support, tool calling, RAG, MCP integration, and advanced research capabilities.
5//!
6//! ## Overview
7//!
8//! A.R.E.S can be used in two ways:
9//!
10//! 1. **As a standalone server** - Run the `ares-server` binary
11//! 2. **As a library** - Import components into your own Rust project
12//!
13//! ## Quick Start (Library Usage)
14//!
15//! Add to your `Cargo.toml`:
16//!
17//! ```toml
18//! [dependencies]
19//! ares-server = "0.5"
20//! ```
21//!
22//! ### Basic Example
23//!
24//! ```rust,ignore
25//! use ares::{Provider, LLMClient};
26//!
27//! #[tokio::main]
28//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
29//!     // Create an Ollama provider
30//!     let provider = Provider::Ollama {
31//!         base_url: "http://localhost:11434".to_string(),
32//!         model: "llama3.2:3b".to_string(),
33//!     };
34//!
35//!     // Create a client and generate a response
36//!     let client = provider.create_client().await?;
37//!     let response = client.generate("Hello, world!").await?;
38//!     println!("{}", response);
39//!
40//!     Ok(())
41//! }
42//! ```
43//!
44//! ### Using Tools
45//!
46//! ```rust,ignore
47//! use ares::{ToolRegistry, tools::calculator::Calculator};
48//! use std::sync::Arc;
49//!
50//! let mut registry = ToolRegistry::new();
51//! registry.register(Arc::new(Calculator));
52//!
53//! // Tools can be used with LLM function calling
54//! let tool_definitions = registry.definitions();
55//! ```
56//!
57//! ### Multi-Turn Tool Calling with ToolCoordinator
58//!
59//! ```rust,ignore
60//! use ares::llm::{Provider, ToolCoordinator, ToolCallingConfig};
61//! use ares::tools::ToolRegistry;
62//! use std::sync::Arc;
63//!
64//! let provider = Provider::from_env()?;
65//! let client = provider.create_client().await?;
66//! let registry = Arc::new(ToolRegistry::new());
67//!
68//! // Create a unified coordinator that works with any LLM provider
69//! let coordinator = ToolCoordinator::new(client, registry, ToolCallingConfig::default());
70//!
71//! // Execute a tool-calling conversation
72//! let result = coordinator.execute(Some("You are a helpful assistant."), "What is 25 * 4?").await?;
73//! println!("Response: {}", result.content);
74//! println!("Tool calls made: {}", result.tool_calls.len());
75//! ```
76//!
77//! ### Configuration-Driven Setup
78//!
79//! ```rust,ignore
80//! use ares::{AresConfigManager, AgentRegistry, ProviderRegistry, ToolRegistry};
81//! use std::sync::Arc;
82//!
83//! // Load configuration from ares.toml
84//! let config_manager = AresConfigManager::new("ares.toml")?;
85//! let config = config_manager.config();
86//!
87//! // Create registries from configuration
88//! let provider_registry = Arc::new(ProviderRegistry::from_config(&config));
89//! let tool_registry = Arc::new(ToolRegistry::with_config(&config));
90//! let agent_registry = AgentRegistry::from_config(
91//!     &config,
92//!     provider_registry,
93//!     tool_registry,
94//! );
95//! ```
96//!
97//! ## Feature Flags
98//!
99//! | Feature | Description |
100//! |---------|-------------|
101//! | `ollama` | Ollama local inference (default) |
102//! | `openai` | OpenAI API support |
103//! | `llamacpp` | Direct GGUF model loading |
104//! | `postgres` | PostgreSQL database (default) |
105//! | `qdrant` | Qdrant vector database |
106//! | `mcp` | Model Context Protocol support |
107//!
108//! ## Modules
109//!
110//! - [`agents`] - Agent framework for multi-agent orchestration
111//! - [`api`] - REST API handlers and routes
112//! - [`auth`] - JWT authentication and middleware
113//! - [`db`] - Database abstraction (PostgreSQL)
114//! - [`llm`] - LLM client implementations
115//! - [`tools`] - Tool definitions and registry
116//! - [`workflows`] - Declarative workflow engine
117//! - [`types`] - Common types and error handling
118//!
119//! ## Architecture
120//!
121//! A.R.E.S uses a hybrid configuration system:
122//!
123//! - **TOML** (`ares.toml`): Infrastructure config (server, auth, providers)
124//! - **TOON** (`config/*.toon`): Behavioral config (agents, models, tools)
125//!
126//! Both support hot-reloading for zero-downtime configuration changes.
127
128#![cfg_attr(docsrs, feature(doc_cfg))]
129#![warn(missing_docs)]
130#![warn(rustdoc::missing_crate_level_docs)]
131
132/// AI agent orchestration and management.
133pub mod agents;
134/// HTTP API handlers and routes.
135#[cfg(feature = "postgres")]
136pub mod api;
137/// JWT authentication and middleware.
138#[cfg(feature = "postgres")]
139pub mod auth;
140/// Command-line interface and scaffolding.
141pub mod cli;
142/// Database clients (Turso/SQLite, Qdrant).
143pub mod db;
144/// LLM provider clients and abstractions.
145pub mod llm;
146/// Model Context Protocol (MCP) server integration.
147#[cfg(feature = "mcp")]
148pub mod mcp;
149/// Conversation memory and context management.
150pub mod memory;
151/// Middleware for API key auth and usage tracking.
152#[cfg(feature = "postgres")]
153pub mod middleware;
154/// Multi-tenant models (Tenant, ApiKey, Quota).
155pub mod models;
156/// Retrieval Augmented Generation (RAG) components.
157pub mod rag;
158/// Multi-agent research coordination.
159#[cfg(feature = "postgres")]
160pub mod research;
161/// SKILL.md file discovery and loading (requires `skills` feature).
162#[cfg(feature = "skills")]
163pub mod skills;
164/// Built-in tools (calculator, web search).
165pub mod tools;
166/// Core types (requests, responses, errors).
167pub mod types;
168/// Configuration utilities (TOML, TOON).
169pub mod utils;
170/// Workflow engine for agent orchestration.
171#[cfg(feature = "postgres")]
172pub mod workflows;
173
174// Re-export commonly used types
175pub use agents::{AgentRegistry, AgentRegistryBuilder};
176#[cfg(feature = "postgres")]
177pub use db::tenants::TenantDb;
178#[cfg(feature = "postgres")]
179pub use db::PostgresClient;
180pub use llm::client::LLMClientFactoryTrait;
181pub use llm::{
182    ConfigBasedLLMFactory, LLMClient, LLMClientFactory, LLMResponse, Provider, ProviderRegistry,
183};
184pub use models::{ApiKey, Tenant, TenantContext, TenantQuota, TenantTier};
185pub use tools::registry::ToolRegistry;
186pub use types::{AppError, ErrorCode, Result};
187pub use utils::toml_config::{AresConfig, AresConfigManager};
188pub use utils::toon_config::DynamicConfigManager;
189#[cfg(feature = "postgres")]
190pub use workflows::{WorkflowEngine, WorkflowOutput, WorkflowStep};
191
192use std::sync::Arc;
193
194/// Application state shared across handlers (requires postgres feature for full server)
195#[cfg(feature = "postgres")]
196use crate::auth::jwt::AuthService;
197
198/// Application state shared across handlers
199#[cfg(feature = "postgres")]
200#[derive(Clone)]
201pub struct AppState {
202    /// TOML-based infrastructure configuration with hot-reload support
203    pub config_manager: Arc<AresConfigManager>,
204    /// TOON-based dynamic behavioral configuration with hot-reload support
205    pub dynamic_config: Arc<DynamicConfigManager>,
206    /// Database client
207    pub db: Arc<dyn crate::db::traits::DatabaseClient>,
208    /// Multi-tenant database
209    pub tenant_db: Arc<TenantDb>,
210    /// LLM client factory (config-based)
211    pub llm_factory: Arc<ConfigBasedLLMFactory>,
212    /// Provider registry for model/provider management
213    pub provider_registry: Arc<ProviderRegistry>,
214    /// Agent registry for creating config-driven agents
215    pub agent_registry: Arc<AgentRegistry>,
216    /// Tool registry for agent tools
217    pub tool_registry: Arc<ToolRegistry>,
218    /// Authentication service
219    pub auth_service: Arc<AuthService>,
220    /// MCP client registry for external services like Eruka
221    #[cfg(feature = "mcp")]
222    pub mcp_registry: Option<Arc<crate::mcp::McpRegistry>>,
223    /// Deploy registry for tracking deployment operations
224    pub deploy_registry: crate::api::handlers::deploy::DeployRegistry,
225    /// Emergency stop flag — when true, all agent requests are rejected with 503.
226    /// Set/cleared via POST /api/admin/agents/emergency-stop.
227    pub emergency_stop: Arc<std::sync::atomic::AtomicBool>,
228    /// External context provider for agent calls.
229    /// OSS: NoOpContextProvider. Managed: ErukaContextProvider (from dirmacs-core).
230    pub context_provider: Arc<dyn crate::agents::context_provider::ContextProvider>,
231}
232
233/// Returns the base ARES router with all generic endpoints.
234///
235/// Extension crates can `.merge()` additional routes and `.layer()` middleware
236/// on top of this to build managed platform binaries.
237///
238/// # Example
239///
240/// ```rust,ignore
241/// use ares::{base_router, AppState};
242///
243/// let app = base_router(state.clone())
244///     .merge(my_custom_routes(state.clone()))
245///     .layer(my_custom_middleware());
246/// ```
247#[cfg(feature = "postgres")]
248pub fn base_router(state: AppState) -> axum::Router {
249    axum::Router::new()
250        .route("/health", axum::routing::get(|| async { "OK" }))
251        .nest(
252            "/api",
253            api::routes::create_router(state.auth_service.clone(), state.tenant_db.clone()),
254        )
255        .with_state(state)
256}