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
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
//! Agent 核心类型定义
//!
//! 定义统一的 Agent 输入、输出和状态类型

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

// 导出统一类型模块
pub mod error;
pub mod event;
pub mod global;

pub use error::{ErrorCategory, ErrorContext, GlobalError, GlobalResult};
pub use event::{EventBuilder, GlobalEvent};
pub use event::{execution, lifecycle, message, plugin, state};
// 重新导出常用类型
pub use global::{GlobalMessage, MessageContent, MessageMetadata};

// ============================================================================
// Agent 状态
// ============================================================================

/// Agent 状态机
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum AgentState {
    /// 已创建,未初始化
    #[default]
    Created,
    /// 正在初始化
    Initializing,
    /// 就绪,可执行
    Ready,
    /// 运行中
    Running,
    /// 正在执行
    Executing,
    /// 已暂停
    Paused,
    /// 已中断
    Interrupted,
    /// 正在关闭
    ShuttingDown,
    /// 已终止/关闭
    Shutdown,
    /// 失败状态
    Failed,
    /// 销毁
    Destroyed,
    /// 错误状态 (带消息)
    Error(String),
}

impl fmt::Display for AgentState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AgentState::Created => write!(f, "Created"),
            AgentState::Initializing => write!(f, "Initializing"),
            AgentState::Ready => write!(f, "Ready"),
            AgentState::Executing => write!(f, "Executing"),
            AgentState::Paused => write!(f, "Paused"),
            AgentState::Interrupted => write!(f, "Interrupted"),
            AgentState::ShuttingDown => write!(f, "ShuttingDown"),
            AgentState::Shutdown => write!(f, "Shutdown"),
            AgentState::Failed => write!(f, "Failed"),
            AgentState::Error(msg) => write!(f, "Error({})", msg),
            AgentState::Running => {
                write!(f, "Running")
            }
            AgentState::Destroyed => {
                write!(f, "Destroyed")
            }
        }
    }
}

impl AgentState {
    /// 转换到目标状态
    pub fn transition_to(
        &self,
        target: AgentState,
    ) -> Result<AgentState, super::error::AgentError> {
        if self.can_transition_to(&target) {
            Ok(target)
        } else {
            Err(super::error::AgentError::invalid_state_transition(
                self, &target,
            ))
        }
    }

    /// 检查是否可以转换到目标状态
    pub fn can_transition_to(&self, target: &AgentState) -> bool {
        use AgentState::*;
        matches!(
            (self, target),
            (Created, Initializing)
                | (Initializing, Ready)
                | (Initializing, Error(_))
                | (Initializing, Failed)
                | (Ready, Executing)
                | (Ready, ShuttingDown)
                | (Executing, Ready)
                | (Executing, Paused)
                | (Executing, Interrupted)
                | (Executing, Error(_))
                | (Executing, Failed)
                | (Paused, Ready)
                | (Paused, Executing)
                | (Paused, ShuttingDown)
                | (Interrupted, Ready)
                | (Interrupted, ShuttingDown)
                | (ShuttingDown, Shutdown)
                | (Error(_), ShuttingDown)
                | (Error(_), Shutdown)
                | (Failed, ShuttingDown)
                | (Failed, Shutdown)
        )
    }

    /// 是否为活动状态
    pub fn is_active(&self) -> bool {
        matches!(self, AgentState::Ready | AgentState::Executing)
    }

    /// 是否为终止状态
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            AgentState::Shutdown | AgentState::Failed | AgentState::Error(_)
        )
    }
}

// ============================================================================
// Agent 输入
// ============================================================================

/// Agent 输入类型
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum AgentInput {
    /// 文本输入
    Text(String),
    /// 多行文本
    Texts(Vec<String>),
    /// 结构化 JSON
    Json(serde_json::Value),
    /// 键值对
    Map(HashMap<String, serde_json::Value>),
    /// 二进制数据
    Binary(Vec<u8>),
    /// 空输入
    #[default]
    Empty,
}

