code_mesh_core/lib.rs
1//! # Code Mesh Core
2//!
3//! **Code Mesh Core** is the foundational library for the Code Mesh AI coding assistant.
4//! It provides a comprehensive set of abstractions and implementations for building
5//! AI-powered development tools.
6//!
7//! ## Features
8//!
9//! - **🤖 Multi-LLM Support**: Unified interface for Anthropic Claude, OpenAI GPT, Google Gemini, and more
10//! - **🛠️ Extensible Tool System**: Built-in tools for file operations, code execution, web search, and custom extensions
11//! - **💾 Session Management**: Persistent conversation history with intelligent context management
12//! - **🔐 Secure Authentication**: OAuth and API key support with encrypted credential storage
13//! - **🌐 Cross-Platform**: Native performance with WebAssembly compatibility
14//! - **🧠 Agent Orchestration**: Multi-agent coordination for complex coding workflows
15//!
16//! ## Quick Start
17//!
18//! ```rust
19//! use code_mesh_core::{Session, LanguageModel, ProviderRegistry, ToolRegistry};
20//! use tokio;
21//!
22//! #[tokio::main]
23//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
24//! // Initialize provider registry
25//! let mut providers = ProviderRegistry::new();
26//! providers.register_anthropic("your-api-key")?;
27//!
28//! // Create a new session
29//! let mut session = Session::new();
30//! session.add_user_message("Help me implement a binary search function");
31//!
32//! // Get a language model
33//! let model = providers.get_model("anthropic/claude-3-opus")?;
34//!
35//! // Generate response
36//! let response = model.complete(&session.build_prompt()).await?;
37//! session.add_assistant_message(response);
38//!
39//! println!("Assistant: {}", session.last_message().content);
40//! Ok(())
41//! }
42//! ```
43//!
44//! ## Architecture Overview
45//!
46//! Code Mesh Core is built around several key abstractions:
47//!
48//! ### Language Models ([`llm`] module)
49//!
50//! The [`LanguageModel`] trait provides a unified interface for interacting with different
51//! AI providers. Implementations are available for major providers:
52//!
53//! - [`AnthropicProvider`] - Claude models via Anthropic API
54//! - [`OpenAIProvider`] - GPT models via OpenAI API
55//! - [`MistralProvider`] - Mistral models via Mistral AI API
56//!
57//! ### Tools ([`tool`] module)
58//!
59//! The [`Tool`] trait enables AI agents to interact with external systems:
60//!
61//! - [`FileTools`] - Read, write, and search files
62//! - [`BashTool`] - Execute shell commands safely
63//! - [`WebTool`] - Search the web and fetch documentation
64//! - [`GitTool`] - Git operations and repository management
65//!
66//! ### Sessions ([`session`] module)
67//!
68//! Sessions manage conversation state and context:
69//!
70//! - [`Session`] - Core conversation management
71//! - [`SessionManager`] - Persistence and retrieval
72//! - [`Message`] - Individual conversation messages
73//!
74//! ### Authentication ([`auth`] module)
75//!
76//! Secure credential management for AI providers:
77//!
78//! - [`Auth`] - Authentication interface
79//! - [`CredentialStore`] - Encrypted credential storage
80//! - [`OAuthFlow`] - OAuth authentication flows
81//!
82//! ## Examples
83//!
84//! ### Multi-Provider Setup
85//!
86//! ```rust
87//! use code_mesh_core::{ProviderRegistry, Provider};
88//!
89//! let mut registry = ProviderRegistry::new();
90//!
91//! // Add multiple providers
92//! registry.register_anthropic("anthropic-key")?;
93//! registry.register_openai("openai-key")?;
94//! registry.register_mistral("mistral-key")?;
95//!
96//! // Use different models for different tasks
97//! let planning_model = registry.get_model("anthropic/claude-3-opus")?;
98//! let coding_model = registry.get_model("openai/gpt-4")?;
99//! let testing_model = registry.get_model("mistral/mistral-large")?;
100//! ```
101//!
102//! ### Tool Integration
103//!
104//! ```rust
105//! use code_mesh_core::{ToolRegistry, FileTools, BashTool};
106//!
107//! let mut tools = ToolRegistry::new();
108//! tools.register(Box::new(FileTools::new()));
109//! tools.register(Box::new(BashTool::new()));
110//!
111//! // Tools can be used by AI agents
112//! let context = ToolContext::new();
113//! let result = tools.execute("read_file", &["src/main.rs"], &context).await?;
114//! ```
115//!
116//! ### Session Persistence
117//!
118//! ```rust
119//! use code_mesh_core::{SessionManager, Storage};
120//!
121//! let storage = Storage::new("./sessions")?;
122//! let mut manager = SessionManager::new(storage);
123//!
124//! // Save session
125//! let session_id = manager.save_session(&session).await?;
126//!
127//! // Load session later
128//! let restored_session = manager.load_session(&session_id).await?;
129//! ```
130//!
131//! ## Feature Flags
132//!
133//! Code Mesh Core supports conditional compilation based on target platform:
134//!
135//! - `native` (default): Full native functionality including file system access
136//! - `wasm`: WebAssembly-compatible subset with browser APIs
137//! - `openai`: OpenAI provider support
138//! - `anthropic`: Anthropic provider support
139//! - `mistral`: Mistral provider support
140//!
141//! ## Error Handling
142//!
143//! All public APIs use the [`Result`] type with [`Error`] for consistent error handling.
144//! Errors are categorized by type and provide detailed context for debugging.
145//!
146//! ## Performance Considerations
147//!
148//! - **Async/Await**: All I/O operations are asynchronous for better performance
149//! - **Connection Pooling**: HTTP clients use connection pooling for efficiency
150//! - **Caching**: Intelligent caching of model responses and file contents
151//! - **Memory Management**: Bounded memory usage with configurable limits
152
153// Core modules
154pub mod agent;
155pub mod auth;
156pub mod llm;
157pub mod memory;
158pub mod planner;
159pub mod session;
160pub mod storage;
161pub mod tool;
162
163// Utility modules
164pub mod config;
165pub mod error;
166pub mod events;
167pub mod features;
168pub mod permission;
169pub mod sync;
170pub mod utils;
171
172// Generated prompts
173pub mod prompts;
174
175// Re-export commonly used types
176pub use llm::{
177 Provider, Model, LanguageModel, ProviderRegistry,
178 Message, MessageRole, MessageContent, GenerateOptions,
179 GenerateResult, StreamChunk, Usage, FinishReason
180};
181pub use tool::{
182 Tool, ToolContext, ToolResult, ToolRegistry, ToolError,
183 ToolDefinition
184};
185pub use auth::{Auth, AuthCredentials, AuthStorage};
186pub use storage::{Storage, StorageError};
187pub use session::{
188 Session, Message as SessionMessage, SessionManager,
189 MessageRole as SessionMessageRole, SessionMetadata
190};
191pub use config::{Config, ConfigManager, ProviderConfig, ToolConfig};
192pub use permission::{PermissionManager, PermissionContext, PermissionLevel};
193
194// Error types
195pub use error::{Error, Result};
196
197// Event system
198pub use events::{Event, EventBus, EventHandler};
199
200// Synchronization primitives
201pub use sync::{AsyncMutex, AsyncRwLock, Debouncer};
202
203// Version and build information
204pub const VERSION: &str = env!("CARGO_PKG_VERSION");
205
206
207/// Runtime compatibility layer
208#[cfg(feature = "native")]
209pub mod runtime {
210 pub use tokio::*;
211 pub type Runtime = tokio::runtime::Runtime;
212 pub type Handle = tokio::runtime::Handle;
213}
214
215#[cfg(feature = "wasm")]
216pub mod runtime {
217 pub use wasm_bindgen_futures::*;
218 // WASM doesn't have a runtime concept like tokio
219 pub type Runtime = ();
220 pub type Handle = ();
221}