praisonai 0.2.0

Core library for PraisonAI - Agent, Tools, Workflows
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Configuration Loader
//!
//! Loads configuration from multiple sources with precedence:
//! 1. Explicit parameters (highest)
//! 2. Environment variables
//! 3. Config file (.praisonai/config.toml or praisonai.toml)
//! 4. Defaults (lowest)

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

// =============================================================================
// Config Types
// =============================================================================

/// Configuration validation error
#[derive(Debug, Clone, thiserror::Error)]
pub enum ConfigValidationError {
    /// Unknown key in config
    #[error("Unknown key '{key}' in section [{section}]. Did you mean '{suggestion:?}'?")]
    UnknownKey {
        section: String,
        key: String,
        suggestion: Option<String>,
    },
    /// Invalid type
    #[error("Invalid type for [{section}.{key}]: expected {expected}, got {actual}")]
    InvalidType {
        section: String,
        key: String,
        expected: String,
        actual: String,
    },
    /// Multiple errors
    #[error("Config validation failed:\n{}", .0.iter().map(|e| format!("  - {}", e)).collect::<Vec<_>>().join("\n"))]
    Multiple(Vec<ConfigValidationError>),
}

/// Plugins configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PluginsConfig {
    /// Whether plugins are enabled (bool, list of names, or "true"/"false")
    #[serde(default)]
    pub enabled: PluginsEnabled,
    /// Whether to auto-discover plugins
    #[serde(default = "default_true")]
    pub auto_discover: bool,
    /// Plugin directories
    #[serde(default = "default_plugin_dirs")]
    pub directories: Vec<String>,
}

fn default_true() -> bool {
    true
}

fn default_plugin_dirs() -> Vec<String> {
    vec![
        "./.praisonai/plugins/".to_string(),
        "~/.praisonai/plugins/".to_string(),
    ]
}

/// Plugins enabled state
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PluginsEnabled {
    /// Boolean enabled/disabled
    Bool(bool),
    /// List of specific plugin names
    List(Vec<String>),
}

impl Default for PluginsEnabled {
    fn default() -> Self {
        Self::Bool(false)
    }
}

impl PluginsEnabled {
    /// Check if plugins are enabled
    pub fn is_enabled(&self) -> bool {
        match self {
            Self::Bool(b) => *b,
            Self::List(list) => !list.is_empty(),
        }
    }

    /// Get list of enabled plugins (None if all enabled)
    pub fn get_list(&self) -> Option<&[String]> {
        match self {
            Self::Bool(_) => None,
            Self::List(list) => Some(list),
        }
    }
}

/// Defaults configuration for Agent parameters
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DefaultsConfig {
    /// Default LLM model
    pub model: Option<String>,
    /// Default base URL
    pub base_url: Option<String>,
    /// Default API key (not recommended in config)
    pub api_key: Option<String>,
    /// Allow delegation
    #[serde(default)]
    pub allow_delegation: bool,
    /// Allow code execution
    #[serde(default)]
    pub allow_code_execution: bool,
    /// Code execution mode
    #[serde(default = "default_code_execution_mode")]
    pub code_execution_mode: String,
    /// Memory configuration
    pub memory: Option<serde_json::Value>,
    /// Knowledge configuration
    pub knowledge: Option<serde_json::Value>,
    /// Planning configuration
    pub planning: Option<serde_json::Value>,
    /// Reflection configuration
    pub reflection: Option<serde_json::Value>,
    /// Guardrails configuration
    pub guardrails: Option<serde_json::Value>,
    /// Web configuration
    pub web: Option<serde_json::Value>,
    /// Output configuration
    pub output: Option<serde_json::Value>,
    /// Execution configuration
    pub execution: Option<serde_json::Value>,
    /// Caching configuration
    pub caching: Option<serde_json::Value>,
    /// Autonomy configuration
    pub autonomy: Option<serde_json::Value>,
    /// Skills configuration
    pub skills: Option<serde_json::Value>,
    /// Context configuration
    pub context: Option<serde_json::Value>,
    /// Hooks configuration
    pub hooks: Option<serde_json::Value>,
    /// Templates configuration
    pub templates: Option<serde_json::Value>,
}