impl AgentInput {
    /// 创建文本输入
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text(s.into())
    }

    /// 创建 JSON 输入
    pub fn json(value: serde_json::Value) -> Self {
        Self::Json(value)
    }

    /// 创建键值对输入
    pub fn map(map: HashMap<String, serde_json::Value>) -> Self {
        Self::Map(map)
    }

    /// 获取文本内容
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(s) => Some(s),
            _ => None,
        }
    }

    /// 转换为文本
    pub fn to_text(&self) -> String {
        match self {
            Self::Text(s) => s.clone(),
            Self::Texts(v) => v.join("\n"),
            Self::Json(v) => v.to_string(),
            Self::Map(m) => serde_json::to_string(m).unwrap_or_default(),
            Self::Binary(b) => String::from_utf8_lossy(b).to_string(),
            Self::Empty => String::new(),
        }
    }

    /// 获取 JSON 内容
    pub fn as_json(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Json(v) => Some(v),
            _ => None,
        }
    }

    /// 转换为 JSON
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Self::Text(s) => serde_json::Value::String(s.clone()),
            Self::Texts(v) => serde_json::json!(v),
            Self::Json(v) => v.clone(),
            Self::Map(m) => serde_json::to_value(m).unwrap_or_default(),
            Self::Binary(b) => serde_json::json!({ "binary": base64_encode(b) }),
            Self::Empty => serde_json::Value::Null,
        }
    }

    /// 是否为空
    pub fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }
}

impl From<String> for AgentInput {
    fn from(s: String) -> Self {
        Self::Text(s)
    }
}

impl From<&str> for AgentInput {
    fn from(s: &str) -> Self {
        Self::Text(s.to_string())
    }
}

impl From<serde_json::Value> for AgentInput {
    fn from(v: serde_json::Value) -> Self {
        Self::Json(v)
    }
}

// ============================================================================
// Agent 输出
// ============================================================================

/// Agent 输出类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentOutput {
    /// 主输出内容
    pub content: OutputContent,
    /// 输出元数据
    pub metadata: HashMap<String, serde_json::Value>,
    /// 使用的工具
    pub tools_used: Vec<ToolUsage>,
    /// 推理步骤 (如果有)
    pub reasoning_steps: Vec<ReasoningStep>,
    /// 执行时间 (毫秒)
    pub duration_ms: u64,
    /// Token 使用统计
    pub token_usage: Option<TokenUsage>,
}

impl Default for AgentOutput {
    fn default() -> Self {
        Self {
            content: OutputContent::Empty,
            metadata: HashMap::new(),
            tools_used: Vec::new(),
            reasoning_steps: Vec::new(),
            duration_ms: 0,
            token_usage: None,
        }
    }
}

impl AgentOutput {
    /// 创建文本输出
    pub fn text(s: impl Into<String>) -> Self {
        Self {
            content: OutputContent::Text(s.into()),
            ..Default::default()
        }
    }

    /// 创建 JSON 输出
    pub fn json(value: serde_json::Value) -> Self {
        Self {
            content: OutputContent::Json(value),
            ..Default::default()
        }
    }

    /// 创建错误输出
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            content: OutputContent::Error(message.into()),
            ..Default::default()
        }
    }

    /// 获取文本内容
    pub fn as_text(&self) -> Option<&str> {
        match &self.content {
            OutputContent::Text(s) => Some(s),
            _ => None,
        }
    }

    /// 转换为文本
    pub fn to_text(&self) -> String {
        self.content.to_text()
    }

    /// 设置执行时间
    pub fn with_duration(mut self, duration_ms: u64) -> Self {
        self.duration_ms = duration_ms;
        self
    }

    /// 添加元数据
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// 添加工具使用记录
    pub fn with_tool_usage(mut self, usage: ToolUsage) -> Self {
        self.tools_used.push(usage);
        self
    }

    /// 设置所有工具使用记录
    pub fn with_tools_used(mut self, usages: Vec<ToolUsage>) -> Self {
        self.tools_used = usages;
        self
    }

    /// 添加推理步骤
    pub fn with_reasoning_step(mut self, step: ReasoningStep) -> Self {
        self.reasoning_steps.push(step);
        self
    }

    /// 设置所有推理步骤
    pub fn with_reasoning_steps(mut self, steps: Vec<ReasoningStep>) -> Self {
        self.reasoning_steps = steps;
        self
    }

    /// 设置 Token 使用
    pub fn with_token_usage(mut self, usage: TokenUsage) -> Self {
        self.token_usage = Some(usage);
        self
    }

    /// 是否为错误
    pub fn is_error(&self) -> bool {
        matches!(self.content, OutputContent::Error(_))
    }
}

