mofa-runtime 0.1.1

MoFA Runtime - Message bus, agent registry, and event loop
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! 配置 Schema 定义
//!
//! 定义 Agent 的配置结构

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// 主配置结构
// ============================================================================

/// Agent 配置
///
/// 统一的 Agent 配置结构,支持多种 Agent 类型
///
/// # 示例
///
/// ```rust,ignore
/// use mofa_runtime::agent::config::{AgentConfig, AgentType, LlmAgentConfig};
///
/// let config = AgentConfig {
///     id: "my-agent".to_string(),
///     name: "My LLM Agent".to_string(),
///     description: Some("A helpful assistant".to_string()),
///     agent_type: AgentType::Llm(LlmAgentConfig {
///         model: "gpt-4".to_string(),
///         ..Default::default()
///     }),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent ID (唯一标识符)
    pub id: String,

    /// Agent 名称 (显示名)
    pub name: String,

    /// Agent 描述
    #[serde(default)]
    pub description: Option<String>,

    /// Agent 类型配置
    #[serde(flatten)]
    pub agent_type: AgentType,

    /// 组件配置
    #[serde(default)]
    pub components: ComponentsConfig,

    /// 能力配置
    #[serde(default)]
    pub capabilities: CapabilitiesConfig,

    /// 自定义配置
    #[serde(default)]
    pub custom: HashMap<String, serde_json::Value>,

    /// 环境变量映射
    #[serde(default)]
    pub env_mappings: HashMap<String, String>,

    /// 是否启用
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// 版本号
    #[serde(default)]
    pub version: Option<String>,
}

fn default_enabled() -> bool {
    true
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            id: String::new(),
            name: String::new(),
            description: None,
            agent_type: AgentType::default(),
            components: ComponentsConfig::default(),
            capabilities: CapabilitiesConfig::default(),
            custom: HashMap::new(),
            env_mappings: HashMap::new(),
            enabled: true,
            version: None,
        }
    }
}

impl AgentConfig {
    /// 创建新配置
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            ..Default::default()
        }
    }

    /// 设置描述
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// 设置 Agent 类型
    pub fn with_type(mut self, agent_type: AgentType) -> Self {
        self.agent_type = agent_type;
        self
    }

    /// 添加自定义配置
    pub fn with_custom(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.custom.insert(key.into(), value);
        self
    }

    /// 获取自定义配置
    pub fn get_custom<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
        self.custom
            .get(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// 验证配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.id.is_empty() {
            errors.push("Agent ID cannot be empty".to_string());
        }

        if self.name.is_empty() {
            errors.push("Agent name cannot be empty".to_string());
        }

        // 验证类型特定配置
        if let Err(type_errors) = self.agent_type.validate() {
            errors.extend(type_errors);
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

// ============================================================================
// Agent 类型
// ============================================================================

/// Agent 类型
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentType {
    /// LLM Agent
    Llm(LlmAgentConfig),

    /// ReAct Agent
    #[serde(rename = "react")]
    ReAct(ReActAgentConfig),

    /// 工作流 Agent
    Workflow(WorkflowAgentConfig),

    /// 团队 Agent
    Team(TeamAgentConfig),

    /// 自定义 Agent
    Custom {
        /// 类路径或插件标识
        class_path: String,
        /// 自定义配置
        #[serde(default)]
        config: HashMap<String, serde_json::Value>,
    },
}

impl Default for AgentType {
    fn default() -> Self {
        Self::Llm(LlmAgentConfig::default())
    }
}

impl AgentType {
    /// 获取类型名称
    pub fn type_name(&self) -> &str {
        match self {
            Self::Llm(_) => "llm",
            Self::ReAct(_) => "react",
            Self::Workflow(_) => "workflow",
            Self::Team(_) => "team",
            Self::Custom { .. } => "custom",
        }
    }

    /// 验证类型配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        match self {
            Self::Llm(config) => config.validate(),
            Self::ReAct(config) => config.validate(),
            Self::Workflow(config) => config.validate(),
            Self::Team(config) => config.validate(),
            Self::Custom { class_path, .. } => {
                if class_path.is_empty() {
                    Err(vec!["Custom agent class_path cannot be empty".to_string()])
                } else {
                    Ok(())
                }
            }
        }
    }
}

// ============================================================================
// LLM Agent 配置
// ============================================================================

/// LLM Agent 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmAgentConfig {
    /// 模型名称
    pub model: String,

    /// 系统提示词
    #[serde(default)]
    pub system_prompt: Option<String>,

    /// 温度参数
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// 最大 token 数
    #[serde(default)]
    pub max_tokens: Option<u32>,

    /// Top P 参数
    #[serde(default)]
    pub top_p: Option<f32>,

    /// 停止序列
    #[serde(default)]
    pub stop_sequences: Vec<String>,

    /// 是否启用流式输出
    #[serde(default)]
    pub streaming: bool,

    /// API Key 环境变量名
    #[serde(default)]
    pub api_key_env: Option<String>,

    /// API Base URL
    #[serde(default)]
    pub base_url: Option<String>,

    /// 额外参数
    #[serde(default)]
    pub extra: HashMap<String, serde_json::Value>,
}