fn default_code_execution_mode() -> String {
    "safe".to_string()
}

/// Manager configuration for multi-agent workflows
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ManagerConfig {
    /// Manager LLM model
    pub llm: Option<String>,
    /// Maximum iterations
    pub max_iter: Option<usize>,
    /// Verbose output
    #[serde(default)]
    pub verbose: bool,
}

/// Session configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionConfig {
    /// Session ID
    pub session_id: Option<String>,
    /// User ID
    pub user_id: Option<String>,
    /// Persist session
    #[serde(default)]
    pub persist: bool,
    /// Session storage path
    pub storage_path: Option<String>,
}

/// AutoRAG configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AutoRagConfig {
    /// Enable AutoRAG
    #[serde(default)]
    pub enabled: bool,
    /// Chunk size
    pub chunk_size: Option<usize>,
    /// Chunk overlap
    pub chunk_overlap: Option<usize>,
    /// Embedding model
    pub embedding_model: Option<String>,
    /// Vector store backend
    pub vector_store: Option<String>,
}

/// Root configuration for PraisonAI
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PraisonConfig {
    /// Plugins configuration
    #[serde(default)]
    pub plugins: PluginsConfig,
    /// Defaults configuration
    #[serde(default)]
    pub defaults: DefaultsConfig,
}

impl PraisonConfig {
    /// Convert to dictionary
    pub fn to_dict(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or_default()
    }
}

// =============================================================================
// Config Loading Functions
// =============================================================================

/// Global config cache
static CONFIG_CACHE: OnceLock<PraisonConfig> = OnceLock::new();

/// Find config file in standard locations
fn find_config_file() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    
    // Project-local locations
    let local_paths = [
        cwd.join(".praisonai").join("config.toml"),
        cwd.join("praisonai.toml"),
    ];
    
    for path in &local_paths {
        if path.exists() {
            return Some(path.clone());
        }
    }
    
    // User global location
    if let Some(home) = dirs::home_dir() {
        let global_path = home.join(".praisonai").join("config.toml");
        if global_path.exists() {
            return Some(global_path);
        }
    }
    
    None
}

/// Load configuration from file
fn load_config_from_file() -> PraisonConfig {
    let config_path = match find_config_file() {
        Some(path) => path,
        None => return PraisonConfig::default(),
    };
    
    let content = match std::fs::read_to_string(&config_path) {
        Ok(c) => c,
        Err(_) => return PraisonConfig::default(),
    };
    
    // Parse TOML
    match toml::from_str(&content) {
        Ok(config) => config,
        Err(e) => {
            tracing::warn!("Failed to parse config from {:?}: {}", config_path, e);
            PraisonConfig::default()
        }
    }
}

/// Get the global configuration
///
/// Loads config lazily on first access and caches it.
pub fn get_config() -> &'static PraisonConfig {
    CONFIG_CACHE.get_or_init(load_config_from_file)
}

/// Get config path if it exists
pub fn get_config_path() -> Option<PathBuf> {
    find_config_file()
}

/// Get plugins configuration
pub fn get_plugins_config() -> &'static PluginsConfig {
    &get_config().plugins
}

/// Get defaults configuration
pub fn get_defaults_config() -> &'static DefaultsConfig {
    &get_config().defaults
}

/// Get a specific default value
///
/// Supports nested keys like "memory.backend"
pub fn get_default<T: serde::de::DeserializeOwned>(key: &str, fallback: T) -> T {
    let defaults = get_defaults_config();
    let value = serde_json::to_value(defaults).unwrap_or_default();
    
    // Handle nested keys
    let parts: Vec<&str> = key.split('.').collect();
    let mut current = &value;
    
    for part in parts {
        match current.get(part) {
            Some(v) => current = v,
            None => return fallback,
        }
    }
    
    serde_json::from_value(current.clone()).unwrap_or(fallback)
}

