mofa-kernel 0.1.1

MoFA Kernel - Core runtime and microkernel implementation
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
//! 配置加载器
//!
//! 支持多种配置格式: YAML, TOML, JSON, INI, RON, JSON5
//!
//! 使用统一的 config crate 提供一致的 API 接口

use super::schema::AgentConfig;
use crate::agent::error::{AgentError, AgentResult};
use crate::config::{ConfigError, detect_format, from_str, load_config, load_merged};
use config::FileFormat;
use serde::{Deserialize, Serialize};

/// 配置格式
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConfigFormat {
    /// YAML 格式
    Yaml,
    /// TOML 格式
    Toml,
    /// JSON 格式
    Json,
    /// INI 格式
    Ini,
    /// RON 格式
    Ron,
    /// JSON5 格式
    Json5,
}

impl ConfigFormat {
    /// 从文件扩展名推断格式
    pub fn from_extension(path: &str) -> Option<Self> {
        match detect_format(path) {
            Ok(FileFormat::Yaml) => Some(Self::Yaml),
            Ok(FileFormat::Toml) => Some(Self::Toml),
            Ok(FileFormat::Json) => Some(Self::Json),
            Ok(FileFormat::Ini) => Some(Self::Ini),
            Ok(FileFormat::Ron) => Some(Self::Ron),
            Ok(FileFormat::Json5) => Some(Self::Json5),
            _ => None,
        }
    }

    /// 转换为 config crate 的 FileFormat
    pub fn to_file_format(self) -> FileFormat {
        match self {
            Self::Yaml => FileFormat::Yaml,
            Self::Toml => FileFormat::Toml,
            Self::Json => FileFormat::Json,
            Self::Ini => FileFormat::Ini,
            Self::Ron => FileFormat::Ron,
            Self::Json5 => FileFormat::Json5,
        }
    }

    /// 获取格式名称
    pub fn name(&self) -> &str {
        match self {
            Self::Yaml => "yaml",
            Self::Toml => "toml",
            Self::Json => "json",
            Self::Ini => "ini",
            Self::Ron => "ron",
            Self::Json5 => "json5",
        }
    }

    /// 获取默认文件扩展名
    pub fn default_extension(&self) -> &str {
        match self {
            Self::Yaml => "yml",
            Self::Toml => "toml",
            Self::Json => "json",
            Self::Ini => "ini",
            Self::Ron => "ron",
            Self::Json5 => "json5",
        }
    }
}

/// 配置加载器
///
/// 支持从文件或字符串加载配置,支持多种格式
///
/// # 示例
///
/// ```rust,ignore
/// use mofa_kernel::agent::config::{ConfigLoader, ConfigFormat};
///
/// // 从 YAML 字符串加载
/// let yaml = r#"
/// id: my-agent
/// name: My Agent
/// type: llm
/// llm:
///   model: gpt-4
/// "#;
/// let config = ConfigLoader::from_str(yaml, ConfigFormat::Yaml)?;
///
/// // 从文件加载 (自动检测格式)
/// let config = ConfigLoader::load_file("agent.yaml")?;
///
/// // 从 TOML 字符串加载
/// let toml = r#"
/// id = "my-agent"
/// name = "My Agent"
/// type = "llm"
/// "#;
/// let config = ConfigLoader::from_toml(toml)?;
///
/// // 从 INI 文件加载
/// let config = ConfigLoader::load_ini("agent.ini")?;
/// ```
pub struct ConfigLoader;

impl ConfigLoader {
    /// 从字符串加载配置
    pub fn from_str(content: &str, format: ConfigFormat) -> AgentResult<AgentConfig> {
        from_str(content, format.to_file_format()).map_err(|e| match e {
            ConfigError::Parse(e) => {
                AgentError::ConfigError(format!("Failed to parse config: {}", e))
            }
            ConfigError::Serialization(e) => {
                AgentError::ConfigError(format!("Failed to deserialize config: {}", e))
            }
            ConfigError::UnsupportedFormat(e) => {
                AgentError::ConfigError(format!("Unsupported config format: {}", e))
            }
            _ => AgentError::ConfigError(format!("Config error: {}", e)),
        })
    }

