coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Configuration management for CoderLib
//!
//! This module handles loading and managing configuration for the library,
//! including provider settings, agent configurations, and storage options.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::core::error::{ConfigError, ConfigResult};
use crate::storage::{Storage, SqliteStorage, MemoryStorage};
use crate::lsp::LspConfig;

/// Main configuration for CoderLib
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoderLibConfig {
    /// LLM provider configurations
    pub providers: HashMap<String, ProviderConfig>,
    
    /// Agent configurations
    pub agents: HashMap<String, AgentConfig>,
    
    /// Storage configuration
    pub storage: StorageConfig,
    
    /// Tool configurations
    pub tools: ToolsConfig,

    /// LSP configuration
    pub lsp: LspConfig,

    /// MCP configuration
    pub mcp: crate::mcp::McpConfig,

    /// Debug mode
    pub debug: bool,

    /// Log level
    pub log_level: String,
}

/// Configuration for an LLM provider
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderConfig {
    /// Whether this provider is enabled
    pub enabled: bool,
    
    /// API key for the provider
    pub api_key: Option<String>,
    
    /// Base URL for the API (for custom endpoints)
    pub base_url: Option<String>,
    
    /// Default model to use
    pub default_model: String,
    
    /// Maximum tokens per request
    pub max_tokens: Option<u32>,
    
    /// Request timeout in seconds
    pub timeout: u64,
    
    /// Rate limiting configuration
    pub rate_limit: RateLimitConfig,
    
    /// Provider-specific settings
    pub settings: HashMap<String, serde_json::Value>,
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Requests per minute
    pub requests_per_minute: u32,
    
    /// Tokens per minute
    pub tokens_per_minute: u32,
}

/// Configuration for an agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Provider to use for this agent
    pub provider: String,
    
    /// Model to use
    pub model: String,
    
    /// System prompt
    pub system_prompt: Option<String>,
    
    /// Maximum tokens for responses
    pub max_tokens: u32,
    
    /// Temperature for response generation
    pub temperature: f32,
    
    /// Whether to enable streaming
    pub streaming: bool,
    
    /// Tools available to this agent
    pub tools: Vec<String>,
    
    /// Auto-summarization settings
    pub auto_summarize: AutoSummarizeConfig,
}

/// Auto-summarization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoSummarizeConfig {
    /// Whether auto-summarization is enabled
    pub enabled: bool,
    
    /// Threshold for triggering summarization (number of messages)
    pub message_threshold: u32,
    
    /// Threshold for triggering summarization (number of tokens)
    pub token_threshold: u32,
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Storage type (sqlite, memory, etc.)
    pub storage_type: String,
    
    /// Database file path (for SQLite)
    pub database_path: Option<PathBuf>,
    
    /// Connection pool size
    pub pool_size: u32,
    
    /// Connection timeout in seconds
    pub connection_timeout: u64,
}

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsConfig {
    /// Whether shell commands are enabled
    pub shell_enabled: bool,
    
    /// Whether file operations are enabled
    pub file_operations_enabled: bool,
    
    /// Whether network operations are enabled
    pub network_enabled: bool,
    
    /// Maximum file size for operations (in bytes)
    pub max_file_size: u64,
    
    /// Allowed file extensions for operations
    pub allowed_extensions: Vec<String>,
    
    /// Blocked directories
    pub blocked_directories: Vec<PathBuf>,
}