/// Check if plugins are enabled via config or env var
pub fn is_plugins_enabled() -> bool {
    // Check env var first (highest precedence)
    if let Ok(env_value) = std::env::var("PRAISONAI_PLUGINS") {
        let lower = env_value.to_lowercase();
        if matches!(lower.as_str(), "true" | "1" | "yes" | "on") {
            return true;
        }
        if matches!(lower.as_str(), "false" | "0" | "no" | "off") {
            return false;
        }
        // Treat as comma-separated list of plugin names
        return true;
    }
    
    // Check config file
    get_plugins_config().enabled.is_enabled()
}

/// Get list of enabled plugins (if specific list provided)
pub fn get_enabled_plugins() -> Option<Vec<String>> {
    // Check env var first
    if let Ok(env_value) = std::env::var("PRAISONAI_PLUGINS") {
        let lower = env_value.to_lowercase();
        if !matches!(lower.as_str(), "true" | "1" | "yes" | "on" | "false" | "0" | "no" | "off") {
            // Treat as comma-separated list
            return Some(
                env_value
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect(),
            );
        }
    }
    
    // Check config file
    get_plugins_config().enabled.get_list().map(|l| l.to_vec())
}

/// Apply config defaults to a parameter if not explicitly set
pub fn apply_config_defaults<T: serde::de::DeserializeOwned + Default>(
    param_name: &str,
    explicit_value: Option<T>,
) -> Option<T> {
    // If user explicitly passed a value, respect it
    if explicit_value.is_some() {
        return explicit_value;
    }
    
    // Check if config has defaults for this param
    let config_value: Option<serde_json::Value> = get_default(param_name, None);
    
    match config_value {
        Some(v) => {
            // Check if enabled
            if let Some(enabled) = v.get("enabled") {
                if enabled.as_bool() == Some(false) {
                    return None;
                }
            }
            serde_json::from_value(v).ok()
        }
        None => None,
    }
}

// =============================================================================
// Config Validation
// =============================================================================

/// Valid root keys
const VALID_ROOT_KEYS: &[&str] = &["plugins", "defaults"];

/// Valid plugins keys
const VALID_PLUGINS_KEYS: &[&str] = &["enabled", "auto_discover", "directories"];

/// Valid defaults keys
const VALID_DEFAULTS_KEYS: &[&str] = &[
    "model",
    "base_url",
    "api_key",
    "allow_delegation",
    "allow_code_execution",
    "code_execution_mode",
    "memory",
    "knowledge",
    "planning",
    "reflection",
    "guardrails",
    "web",
    "output",
    "execution",
    "caching",
    "autonomy",
    "skills",
    "context",
    "hooks",
    "templates",
];

/// Suggest similar key using simple string matching
fn suggest_similar_key(key: &str, valid_keys: &[&str]) -> Option<String> {
    let key_lower = key.to_lowercase();
    
    for valid in valid_keys {
        let valid_lower = valid.to_lowercase();
        // Exact match after lowercasing
        if valid_lower == key_lower {
            return Some(valid.to_string());
        }
        // Prefix match
        if valid_lower.starts_with(&key_lower) || key_lower.starts_with(&valid_lower) {
            return Some(valid.to_string());
        }
        // Substring match
        if valid_lower.contains(&key_lower) || key_lower.contains(&valid_lower) {
            return Some(valid.to_string());
        }
    }
    
    None
}