fn default_temperature() -> f32 {
    0.7
}

impl Default for LlmAgentConfig {
    fn default() -> Self {
        Self {
            model: "gpt-4".to_string(),
            system_prompt: None,
            temperature: 0.7,
            max_tokens: None,
            top_p: None,
            stop_sequences: Vec::new(),
            streaming: false,
            api_key_env: None,
            base_url: None,
            extra: HashMap::new(),
        }
    }
}

impl LlmAgentConfig {
    /// 验证配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.model.is_empty() {
            errors.push("LLM model cannot be empty".to_string());
        }

        if self.temperature < 0.0 || self.temperature > 2.0 {
            errors.push("Temperature must be between 0.0 and 2.0".to_string());
        }

        if let Some(top_p) = self.top_p
            && (!(0.0..=1.0).contains(&top_p))
        {
            errors.push("Top P must be between 0.0 and 1.0".to_string());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

// ============================================================================
// ReAct Agent 配置
// ============================================================================

/// ReAct Agent 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReActAgentConfig {
    /// LLM 配置
    pub llm: LlmAgentConfig,

    /// 最大推理步数
    #[serde(default = "default_max_steps")]
    pub max_steps: usize,

    /// 工具配置
    #[serde(default)]
    pub tools: Vec<ToolConfig>,

    /// 是否启用并行工具调用
    #[serde(default)]
    pub parallel_tool_calls: bool,

    /// 思考格式
    #[serde(default)]
    pub thought_format: Option<String>,
}

fn default_max_steps() -> usize {
    10
}

impl Default for ReActAgentConfig {
    fn default() -> Self {
        Self {
            llm: LlmAgentConfig::default(),
            max_steps: 10,
            tools: Vec::new(),
            parallel_tool_calls: false,
            thought_format: None,
        }
    }
}

impl ReActAgentConfig {
    /// 验证配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if let Err(llm_errors) = self.llm.validate() {
            errors.extend(llm_errors);
        }

        if self.max_steps == 0 {
            errors.push("ReAct max_steps must be greater than 0".to_string());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// 工具配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolConfig {
    /// 工具名称
    pub name: String,

    /// 工具类型
    #[serde(default)]
    pub tool_type: ToolType,

    /// 工具配置
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,

    /// 是否启用
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

/// 工具类型
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolType {
    /// 内置工具
    #[default]
    Builtin,
    /// MCP 工具
    Mcp,
    /// 自定义工具
    Custom,
    /// 插件工具
    Plugin,
}

// ============================================================================
// Workflow Agent 配置
// ============================================================================

/// Workflow Agent 配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WorkflowAgentConfig {
    /// 工作流步骤
    pub steps: Vec<WorkflowStep>,

    /// 是否启用并行执行
    #[serde(default)]
    pub parallel: bool,

    /// 错误处理策略
    #[serde(default)]
    pub error_strategy: ErrorStrategy,
}