/// 输出内容类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OutputContent {
    /// 文本输出
    Text(String),
    /// 多行文本
    Texts(Vec<String>),
    /// JSON 输出
    Json(serde_json::Value),
    /// 二进制输出
    Binary(Vec<u8>),
    /// 流式输出标记
    Stream,
    /// 错误输出
    Error(String),
    /// 空输出
    Empty,
}

impl OutputContent {
    /// 转换为文本
    pub fn to_text(&self) -> String {
        match self {
            Self::Text(s) => s.clone(),
            Self::Texts(v) => v.join("\n"),
            Self::Json(v) => v.to_string(),
            Self::Binary(b) => String::from_utf8_lossy(b).to_string(),
            Self::Stream => "[STREAM]".to_string(),
            Self::Error(e) => format!("Error: {}", e),
            Self::Empty => String::new(),
        }
    }
}

// ============================================================================
// 辅助类型
// ============================================================================

/// 工具使用记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUsage {
    /// 工具名称
    pub name: String,
    /// 工具输入
    pub input: serde_json::Value,
    /// 工具输出
    pub output: Option<serde_json::Value>,
    /// 是否成功
    pub success: bool,
    /// 错误信息
    pub error: Option<String>,
    /// 执行时间 (毫秒)
    pub duration_ms: u64,
}

impl ToolUsage {
    /// 创建成功的工具使用记录
    pub fn success(
        name: impl Into<String>,
        input: serde_json::Value,
        output: serde_json::Value,
        duration_ms: u64,
    ) -> Self {
        Self {
            name: name.into(),
            input,
            output: Some(output),
            success: true,
            error: None,
            duration_ms,
        }
    }

    /// 创建失败的工具使用记录
    pub fn failure(
        name: impl Into<String>,
        input: serde_json::Value,
        error: impl Into<String>,
        duration_ms: u64,
    ) -> Self {
        Self {
            name: name.into(),
            input,
            output: None,
            success: false,
            error: Some(error.into()),
            duration_ms,
        }
    }
}

/// 推理步骤
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningStep {
    /// 步骤类型
    pub step_type: ReasoningStepType,
    /// 步骤内容
    pub content: String,
    /// 步骤序号
    pub step_number: usize,
    /// 时间戳
    pub timestamp_ms: u64,
}

impl ReasoningStep {
    /// 创建新的推理步骤
    pub fn new(
        step_type: ReasoningStepType,
        content: impl Into<String>,
        step_number: usize,
    ) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;

        Self {
            step_type,
            content: content.into(),
            step_number,
            timestamp_ms: now,
        }
    }
}

/// 推理步骤类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReasoningStepType {
    /// 思考
    Thought,
    /// 行动
    Action,
    /// 观察
    Observation,
    /// 反思
    Reflection,
    /// 决策
    Decision,
    /// 最终答案
    FinalAnswer,
    /// 自定义
    Custom(String),
}

/// Token 使用统计
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TokenUsage {
    /// 提示词 tokens
    pub prompt_tokens: u32,
    /// 完成 tokens
    pub completion_tokens: u32,
    /// 总 tokens
    pub total_tokens: u32,
}

impl TokenUsage {
    pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self {
        let total_tokens = prompt_tokens + completion_tokens;
        Self {
            prompt_tokens,
            completion_tokens,
            total_tokens,
        }
    }
}

// ============================================================================
// LLM 相关类型
// ============================================================================

/// LLM 聊天完成请求
#[derive(Debug, Clone)]
pub struct ChatCompletionRequest {
    /// Messages for the chat completion
    pub messages: Vec<ChatMessage>,
    /// Model to use
    pub model: Option<String>,
    /// Tool definitions (if tools are available)
    pub tools: Option<Vec<ToolDefinition>>,
    /// Temperature
    pub temperature: Option<f32>,
    /// Max tokens
    pub max_tokens: Option<u32>,
}

/// 聊天消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    /// Role: system, user, assistant, tool
    pub role: String,
    /// Content (text or structured)
    pub content: Option<String>,
    /// Tool call ID (for tool responses)
    pub tool_call_id: Option<String>,
    /// Tool calls (for assistant messages with tools)
    pub tool_calls: Option<Vec<ToolCall>>,
}

/// LLM 工具调用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Tool call ID
    pub id: String,
    /// Tool name
    pub name: String,
    /// Tool arguments (as JSON string or Value)
    pub arguments: serde_json::Value,
}