/// Validate config structure and types
pub fn validate_config(config: &serde_json::Value) -> Result<(), ConfigValidationError> {
    let mut errors = Vec::new();
    
    if let Some(obj) = config.as_object() {
        // Check root keys
        for key in obj.keys() {
            if !VALID_ROOT_KEYS.contains(&key.as_str()) {
                errors.push(ConfigValidationError::UnknownKey {
                    section: "root".to_string(),
                    key: key.clone(),
                    suggestion: suggest_similar_key(key, VALID_ROOT_KEYS),
                });
            }
        }
        
        // Validate [plugins] section
        if let Some(plugins) = obj.get("plugins") {
            if let Some(plugins_obj) = plugins.as_object() {
                for key in plugins_obj.keys() {
                    if !VALID_PLUGINS_KEYS.contains(&key.as_str()) {
                        errors.push(ConfigValidationError::UnknownKey {
                            section: "plugins".to_string(),
                            key: key.clone(),
                            suggestion: suggest_similar_key(key, VALID_PLUGINS_KEYS),
                        });
                    }
                }
            }
        }
        
        // Validate [defaults] section
        if let Some(defaults) = obj.get("defaults") {
            if let Some(defaults_obj) = defaults.as_object() {
                for key in defaults_obj.keys() {
                    if !VALID_DEFAULTS_KEYS.contains(&key.as_str()) {
                        errors.push(ConfigValidationError::UnknownKey {
                            section: "defaults".to_string(),
                            key: key.clone(),
                            suggestion: suggest_similar_key(key, VALID_DEFAULTS_KEYS),
                        });
                    }
                }
            }
        }
    }
    
    if errors.is_empty() {
        Ok(())
    } else if errors.len() == 1 {
        Err(errors.remove(0))
    } else {
        Err(ConfigValidationError::Multiple(errors))
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_plugins_enabled_bool() {
        let enabled = PluginsEnabled::Bool(true);
        assert!(enabled.is_enabled());
        assert!(enabled.get_list().is_none());
        
        let disabled = PluginsEnabled::Bool(false);
        assert!(!disabled.is_enabled());
    }

    #[test]
    fn test_plugins_enabled_list() {
        let enabled = PluginsEnabled::List(vec!["plugin1".to_string(), "plugin2".to_string()]);
        assert!(enabled.is_enabled());
        assert_eq!(enabled.get_list().unwrap().len(), 2);
        
        let empty = PluginsEnabled::List(vec![]);
        assert!(!empty.is_enabled());
    }

    #[test]
    fn test_praison_config_default() {
        let config = PraisonConfig::default();
        assert!(!config.plugins.enabled.is_enabled());
        // auto_discover defaults to false
        assert!(!config.plugins.auto_discover);
    }

    #[test]
    fn test_suggest_similar_key() {
        // Test with exact match (case insensitive)
        let result = suggest_similar_key("model", VALID_DEFAULTS_KEYS);
        assert_eq!(result, Some("model".to_string()));
        
        // Test with prefix match - "mod" should match "model"
        let result2 = suggest_similar_key("mod", VALID_DEFAULTS_KEYS);
        assert_eq!(result2, Some("model".to_string()));
        
        // Test with substring match - "mem" should match "memory"
        let result3 = suggest_similar_key("mem", VALID_DEFAULTS_KEYS);
        assert_eq!(result3, Some("memory".to_string()));
        
        // Test with completely different word - should return None
        let result4 = suggest_similar_key("xyzabc", VALID_DEFAULTS_KEYS);
        assert!(result4.is_none());
    }

    #[test]
    fn test_validate_config_valid() {
        let config = serde_json::json!({
            "plugins": {
                "enabled": true
            },
            "defaults": {
                "model": "gpt-4o"
            }
        });
        
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_config_invalid_key() {
        let config = serde_json::json!({
            "plugins": {
                "enabeld": true  // typo
            }
        });
        
        let result = validate_config(&config);
        assert!(result.is_err());
    }

    #[test]
    fn test_defaults_config() {
        let defaults = DefaultsConfig {
            model: Some("gpt-4o".to_string()),
            allow_delegation: true,
            ..Default::default()
        };
        
        assert_eq!(defaults.model, Some("gpt-4o".to_string()));
        assert!(defaults.allow_delegation);
        assert!(!defaults.allow_code_execution);
    }
}