impl WorkflowAgentConfig {
    /// 验证配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.steps.is_empty() {
            errors.push("Workflow steps cannot be empty".to_string());
        }

        for (i, step) in self.steps.iter().enumerate() {
            if step.agent_id.is_empty() {
                errors.push(format!("Workflow step {} agent_id cannot be empty", i));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// 工作流步骤
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowStep {
    /// 步骤 ID
    pub id: String,

    /// Agent ID
    pub agent_id: String,

    /// 输入映射
    #[serde(default)]
    pub input_mapping: HashMap<String, String>,

    /// 输出映射
    #[serde(default)]
    pub output_mapping: HashMap<String, String>,

    /// 条件表达式
    #[serde(default)]
    pub condition: Option<String>,

    /// 超时 (毫秒)
    #[serde(default)]
    pub timeout_ms: Option<u64>,
}

/// 错误处理策略
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorStrategy {
    /// 快速失败
    #[default]
    FailFast,
    /// 继续执行
    Continue,
    /// 重试
    Retry { max_retries: usize, delay_ms: u64 },
    /// 回退
    Fallback { fallback_agent_id: String },
}

// ============================================================================
// Team Agent 配置
// ============================================================================

/// Team Agent 配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TeamAgentConfig {
    /// 团队成员
    pub members: Vec<TeamMember>,

    /// 协调模式
    #[serde(default)]
    pub coordination: CoordinationMode,

    /// 领导者 Agent ID (用于 Hierarchical 模式)
    #[serde(default)]
    pub leader_id: Option<String>,

    /// 任务分发策略
    #[serde(default)]
    pub dispatch_strategy: DispatchStrategy,
}

impl TeamAgentConfig {
    /// 验证配置
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.members.is_empty() {
            errors.push("Team members cannot be empty".to_string());
        }

        if matches!(self.coordination, CoordinationMode::Hierarchical) && self.leader_id.is_none() {
            errors.push("Hierarchical coordination requires leader_id".to_string());
        }

        for member in &self.members {
            if member.agent_id.is_empty() {
                errors.push("Team member agent_id cannot be empty".to_string());
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// 团队成员
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamMember {
    /// Agent ID
    pub agent_id: String,

    /// 角色
    #[serde(default)]
    pub role: Option<String>,

    /// 权重 (用于负载均衡)
    #[serde(default = "default_weight")]
    pub weight: f32,

    /// 是否为可选成员
    #[serde(default)]
    pub optional: bool,
}

fn default_weight() -> f32 {
    1.0
}

/// 协调模式
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CoordinationMode {
    /// 顺序执行
    #[default]
    Sequential,
    /// 并行执行
    Parallel,
    /// 层级执行
    Hierarchical,
    /// 共识模式
    Consensus,
    /// 投票模式
    Voting,
    /// 辩论模式
    Debate,
}

/// 任务分发策略
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DispatchStrategy {
    /// 广播 (所有成员)
    #[default]
    Broadcast,
    /// 轮询
    RoundRobin,
    /// 随机
    Random,
    /// 负载均衡
    LoadBalanced,
    /// 按能力匹配
    CapabilityBased,
}

// ============================================================================
// 组件配置
// ============================================================================

/// 组件配置
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ComponentsConfig {
    /// 推理器配置
    #[serde(default)]
    pub reasoner: Option<ReasonerConfig>,

    /// 记忆配置
    #[serde(default)]
    pub memory: Option<MemoryConfig>,

    /// 协调器配置
    #[serde(default)]
    pub coordinator: Option<CoordinatorConfig>,
}

/// 推理器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasonerConfig {
    /// 推理策略
    #[serde(default)]
    pub strategy: ReasonerStrategy,

    /// 自定义配置
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,
}

/// 推理策略
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasonerStrategy {
    #[default]
    Direct,
    ChainOfThought,
    TreeOfThought,
    ReAct,
    Custom,
}

/// 记忆配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// 记忆类型
    #[serde(default)]
    pub memory_type: MemoryType,

    /// 最大记忆项数
    #[serde(default)]
    pub max_items: Option<usize>,

    /// 向量数据库配置
    #[serde(default)]
    pub vector_db: Option<VectorDbConfig>,
}

/// 记忆类型
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryType {
    #[default]
    InMemory,
    Redis,
    Sqlite,
    VectorDb,
    Custom,
}

/// 向量数据库配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorDbConfig {
    /// 数据库类型
    pub db_type: String,
    /// 连接 URL
    pub url: String,
    /// 集合/索引名称
    #[serde(default)]
    pub collection: Option<String>,
}

/// 协调器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinatorConfig {
    /// 协调模式
    #[serde(default)]
    pub pattern: CoordinationMode,

    /// 超时 (毫秒)
    #[serde(default)]
    pub timeout_ms: Option<u64>,

    /// 自定义配置
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,
}

// ============================================================================
// 能力配置
// ============================================================================

/// 能力配置
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CapabilitiesConfig {
    /// 标签
    #[serde(default)]
    pub tags: Vec<String>,

    /// 支持的输入类型
    #[serde(default)]
    pub input_types: Vec<String>,

    /// 支持的输出类型
    #[serde(default)]
    pub output_types: Vec<String>,

    /// 是否支持流式输出
    #[serde(default)]
    pub supports_streaming: bool,

    /// 是否支持工具调用
    #[serde(default)]
    pub supports_tools: bool,

    /// 是否支持多 Agent 协调
    #[serde(default)]
    pub supports_coordination: bool,

    /// 推理策略
    #[serde(default)]
    pub reasoning_strategies: Vec<String>,
}

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

    #[test]
    fn test_agent_config_validation() {
        let config = AgentConfig::new("test-agent", "Test Agent")
            .with_type(AgentType::Llm(LlmAgentConfig::default()));

        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_empty_config_validation() {
        let config = AgentConfig::default();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_llm_config_serialization() {
        let config = AgentConfig {
            id: "llm-agent".to_string(),
            name: "LLM Agent".to_string(),
            agent_type: AgentType::Llm(LlmAgentConfig {
                model: "gpt-4".to_string(),
                temperature: 0.8,
                ..Default::default()
            }),
            ..Default::default()
        };

        let json = serde_json::to_string_pretty(&config).unwrap();
        assert!(json.contains("gpt-4"));
        assert!(json.contains("0.8"));
    }

    #[test]
    fn test_react_config_serialization() {
        let config = AgentConfig {
            id: "react-agent".to_string(),
            name: "ReAct Agent".to_string(),
            agent_type: AgentType::ReAct(ReActAgentConfig {
                max_steps: 15,
                ..Default::default()
            }),
            ..Default::default()
        };

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("react"));
        assert!(json.contains("15"));
    }

    #[test]
    fn test_team_config_validation() {
        let config = TeamAgentConfig {
            members: vec![TeamMember {
                agent_id: "agent-1".to_string(),
                role: Some("worker".to_string()),
                weight: 1.0,
                optional: false,
            }],
            coordination: CoordinationMode::Hierarchical,
            leader_id: None, // Missing leader
            dispatch_strategy: DispatchStrategy::Broadcast,
        };

        assert!(config.validate().is_err());
    }
}