Skip to main content

ai_session/
lib.rs

1//! # AI-Optimized Terminal Session Management Library
2//!
3//! `ai-session` provides an advanced session management system designed specifically
4//! for AI agents and modern development workflows. It offers features beyond traditional
5//! terminal multiplexers like tmux, with a focus on AI context management, multi-agent
6//! coordination, and intelligent output handling.
7//!
8//! ## Key Features
9//!
10//! ### 🧠 AI-Optimized Session Management
11//! - **Token-efficient context handling**: Automatically manages conversation history with intelligent compression
12//! - **Semantic output parsing**: Understands command output types (build results, test outputs, error messages)
13//! - **Context-aware suggestions**: Provides intelligent next-action recommendations
14//!
15#![allow(clippy::new_without_default)]
16#![allow(clippy::field_reassign_with_default)]
17#![allow(clippy::const_is_empty)]
18#![allow(clippy::inherent_to_string_shadow_display)]
19
20//! ### 🤝 Multi-Agent Coordination  
21//! - **Message bus architecture**: Enables seamless communication between AI agents
22//! - **Task delegation**: Intelligent workload distribution across specialized agents
23//! - **Shared context**: Cross-agent knowledge sharing for improved efficiency
24//!
25//! ### 📊 Advanced Observability
26//! - **Decision tracking**: Records AI agent decision-making processes and outcomes
27//! - **Performance profiling**: Monitors resource usage and optimization opportunities
28//! - **Anomaly detection**: Identifies unusual patterns in agent behavior
29//!
30//! ### 🔒 Security & Isolation
31//! - **Capability-based security**: Fine-grained access control for agent actions
32//! - **Namespace isolation**: Secure separation between different agent sessions
33//! - **Rate limiting**: Prevents resource abuse and ensures fair usage
34//!
35//! ### 💾 Session Persistence
36//! - **State snapshots**: Save and restore session state for continuity
37//! - **Command history**: Complete audit trail of all executed commands
38//! - **Compression**: Efficient storage using zstd compression
39//!
40//! ## Quick Start
41//!
42//! ```rust,no_run
43//! use ai_session::*;
44//! use anyhow::Result;
45//!
46//! #[tokio::main]
47//! async fn main() -> Result<()> {
48//!     // Create session manager
49//!     let manager = SessionManager::new();
50//!     
51//!     // Configure session with AI features
52//!     let mut config = SessionConfig::default();
53//!     config.enable_ai_features = true;
54//!     config.context_config.max_tokens = 4096;
55//!     
56//!     // Create and start session
57//!     let session = manager.create_session_with_config(config).await?;
58//!     session.start().await?;
59//!     
60//!     // Execute commands
61//!     session.send_input("echo 'Hello AI Session!'\n").await?;
62//!     let output = session.read_output().await?;
63//!     
64//!     println!("Output: {}", String::from_utf8_lossy(&output));
65//!     
66//!     // Clean up
67//!     session.stop().await?;
68//!     Ok(())
69//! }
70//! ```
71//!
72//! ## Multi-Agent Example
73//!
74//! ```rust,no_run
75//! use ai_session::*;
76//! use ai_session::coordination::{MultiAgentSession, AgentId};
77//! use anyhow::Result;
78//! use std::sync::Arc;
79//!
80//! #[tokio::main]
81//! async fn main() -> Result<()> {
82//!     let coordinator = Arc::new(MultiAgentSession::new());
83//!     let manager = SessionManager::new();
84//!     
85//!     // Create specialized agents
86//!     let mut frontend_config = SessionConfig::default();
87//!     frontend_config.agent_role = Some("frontend".to_string());
88//!     frontend_config.enable_ai_features = true;
89//!     
90//!     let frontend_session = manager.create_session_with_config(frontend_config).await?;
91//!     let frontend_id = AgentId::new();
92//!     
93//!     coordinator.register_agent(frontend_id.clone(), frontend_session)?;
94//!     
95//!     // Agents can now coordinate through the message bus
96//!     println!("Multi-agent system ready!");
97//!     
98//!     Ok(())
99//! }
100//! ```
101//!
102//! ## Architecture Overview
103//!
104//! The library is organized into several key modules:
105//!
106//! - [`core`] - Core session management and lifecycle
107//! - [`context`] - AI context and conversation history management  
108//! - [`coordination`] - Multi-agent communication and task distribution
109//! - [`output`] - Intelligent output parsing and semantic analysis
110//! - security - Access control, isolation, and rate limiting
111//! - observability - Monitoring, decision tracking, and performance analysis
112//! - [`persistence`] - Session state storage and recovery
113//! - integration - Compatibility layers (tmux, VS Code, etc.)
114//!
115//! ## Performance Characteristics
116//!
117//! - **Memory Efficient**: Context compression reduces memory usage by ~70%
118//! - **Context Optimized**: Intelligent history management for efficient session handling
119//! - **Low Latency**: Message passing adds <100ms coordination overhead
120//! - **Scalable**: Supports 100+ concurrent agent sessions
121//!
122//! ## Compatibility
123//!
124//! - **Cross-platform**: Works on Linux, macOS, and Windows
125//! - **tmux Compatible**: Drop-in replacement with migration tools
126//! - **IDE Integration**: VS Code extension support built-in
127//! - **CI/CD Ready**: Designed for automated workflows
128
129pub mod context;
130pub mod coordination;
131pub mod core;
132pub mod execution;
133#[cfg(feature = "mcp")]
134pub mod mcp;
135pub mod output;
136pub mod persistence;
137pub mod session_persistence;
138
139// Re-export main types
140pub use context::{
141    AgentState, Message as ContextMessage, MessageRole, SessionConfig as ContextSessionConfig,
142    SessionContext, TaskContext, WorkspaceState,
143};
144pub use coordination::{
145    AgentId, AgentMessage, BroadcastMessage, Message as CoordinationMessage, MessageBus,
146    MessagePriority, MessageType, MultiAgentSession, ResourceManager, Task, TaskDistributor,
147    TaskId, TaskPriority,
148};
149pub use core::{
150    AISession, AttentionState, ContextConfig, SessionConfig, SessionError, SessionId,
151    SessionResult, SessionStatus, pty::PtyHandle,
152};
153pub use execution::{
154    CommandExecution, DEFAULT_MAX_PROMPT_BYTES, prepare_provider_prompt, run_provider_command,
155};
156pub use output::{OutputManager, OutputParser, ParsedOutput};
157
158// Session manager for easy access
159pub use crate::core::SessionManager;
160
161/// Library version
162pub const VERSION: &str = env!("CARGO_PKG_VERSION");
163
164/// Initialize the logging system
165pub fn init_logging() {
166    use tracing_subscriber::{EnvFilter, fmt, prelude::*};
167
168    tracing_subscriber::registry()
169        .with(fmt::layer())
170        .with(EnvFilter::from_default_env())
171        .init();
172}
173
174// Additional types for examples and bin
175use anyhow::Result;
176use std::path::PathBuf;
177
178/// Session information (for listing sessions)
179#[derive(Debug, Clone, serde::Serialize)]
180pub struct SessionInfo {
181    /// Unique session identifier
182    pub id: SessionId,
183    /// Optional human-readable name
184    pub name: Option<String>,
185    /// Current session status
186    pub status: SessionStatus,
187    /// When the session was created
188    pub created_at: chrono::DateTime<chrono::Utc>,
189    /// Last activity timestamp
190    pub last_activity: chrono::DateTime<chrono::Utc>,
191    /// Working directory for the session
192    pub working_directory: PathBuf,
193    /// Whether AI features are enabled
194    pub ai_features_enabled: bool,
195    /// Token count in context
196    pub context_token_count: usize,
197    /// Number of commands executed
198    pub command_count: usize,
199}
200
201// Extension methods for AISession (for examples)
202impl AISession {
203    /// Get AI context
204    pub async fn get_ai_context(&self) -> Result<SessionContext> {
205        Ok(self.context.read().await.clone())
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn test_version() {
215        assert!(!VERSION.is_empty());
216    }
217}