/// LLM 工具定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Tool name
    pub name: String,
    /// Tool description
    pub description: String,
    /// Tool parameters (JSON Schema)
    pub parameters: serde_json::Value,
}

/// LLM 聊天完成响应
#[derive(Debug, Clone)]
pub struct ChatCompletionResponse {
    /// Response content
    pub content: Option<String>,
    /// Tool calls from the LLM
    pub tool_calls: Option<Vec<ToolCall>>,
    /// Usage statistics
    pub usage: Option<TokenUsage>,
}

/// LLM Provider trait - 定义 LLM 提供商接口
///
/// 这是一个核心抽象,定义了所有 LLM 提供商必须实现的最小接口。
///
/// # 示例
///
/// ```rust,ignore
/// use mofa_kernel::agent::types::{LLMProvider, ChatCompletionRequest, ChatCompletionResponse};
///
/// struct MyLLMProvider;
///
/// #[async_trait]
/// impl LLMProvider for MyLLMProvider {
///     fn name(&self) -> &str { "my-llm" }
///
///     async fn chat(&self, request: ChatCompletionRequest) -> AgentResult<ChatCompletionResponse> {
///         // 实现 LLM 调用逻辑
///     }
/// }
/// ```
#[async_trait]
pub trait LLMProvider: Send + Sync {
    /// Get provider name
    fn name(&self) -> &str;

    /// Complete a chat request
    async fn chat(
        &self,
        request: ChatCompletionRequest,
    ) -> super::error::AgentResult<ChatCompletionResponse>;
}

// ============================================================================
// 中断处理
// ============================================================================

/// 中断处理结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InterruptResult {
    /// 中断已确认,继续执行
    Acknowledged,
    /// 中断导致暂停
    Paused,
    /// 已中断(带部分结果)
    Interrupted {
        /// 部分结果
        partial_result: Option<String>,
    },
    /// 中断导致任务终止
    TaskTerminated {
        /// 部分结果
        partial_result: Option<AgentOutput>,
    },
    /// 中断被忽略(Agent 在关键区段)
    Ignored,
}

// ============================================================================
// 输入输出类型
// ============================================================================

/// 支持的输入类型
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum InputType {
    Text,
    Image,
    Audio,
    Video,
    Structured(String),
    Binary,
}

/// 支持的输出类型
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OutputType {
    Text,
    Json,
    StructuredJson,
    Stream,
    Binary,
    Multimodal,
}

// ============================================================================
// 辅助函数
// ============================================================================

fn base64_encode(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut result = Vec::new();

    for chunk in data.chunks(3) {
        let (n, _pad) = match chunk.len() {
            1 => (((chunk[0] as u32) << 16), 2),
            2 => (((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8), 1),
            _ => (
                ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32),
                0,
            ),
        };

        result.push(CHARS[((n >> 18) & 0x3F) as usize]);
        result.push(CHARS[((n >> 12) & 0x3F) as usize]);

        if chunk.len() > 1 {
            result.push(CHARS[((n >> 6) & 0x3F) as usize]);
        } else {
            result.push(b'=');
        }

        if chunk.len() > 2 {
            result.push(CHARS[(n & 0x3F) as usize]);
        } else {
            result.push(b'=');
        }
    }

    String::from_utf8(result).unwrap_or_default()
}

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

    #[test]
    fn test_agent_state_transitions() {
        let state = AgentState::Created;
        assert!(state.can_transition_to(&AgentState::Initializing));
        assert!(!state.can_transition_to(&AgentState::Executing));
    }

    #[test]
    fn test_agent_input_text() {
        let input = AgentInput::text("Hello");
        assert_eq!(input.as_text(), Some("Hello"));
        assert_eq!(input.to_text(), "Hello");
    }

    #[test]
    fn test_agent_output_text() {
        let output = AgentOutput::text("World")
            .with_duration(100)
            .with_metadata("key", serde_json::json!("value"));

        assert_eq!(output.as_text(), Some("World"));
        assert_eq!(output.duration_ms, 100);
        assert!(output.metadata.contains_key("key"));
    }

    #[test]
    fn test_tool_usage() {
        let usage = ToolUsage::success(
            "calculator",
            serde_json::json!({"a": 1, "b": 2}),
            serde_json::json!(3),
            50,
        );
        assert!(usage.success);
        assert_eq!(usage.name, "calculator");
    }
}