impl Default for CoderLibConfig {
    fn default() -> Self {
        let mut providers = HashMap::new();
        
        // Default OpenAI configuration
        providers.insert("openai".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: None,
            default_model: "gpt-4".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 60,
                tokens_per_minute: 100000,
            },
            settings: HashMap::new(),
        });
        
        // Default Anthropic configuration
        providers.insert("anthropic".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: None,
            default_model: "claude-3-5-sonnet-20241022".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 60,
                tokens_per_minute: 100000,
            },
            settings: HashMap::new(),
        });

        // Default Groq configuration
        providers.insert("groq".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: Some("https://api.groq.com/openai/v1".to_string()),
            default_model: "llama-3.1-70b-versatile".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 30,
                tokens_per_minute: 50000,
            },
            settings: HashMap::new(),
        });

        // Default Cohere configuration
        providers.insert("cohere".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: Some("https://api.cohere.ai/v1".to_string()),
            default_model: "command-r-plus".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 20,
                tokens_per_minute: 40000,
            },
            settings: HashMap::new(),
        });

        // Default SambaNova configuration
        providers.insert("sambanova".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: Some("https://api.sambanova.ai/v1".to_string()),
            default_model: "Meta-Llama-3.1-70B-Instruct".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 20,
                tokens_per_minute: 40000,
            },
            settings: HashMap::new(),
        });

        // Default Together configuration
        providers.insert("together".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: Some("https://api.together.xyz/v1".to_string()),
            default_model: "meta-llama/Llama-3-70b-chat-hf".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 20,
                tokens_per_minute: 40000,
            },
            settings: HashMap::new(),
        });

        // Default Gemini configuration
        providers.insert("gemini".to_string(), ProviderConfig {
            enabled: false,
            api_key: None,
            base_url: None,
            default_model: "gemini-1.5-pro".to_string(),
            max_tokens: Some(4000),
            timeout: 30,
            rate_limit: RateLimitConfig {
                requests_per_minute: 60,
                tokens_per_minute: 100000,
            },
            settings: HashMap::new(),
        });
        
        let mut agents = HashMap::new();
        agents.insert("coder".to_string(), AgentConfig {
            provider: "openai".to_string(),
            model: "gpt-4".to_string(),
            system_prompt: Some("You are a helpful coding assistant.".to_string()),
            max_tokens: 4000,
            temperature: 0.1,
            streaming: true,
            tools: vec![
                "file_read".to_string(),
                "file_write".to_string(),
                "shell_command".to_string(),
            ],
            auto_summarize: AutoSummarizeConfig {
                enabled: true,
                message_threshold: 20,
                token_threshold: 50000,
            },
        });
        
        Self {
            providers,
            agents,
            storage: StorageConfig {
                storage_type: "sqlite".to_string(),
                database_path: Some(PathBuf::from("coderlib.db")),
                pool_size: 5,
                connection_timeout: 30,
            },
            tools: ToolsConfig {
                shell_enabled: true,
                file_operations_enabled: true,
                network_enabled: false,
                max_file_size: 10 * 1024 * 1024, // 10MB
                allowed_extensions: vec![
                    ".rs".to_string(),
                    ".py".to_string(),
                    ".js".to_string(),
                    ".ts".to_string(),
                    ".go".to_string(),
                    ".java".to_string(),
                    ".cpp".to_string(),
                    ".c".to_string(),
                    ".h".to_string(),
                    ".md".to_string(),
                    ".txt".to_string(),
                    ".json".to_string(),
                    ".toml".to_string(),
                    ".yaml".to_string(),
                    ".yml".to_string(),
                ],
                blocked_directories: vec![
                    PathBuf::from("/etc"),
                    PathBuf::from("/sys"),
                    PathBuf::from("/proc"),
                    PathBuf::from("C:\\Windows"),
                    PathBuf::from("C:\\System32"),
                ],
            },
            lsp: LspConfig::default(),
            mcp: crate::mcp::McpConfig::default(),
            debug: false,
            log_level: "info".to_string(),
        }
    }
}

