Skip to main content

mofa_kernel/agent/
error.rs

1//! Agent 错误类型定义
2//!
3//! 统一的 Agent 错误处理
4
5use std::fmt;
6use thiserror::Error;
7
8/// Agent 操作结果类型
9pub type AgentResult<T> = Result<T, AgentError>;
10
11/// Agent 错误类型
12#[derive(Debug, Error)]
13pub enum AgentError {
14    /// Agent 未找到
15    #[error("Agent not found: {0}")]
16    NotFound(String),
17
18    /// Agent 初始化失败
19    #[error("Agent initialization failed: {0}")]
20    InitializationFailed(String),
21
22    #[error("Agent validation failed: {0}")]
23    ValidationFailed(String),
24
25    /// Agent 执行失败
26    #[error("Agent execution failed: {0}")]
27    ExecutionFailed(String),
28
29    /// 工具执行失败
30    #[error("Tool execution failed: {tool_name}: {message}")]
31    ToolExecutionFailed { tool_name: String, message: String },
32
33    /// 工具未找到
34    #[error("Tool not found: {0}")]
35    ToolNotFound(String),
36
37    /// 配置错误
38    #[error("Configuration error: {0}")]
39    ConfigError(String),
40
41    #[error("Shutdown Failed: {0}")]
42    ShutdownFailed(String),
43    /// 无效输入
44    #[error("Invalid input: {0}")]
45    InvalidInput(String),
46
47    /// 无效输出
48    #[error("Invalid output: {0}")]
49    InvalidOutput(String),
50
51    /// 状态错误
52    #[error("Invalid state transition: from {from:?} to {to:?}")]
53    InvalidStateTransition { from: String, to: String },
54
55    /// 超时错误
56    #[error("Operation timed out after {duration_ms}ms")]
57    Timeout { duration_ms: u64 },
58
59    /// 中断错误
60    #[error("Operation was interrupted")]
61    Interrupted,
62
63    /// 资源不可用
64    #[error("Resource unavailable: {0}")]
65    ResourceUnavailable(String),
66
67    /// 能力不匹配
68    #[error("Capability mismatch: required {required}, available {available}")]
69    CapabilityMismatch { required: String, available: String },
70
71    /// 工厂未找到
72    #[error("Agent factory not found: {0}")]
73    FactoryNotFound(String),
74
75    /// 注册失败
76    #[error("Registration failed: {0}")]
77    RegistrationFailed(String),
78
79    /// 内存错误
80    #[error("Memory error: {0}")]
81    MemoryError(String),
82
83    /// 推理错误
84    #[error("Reasoning error: {0}")]
85    ReasoningError(String),
86
87    /// 协调错误
88    #[error("Coordination error: {0}")]
89    CoordinationError(String),
90
91    /// 序列化错误
92    #[error("Serialization error: {0}")]
93    SerializationError(String),
94
95    /// IO 错误
96    #[error("IO error: {0}")]
97    IoError(String),
98
99    /// 内部错误
100    #[error("Internal error: {0}")]
101    Internal(String),
102
103    /// 其他错误
104    #[error("{0}")]
105    Other(String),
106}
107
108impl AgentError {
109    /// 创建工具执行失败错误
110    pub fn tool_execution_failed(tool_name: impl Into<String>, message: impl Into<String>) -> Self {
111        Self::ToolExecutionFailed {
112            tool_name: tool_name.into(),
113            message: message.into(),
114        }
115    }
116
117    /// 创建状态转换错误
118    pub fn invalid_state_transition(from: impl fmt::Debug, to: impl fmt::Debug) -> Self {
119        Self::InvalidStateTransition {
120            from: format!("{:?}", from),
121            to: format!("{:?}", to),
122        }
123    }
124
125    /// 创建超时错误
126    pub fn timeout(duration_ms: u64) -> Self {
127        Self::Timeout { duration_ms }
128    }
129
130    /// 创建能力不匹配错误
131    pub fn capability_mismatch(required: impl Into<String>, available: impl Into<String>) -> Self {
132        Self::CapabilityMismatch {
133            required: required.into(),
134            available: available.into(),
135        }
136    }
137}
138
139impl From<std::io::Error> for AgentError {
140    fn from(err: std::io::Error) -> Self {
141        AgentError::IoError(err.to_string())
142    }
143}
144
145impl From<serde_json::Error> for AgentError {
146    fn from(err: serde_json::Error) -> Self {
147        AgentError::SerializationError(err.to_string())
148    }
149}
150
151impl From<anyhow::Error> for AgentError {
152    fn from(err: anyhow::Error) -> Self {
153        AgentError::Internal(err.to_string())
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn test_error_display() {
163        let err = AgentError::NotFound("test-agent".to_string());
164        assert_eq!(err.to_string(), "Agent not found: test-agent");
165    }
166
167    #[test]
168    fn test_tool_execution_failed() {
169        let err = AgentError::tool_execution_failed("calculator", "division by zero");
170        assert!(err.to_string().contains("calculator"));
171        assert!(err.to_string().contains("division by zero"));
172    }
173}