Skip to main content

ironclad_ai_agent/
lib.rs

1//! # IronClad 🛡️
2//!
3//! **Secure-by-Design Autonomous AI Agent**
4//!
5//! IronClad is a Rust-based autonomous agent that treats the LLM as an untrusted
6//! component ("The Dreamer") and enforces strict policies ("The Governor") on all actions.
7//!
8//! ## Architecture
9//!
10//! The system is built around a "Three-Ring" security architecture:
11//!
12//! 1. **The Dreamer (LLM)**: Generates intentions and commands but has no direct system access
13//! 2. **The Governor**: Validates and gates all LLM outputs through a Traffic Light policy
14//! 3. **The Executor (Sandbox)**: Runs approved commands in isolated environments
15//!
16//! ## Key Features
17//!
18//! - **Multi-Provider LLM Support**: Ollama (local), OpenAI, and Anthropic
19//! - **Sandboxed Execution**: Docker or WSL backends for command isolation
20//! - **Traffic Light Policy**: Commands classified as Green/Yellow/Red/Blocked
21//! - **MCP Integration**: Model Context Protocol for extensible tools
22//! - **Audit Logging**: Complete audit trail in SQLite
23//! - **Telegram Integration**: Remote control via Telegram bot
24//! - **Pulse Scheduler**: Autonomous cron job execution
25//! - **Web Dashboard**: Localhost web interface for observability and management
26//! - **RAG Knowledge Base**: Local codebase indexing for context-aware responses
27//!
28//! ## Quick Start
29//!
30//! ```rust,no_run
31//! use ironclad_ai_agent::config::AppConfig;
32//! use ironclad_ai_agent::audit::AuditLogger;
33//! use ironclad_ai_agent::vault::Vault;
34//! use ironclad_ai_agent::llm;
35//! use std::path::Path;
36//!
37//! #[tokio::main]
38//! async fn main() -> ironclad_ai_agent::error::Result<()> {
39//!     // Load configuration
40//!     let config = AppConfig::load(Path::new("settings.toml"))?;
41//!     
42//!     // Initialize audit logger
43//!     let audit = AuditLogger::new(Path::new("audit.db")).await?;
44//!     
45//!     // Load API keys from environment
46//!     let vault = Vault::load();
47//!     
48//!     // Create LLM provider
49//!     let provider = llm::create_provider(&config, &vault)?;
50//!     
51//!     Ok(())
52//! }
53//! ```
54//!
55//! ## Modules
56//!
57//! - [`audit`]: Audit logging and event tracking
58//! - [`config`]: Configuration management
59//! - [`dashboard`]: Localhost web dashboard for observability
60//! - [`error`]: Error types and Result alias
61//! - [`governor`]: Security policy engine and intent parsing
62//! - [`integrations`]: External integrations (Telegram, Playwright, STT)
63//! - [`llm`]: LLM providers and orchestrator
64//! - [`mcp`]: Model Context Protocol client
65//! - [`memory`]: Chat history persistence
66//! - [`planner`]: Task planning and context management
67//! - [`pulse`]: Job scheduler for autonomous tasks
68//! - [`rag`]: RAG knowledge base for codebase indexing
69//! - [`react`]: Constrained ReAct (Thought-Action-Observation) harness
70//! - [`sandbox`]: Execution backends (Docker, WSL)
71//! - [`security`]: Path validation and workspace boundary enforcement
72//! - [`skills`]: Tool/skill system
73//! - [`subprocess`]: Subprocess orchestration for CLI agent management
74//! - [`tui`]: Terminal user interface
75//! - [`vault`]: API key management and secret scrubbing
76
77pub mod api;
78pub mod audit;
79pub mod bootstrap;
80pub mod collab;
81pub mod config;
82pub mod dashboard;
83pub mod error;
84pub mod governor;
85pub mod integrations;
86pub mod llm;
87pub mod mcp;
88pub mod memory;
89pub mod metrics;
90pub mod planner;
91pub mod plugin;
92pub mod pulse;
93pub mod rag;
94pub mod react;
95pub mod sandbox;
96pub mod security;
97pub mod skills;
98pub mod subprocess;
99pub mod swarm;
100pub mod telemetry;
101pub mod tui;
102pub mod vault;
103
104/// Re-export commonly used types for convenience
105pub mod prelude {
106    pub use crate::config::AppConfig;
107    pub use crate::error::{IronCladError, Result};
108    pub use crate::governor::policy::TrafficLight;
109    pub use crate::governor::{Governor, Intent};
110    pub use crate::llm::ModelProvider;
111    pub use crate::sandbox::SandboxBackend;
112    pub use crate::vault::Vault;
113    pub use crate::{floor_char_boundary, safe_truncate};
114}
115
116/// Return the largest byte index ≤ `index` that falls on a UTF-8 char boundary.
117///
118/// This is equivalent to the nightly `str::floor_char_boundary` method.
119/// Once that method is stabilised, this helper can be removed.
120///
121/// # Examples
122///
123/// ```
124/// use ironclad_ai_agent::floor_char_boundary;
125///
126/// let s = "Hello — world"; // '—' is 3 bytes (U+2014)
127/// let idx = floor_char_boundary(s, 8);  // byte 8 may land inside '—'
128/// assert!(s.is_char_boundary(idx));
129/// assert!(idx <= 8);
130/// ```
131#[inline]
132#[must_use]
133pub fn floor_char_boundary(s: &str, index: usize) -> usize {
134    if index >= s.len() {
135        return s.len();
136    }
137    let mut i = index;
138    while i > 0 && !s.is_char_boundary(i) {
139        i -= 1;
140    }
141    i
142}
143
144/// Truncate a string slice to at most `max_bytes` without splitting a UTF-8 code point.
145///
146/// Returns a slice `&s[..boundary]` where `boundary <= max_bytes` and `s.is_char_boundary(boundary)` is guaranteed.
147///
148/// # Examples
149///
150/// ```
151/// use ironclad_ai_agent::safe_truncate;
152///
153/// let s = "Hello — world"; // '—' is 3 bytes (U+2014)
154/// let truncated = safe_truncate(s, 8);
155/// assert_eq!(truncated, "Hello ");
156/// ```
157#[inline]
158#[must_use]
159pub fn safe_truncate(s: &str, max_bytes: usize) -> &str {
160    let idx = floor_char_boundary(s, max_bytes);
161    &s[..idx]
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn test_floor_char_boundary_ascii() {
170        let s = "abcdef";
171        assert_eq!(floor_char_boundary(s, 0), 0);
172        assert_eq!(floor_char_boundary(s, 3), 3);
173        assert_eq!(floor_char_boundary(s, 6), 6);
174        assert_eq!(floor_char_boundary(s, 10), 6);
175    }
176
177    #[test]
178    fn test_floor_char_boundary_empty() {
179        assert_eq!(floor_char_boundary("", 0), 0);
180        assert_eq!(floor_char_boundary("", 5), 0);
181    }
182
183    #[test]
184    fn test_floor_char_boundary_multibyte() {
185        // 'é' is 2 bytes: [0xC3, 0xA9]
186        let s2 = "café"; // c(1), a(1), f(1), é(2) -> total 5 bytes
187        assert_eq!(floor_char_boundary(s2, 0), 0);
188        assert_eq!(floor_char_boundary(s2, 3), 3);
189        assert_eq!(floor_char_boundary(s2, 4), 3); // inside 'é', falls back to 3
190        assert_eq!(floor_char_boundary(s2, 5), 5);
191
192        // '中' (U+4E2D) is 3 bytes: [0xE4, 0xB8, 0xAD]
193        let s3 = "a中文"; // a(1), 中(3), 文(3) -> total 7 bytes
194        assert_eq!(floor_char_boundary(s3, 1), 1);
195        assert_eq!(floor_char_boundary(s3, 2), 1); // inside 中
196        assert_eq!(floor_char_boundary(s3, 3), 1); // inside 中
197        assert_eq!(floor_char_boundary(s3, 4), 4); // boundary after 中
198        assert_eq!(floor_char_boundary(s3, 5), 4); // inside 文
199        assert_eq!(floor_char_boundary(s3, 7), 7);
200
201        // '🦀' (U+1F980) is 4 bytes: [0xF0, 0x9F, 0xA6, 0x80]
202        let s4 = "Rust🦀!";
203        // R(1)+u(1)+s(1)+t(1) = 4 bytes. 🦀 starts at 4, ends at 8. '!' at 8.
204        assert_eq!(floor_char_boundary(s4, 4), 4);
205        assert_eq!(floor_char_boundary(s4, 5), 4);
206        assert_eq!(floor_char_boundary(s4, 6), 4);
207        assert_eq!(floor_char_boundary(s4, 7), 4);
208        assert_eq!(floor_char_boundary(s4, 8), 8);
209        assert_eq!(floor_char_boundary(s4, 9), 9);
210        assert_eq!(floor_char_boundary(s4, 100), 9);
211    }
212
213    #[test]
214    fn test_safe_truncate_boundary_scenarios() {
215        let s = "Hello 🦀 World 中文";
216        assert_eq!(safe_truncate(s, 0), "");
217        assert_eq!(safe_truncate(s, 5), "Hello");
218        assert_eq!(safe_truncate(s, 6), "Hello ");
219        // 🦀 starts at byte 6, length 4 (bytes 6..10).
220        // Truncating at 7, 8, or 9 must drop 🦀 cleanly to prevent panic.
221        assert_eq!(safe_truncate(s, 7), "Hello ");
222        assert_eq!(safe_truncate(s, 8), "Hello ");
223        assert_eq!(safe_truncate(s, 9), "Hello ");
224        assert_eq!(safe_truncate(s, 10), "Hello 🦀");
225        assert_eq!(safe_truncate(s, 11), "Hello 🦀 ");
226        // Middle of 中 (bytes 17..20)
227        assert_eq!(safe_truncate(s, 18), "Hello 🦀 World ");
228        assert_eq!(safe_truncate(s, 19), "Hello 🦀 World ");
229        assert_eq!(safe_truncate(s, 20), "Hello 🦀 World 中");
230        assert_eq!(safe_truncate(s, 100), s);
231    }
232}