impl CoderLibConfig {
    /// Load configuration from a TOML file
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| ConfigError::LoadFailed(e.to_string()))?;
        
        let config: Self = toml::from_str(&content)
            .map_err(|e| ConfigError::ParseFailed(e.to_string()))?;
        
        config.validate()?;
        Ok(config)
    }
    
    /// Load configuration from environment variables
    pub fn load_from_env() -> ConfigResult<Self> {
        let mut config = Self::default();
        
        // Load provider API keys from environment
        if let Ok(openai_key) = std::env::var("OPENAI_API_KEY") {
            if let Some(provider) = config.providers.get_mut("openai") {
                provider.api_key = Some(openai_key);
                provider.enabled = true;
            }
        }
        
        if let Ok(anthropic_key) = std::env::var("ANTHROPIC_API_KEY") {
            if let Some(provider) = config.providers.get_mut("anthropic") {
                provider.api_key = Some(anthropic_key);
                provider.enabled = true;
            }
        }
        
        // Load debug setting
        if let Ok(debug) = std::env::var("CODERLIB_DEBUG") {
            config.debug = debug.parse().unwrap_or(false);
        }
        
        // Load log level
        if let Ok(log_level) = std::env::var("CODERLIB_LOG_LEVEL") {
            config.log_level = log_level;
        }
        
        config.validate()?;
        Ok(config)
    }
    
    /// Merge this configuration with another, with the other taking precedence
    pub fn merge_with(mut self, other: Self) -> Self {
        // Merge providers
        for (name, provider) in other.providers {
            self.providers.insert(name, provider);
        }
        
        // Merge agents
        for (name, agent) in other.agents {
            self.agents.insert(name, agent);
        }
        
        // Replace storage config
        self.storage = other.storage;
        
        // Replace tools config
        self.tools = other.tools;

        // Replace MCP config
        self.mcp = other.mcp;

        // Replace other settings
        self.debug = other.debug;
        self.log_level = other.log_level;
        
        self
    }
    
    /// Validate the configuration
    pub fn validate(&self) -> ConfigResult<()> {
        // Check that at least one provider is enabled
        let enabled_providers: Vec<_> = self.providers
            .iter()
            .filter(|(_, config)| config.enabled)
            .collect();
        
        if enabled_providers.is_empty() {
            return Err(ConfigError::InvalidValue(
                "At least one provider must be enabled".to_string()
            ));
        }
        
        // Validate that enabled providers have API keys
        for (name, config) in &enabled_providers {
            if config.api_key.is_none() {
                return Err(ConfigError::MissingRequired(
                    format!("API key for provider '{}'", name)
                ));
            }
        }
        
        // Validate agent configurations
        for (name, agent) in &self.agents {
            if !self.providers.contains_key(&agent.provider) {
                return Err(ConfigError::InvalidValue(
                    format!("Agent '{}' references unknown provider '{}'", name, agent.provider)
                ));
            }
        }
        
        Ok(())
    }
    
    /// Create a storage instance based on the configuration
    pub async fn create_storage(&self) -> ConfigResult<Arc<dyn Storage>> {
        match self.storage.storage_type.as_str() {
            "sqlite" => {
                let db_path = self.storage.database_path
                    .as_ref()
                    .ok_or_else(|| ConfigError::MissingRequired("database_path for SQLite".to_string()))?;

                let storage = SqliteStorage::new(db_path).await
                    .map_err(|e| ConfigError::InvalidValue(format!("Failed to create SQLite storage: {}", e)))?;

                Ok(Arc::new(storage))
            }
            "memory" => {
                let storage = MemoryStorage::new();
                Ok(Arc::new(storage))
            }
            _ => Err(ConfigError::InvalidValue(
                format!("Unknown storage type: {}", self.storage.storage_type)
            )),
        }
    }
    
    /// Get the default agent configuration
    pub fn default_agent(&self) -> ConfigResult<&AgentConfig> {
        self.agents.get("coder")
            .ok_or_else(|| ConfigError::MissingRequired("default agent 'coder'".to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;
    use std::io::Write;

    #[test]
    fn test_default_config() {
        let config = CoderLibConfig::default();
        assert!(!config.providers.is_empty());
        assert!(!config.agents.is_empty());
        assert_eq!(config.storage.storage_type, "sqlite");
    }

    #[test]
    fn test_config_validation() {
        let mut config = CoderLibConfig::default();
        
        // Should fail validation because no providers are enabled
        assert!(config.validate().is_err());
        
        // Enable a provider with API key
        config.providers.get_mut("openai").unwrap().enabled = true;
        config.providers.get_mut("openai").unwrap().api_key = Some("test-key".to_string());
        
        // Should pass validation now
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_file_loading() {
        let config_content = r#"
debug = true
log_level = "debug"

[lsp]
enabled = true
timeout = { secs = 30, nanos = 0 }
max_servers = 10

[providers.openai]
enabled = true
api_key = "test-key"
default_model = "gpt-4"
max_tokens = 4000
timeout = 30

[providers.openai.settings]
base_url = "https://api.openai.com/v1"

[providers.openai.rate_limit]
requests_per_minute = 60
tokens_per_minute = 100000

[agents.coder]
provider = "openai"
model = "gpt-4"
max_tokens = 4000
temperature = 0.1
streaming = true
tools = ["file_read", "file_write"]

[agents.coder.auto_summarize]
enabled = true
message_threshold = 20
token_threshold = 50000

[storage]
storage_type = "sqlite"
database_path = "test.db"
pool_size = 5
connection_timeout = 30

[tools]
shell_enabled = true
file_operations_enabled = true
network_enabled = false
max_file_size = 10485760
allowed_extensions = [".rs", ".py"]
blocked_directories = ["/etc"]
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(config_content.as_bytes()).unwrap();
        
        let config = CoderLibConfig::load_from_file(temp_file.path()).unwrap();
        assert!(config.debug);
        assert_eq!(config.log_level, "debug");
        assert!(config.providers.get("openai").unwrap().enabled);
    }
}