    /// 从 YAML 字符串加载
    pub fn from_yaml(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Yaml)
    }

    /// 从 TOML 字符串加载
    pub fn from_toml(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Toml)
    }

    /// 从 JSON 字符串加载
    pub fn from_json(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Json)
    }

    /// 从 INI 字符串加载
    pub fn from_ini(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Ini)
    }

    /// 从 RON 字符串加载
    pub fn from_ron(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Ron)
    }

    /// 从 JSON5 字符串加载
    pub fn from_json5(content: &str) -> AgentResult<AgentConfig> {
        Self::from_str(content, ConfigFormat::Json5)
    }

    /// 从文件加载配置 (自动检测格式)
    pub fn load_file(path: &str) -> AgentResult<AgentConfig> {
        let config: AgentConfig = load_config(path).map_err(|e| match e {
            ConfigError::Io(e) => {
                AgentError::ConfigError(format!("Failed to read config file '{}': {}", path, e))
            }
            ConfigError::Parse(e) => {
                AgentError::ConfigError(format!("Failed to parse config file '{}': {}", path, e))
            }
            ConfigError::Serialization(e) => AgentError::ConfigError(format!(
                "Failed to deserialize config file '{}': {}",
                path, e
            )),
            ConfigError::UnsupportedFormat(e) => AgentError::ConfigError(format!(
                "Unsupported config format for file '{}': {}",
                path, e
            )),
        })?;

        // 验证配置
        config.validate().map_err(|errors| {
            AgentError::ConfigError(format!("Config validation failed: {}", errors.join(", ")))
        })?;

        Ok(config)
    }

    /// 从文件加载 YAML 配置
    pub fn load_yaml(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 从文件加载 TOML 配置
    pub fn load_toml(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 从文件加载 JSON 配置
    pub fn load_json(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 从文件加载 INI 配置
    pub fn load_ini(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 从文件加载 RON 配置
    pub fn load_ron(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 从文件加载 JSON5 配置
    pub fn load_json5(path: &str) -> AgentResult<AgentConfig> {
        Self::load_file(path)
    }

    /// 将配置序列化为字符串
    pub fn to_string(config: &AgentConfig, format: ConfigFormat) -> AgentResult<String> {
        let content = match format {
            ConfigFormat::Yaml => serde_yaml::to_string(config).map_err(|e| {
                AgentError::ConfigError(format!("Failed to serialize to YAML: {}", e))
            })?,
            ConfigFormat::Toml => toml::to_string_pretty(config).map_err(|e| {
                AgentError::ConfigError(format!("Failed to serialize to TOML: {}", e))
            })?,
            ConfigFormat::Json => serde_json::to_string_pretty(config).map_err(|e| {
                AgentError::ConfigError(format!("Failed to serialize to JSON: {}", e))
            })?,
            ConfigFormat::Ini => {
                return Err(AgentError::ConfigError(
                    "INI serialization not directly supported. Use JSON, YAML, or TOML for saving."
                        .to_string(),
                ));
            }
            ConfigFormat::Ron => {
                return Err(AgentError::ConfigError(
                    "RON serialization not directly supported. Use JSON, YAML, or TOML for saving."
                        .to_string(),
                ));
            }
            ConfigFormat::Json5 => {
                // JSON5 is compatible with JSON for serialization purposes
                serde_json::to_string_pretty(config).map_err(|e| {
                    AgentError::ConfigError(format!("Failed to serialize to JSON5: {}", e))
                })?
            }
        };

        Ok(content)
    }

    /// 将配置保存到文件
    pub fn save_file(config: &AgentConfig, path: &str) -> AgentResult<()> {
        let format = ConfigFormat::from_extension(path).ok_or_else(|| {
            AgentError::ConfigError(format!(
                "Unable to determine config format from file extension: {}",
                path
            ))
        })?;

        let content = Self::to_string(config, format)?;

        std::fs::write(path, content).map_err(|e| {
            AgentError::ConfigError(format!("Failed to write config file '{}': {}", path, e))
        })?;

        Ok(())
    }

    /// 加载多个配置文件
    pub fn load_directory(dir_path: &str) -> AgentResult<Vec<AgentConfig>> {
        let mut configs = Vec::new();

        let entries = std::fs::read_dir(dir_path).map_err(|e| {
            AgentError::ConfigError(format!("Failed to read directory '{}': {}", dir_path, e))
        })?;

        let supported_extensions = ["yaml", "yml", "toml", "json", "ini", "ron", "json5"];

        for entry in entries {
            let entry = entry.map_err(|e| {
                AgentError::ConfigError(format!("Failed to read directory entry: {}", e))
            })?;

            let path = entry.path();
            if path.is_file()
                && let Some(ext) = path.extension().and_then(|e| e.to_str())
            {
                let ext_lower = ext.to_lowercase();
                if supported_extensions.contains(&ext_lower.as_str()) {
                    let path_str = path.to_string_lossy().to_string();
                    match Self::load_file(&path_str) {
                        Ok(config) => configs.push(config),
                        Err(e) => {
                            // 记录错误但继续加载其他文件
                            tracing::warn!("Failed to load config '{}': {}", path_str, e);
                        }
                    }
                }
            }
        }

        Ok(configs)
    }

    /// 合并多个配置 (后面的覆盖前面的)
    pub fn merge(base: AgentConfig, overlay: AgentConfig) -> AgentConfig {
        AgentConfig {
            id: if overlay.id.is_empty() {
                base.id
            } else {
                overlay.id
            },
            name: if overlay.name.is_empty() {
                base.name
            } else {
                overlay.name
            },
            description: overlay.description.or(base.description),
            agent_type: overlay.agent_type,
            components: ComponentsConfig {
                reasoner: overlay.components.reasoner.or(base.components.reasoner),
                memory: overlay.components.memory.or(base.components.memory),
                coordinator: overlay
                    .components
                    .coordinator
                    .or(base.components.coordinator),
            },
            capabilities: if overlay.capabilities.tags.is_empty() {
                base.capabilities
            } else {
                overlay.capabilities
            },
            custom: {
                let mut merged = base.custom;
                merged.extend(overlay.custom);
                merged
            },
            env_mappings: {
                let mut merged = base.env_mappings;
                merged.extend(overlay.env_mappings);
                merged
            },
            enabled: overlay.enabled,
            version: overlay.version.or(base.version),
        }
    }

    /// 从多个文件合并加载配置
    pub fn load_merged_files(paths: &[&str]) -> AgentResult<AgentConfig> {
        load_merged(paths).map_err(|e| match e {
            ConfigError::Io(e) => {
                AgentError::ConfigError(format!("Failed to read config file: {}", e))
            }
            ConfigError::Parse(e) => {
                AgentError::ConfigError(format!("Failed to parse config: {}", e))
            }
            ConfigError::Serialization(e) => {
                AgentError::ConfigError(format!("Failed to deserialize config: {}", e))
            }
            ConfigError::UnsupportedFormat(e) => {
                AgentError::ConfigError(format!("Unsupported config format: {}", e))
            }
        })
    }
}

use super::schema::ComponentsConfig;

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

    #[test]
    fn test_format_from_extension() {
        assert_eq!(
            ConfigFormat::from_extension("config.yaml"),
            Some(ConfigFormat::Yaml)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.yml"),
            Some(ConfigFormat::Yaml)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.toml"),
            Some(ConfigFormat::Toml)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.json"),
            Some(ConfigFormat::Json)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.ini"),
            Some(ConfigFormat::Ini)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.ron"),
            Some(ConfigFormat::Ron)
        );
        assert_eq!(
            ConfigFormat::from_extension("config.json5"),
            Some(ConfigFormat::Json5)
        );
        assert_eq!(ConfigFormat::from_extension("config.txt"), None);
    }

    #[test]
    fn test_format_to_file_format() {
        assert_eq!(ConfigFormat::Yaml.to_file_format(), FileFormat::Yaml);
        assert_eq!(ConfigFormat::Toml.to_file_format(), FileFormat::Toml);
        assert_eq!(ConfigFormat::Json.to_file_format(), FileFormat::Json);
        assert_eq!(ConfigFormat::Ini.to_file_format(), FileFormat::Ini);
        assert_eq!(ConfigFormat::Ron.to_file_format(), FileFormat::Ron);
        assert_eq!(ConfigFormat::Json5.to_file_format(), FileFormat::Json5);
    }

    #[test]
    fn test_load_yaml_string() {
        let yaml = r#"
id: test-agent
name: Test Agent
type: llm
model: gpt-4
temperature: 0.8
"#;

        let config = ConfigLoader::from_yaml(yaml).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_load_json_string() {
        let json = r#"{
            "id": "test-agent",
            "name": "Test Agent",
            "type": "llm",
            "model": "gpt-4"
        }"#;

        let config = ConfigLoader::from_json(json).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_load_toml_string() {
        let toml = r#"
id = "test-agent"
name = "Test Agent"
type = "llm"
model = "gpt-4"
"#;

        let config = ConfigLoader::from_toml(toml).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_load_ini_string() {
        // INI format requires flat key-value pairs at the root level for simple structures
        let ini = r#"
id = "test-agent"
name = "Test Agent"
type = "llm"
model = "gpt-4"
"#;

        let config = ConfigLoader::from_ini(ini).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_load_ron_string() {
        let ron = r#"
(
    id: "test-agent",
    name: "Test Agent",
    type: "llm",
    model: "gpt-4",
)
"#;

        let config = ConfigLoader::from_ron(ron).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_load_json5_string() {
        let json5 = r#"{
    // JSON5 allows comments
    id: "test-agent",
    name: "Test Agent",
    type: "llm",
    model: "gpt-4",
}
"#;

        let config = ConfigLoader::from_json5(json5).unwrap();
        assert_eq!(config.id, "test-agent");
        assert_eq!(config.name, "Test Agent");
    }

    #[test]
    fn test_serialize_config() {
        let config = AgentConfig::new("my-agent", "My Agent");

        let yaml = ConfigLoader::to_string(&config, ConfigFormat::Yaml).unwrap();
        assert!(yaml.contains("my-agent"));

        let json = ConfigLoader::to_string(&config, ConfigFormat::Json).unwrap();
        assert!(json.contains("my-agent"));

        let toml = ConfigLoader::to_string(&config, ConfigFormat::Toml).unwrap();
        assert!(toml.contains("my-agent"));
    }

    #[test]
    fn test_merge_configs() {
        let base =
            AgentConfig::new("base-agent", "Base Agent").with_description("Base description");

        let overlay = AgentConfig {
            id: String::new(), // Empty, should use base
            name: "Override Name".to_string(),
            description: Some("Override description".to_string()),
            ..Default::default()
        };

        let merged = ConfigLoader::merge(base, overlay);
        assert_eq!(merged.id, "base-agent"); // From base
        assert_eq!(merged.name, "Override Name"); // From overlay
        assert_eq!(merged.description, Some("Override description".to_string())); // From overlay
    }

    #[test]
    fn test_format_names() {
        assert_eq!(ConfigFormat::Yaml.name(), "yaml");
        assert_eq!(ConfigFormat::Toml.name(), "toml");
        assert_eq!(ConfigFormat::Json.name(), "json");
        assert_eq!(ConfigFormat::Ini.name(), "ini");
        assert_eq!(ConfigFormat::Ron.name(), "ron");
        assert_eq!(ConfigFormat::Json5.name(), "json5");
    }

    #[test]
    fn test_default_extensions() {
        assert_eq!(ConfigFormat::Yaml.default_extension(), "yml");
        assert_eq!(ConfigFormat::Toml.default_extension(), "toml");
        assert_eq!(ConfigFormat::Json.default_extension(), "json");
        assert_eq!(ConfigFormat::Ini.default_extension(), "ini");
        assert_eq!(ConfigFormat::Ron.default_extension(), "ron");
        assert_eq!(ConfigFormat::Json5.default_extension(), "json5");
    }
}