Skip to main content

codive_core/
error.rs

1//! Error types for the Agent system
2//!
3//! This module defines custom error types using `thiserror`.
4//! These errors provide clear, user-friendly messages while
5//! preserving the underlying error chain for debugging.
6//!
7//! # Usage
8//!
9//! ```rust
10//! use codive_core::AgentError;
11//!
12//! fn load_config(path: &std::path::Path) -> Result<(), AgentError> {
13//!     if !path.exists() {
14//!         return Err(AgentError::ConfigNotFound {
15//!             path: path.to_path_buf(),
16//!         });
17//!     }
18//!     Ok(())
19//! }
20//! ```
21
22use std::path::PathBuf;
23use thiserror::Error;
24
25/// Errors that can occur in the Agent system
26///
27/// This enum covers all error cases across the agent:
28/// - Configuration errors
29/// - Server/network errors
30/// - Provider (LLM) errors
31/// - Tool execution errors
32/// - I/O errors
33#[derive(Error, Debug)]
34pub enum AgentError {
35    // =========================================================================
36    // Configuration Errors
37    // =========================================================================
38    /// Configuration file not found at the specified path
39    #[error("Configuration file not found: {path}")]
40    ConfigNotFound {
41        /// The path that was searched
42        path: PathBuf,
43    },
44
45    /// Configuration file exists but is invalid
46    #[error("Invalid configuration: {message}")]
47    ConfigInvalid {
48        /// Description of what's wrong
49        message: String,
50    },
51
52    // =========================================================================
53    // Server/Network Errors
54    // =========================================================================
55    /// Failed to establish connection to server
56    #[error("Failed to connect to server at {url}: {reason}")]
57    ServerConnection {
58        /// The URL we tried to connect to
59        url: String,
60        /// Why the connection failed
61        reason: String,
62    },
63
64    /// Server returned an error response
65    #[error("Server error: {message}")]
66    ServerError {
67        /// Error message from server
68        message: String,
69    },
70
71    // =========================================================================
72    // Provider (LLM) Errors
73    // =========================================================================
74    /// Error from an LLM provider (Anthropic, OpenAI, etc.)
75    #[error("Provider error: {0}")]
76    Provider(String),
77
78    // =========================================================================
79    // Tool Errors
80    // =========================================================================
81    /// A tool failed to execute
82    #[error("Tool '{tool}' failed: {reason}")]
83    ToolExecution {
84        /// Name of the tool that failed
85        tool: String,
86        /// Why it failed
87        reason: String,
88    },
89
90    // =========================================================================
91    // I/O Errors
92    // =========================================================================
93    /// I/O operation failed with context
94    #[error("IO error: {context}")]
95    Io {
96        /// What we were trying to do
97        context: String,
98        /// The underlying I/O error
99        #[source]
100        source: std::io::Error,
101    },
102
103    // =========================================================================
104    // Session Errors
105    // =========================================================================
106    /// Session not found
107    #[error("Session not found: {id}")]
108    SessionNotFound {
109        /// The session ID that wasn't found
110        id: String,
111    },
112
113    // =========================================================================
114    // Generic Errors
115    // =========================================================================
116    /// An unexpected error occurred
117    #[error("Unexpected error: {0}")]
118    Unexpected(String),
119}
120
121// ============================================================================
122// Convenience constructors
123// ============================================================================
124
125impl AgentError {
126    /// Create an I/O error with context
127    pub fn io(context: impl Into<String>, source: std::io::Error) -> Self {
128        Self::Io {
129            context: context.into(),
130            source,
131        }
132    }
133
134    /// Create a tool execution error
135    pub fn tool(tool: impl Into<String>, reason: impl Into<String>) -> Self {
136        Self::ToolExecution {
137            tool: tool.into(),
138            reason: reason.into(),
139        }
140    }
141}
142
143// ============================================================================
144// Tests
145// ============================================================================
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn test_config_not_found_display() {
153        let err = AgentError::ConfigNotFound {
154            path: PathBuf::from("/path/to/config.toml"),
155        };
156        assert_eq!(
157            err.to_string(),
158            "Configuration file not found: /path/to/config.toml"
159        );
160    }
161
162    #[test]
163    fn test_error_with_source() {
164        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
165        let err = AgentError::io("reading config", io_err);
166
167        assert_eq!(err.to_string(), "IO error: reading config");
168
169        // Verify source is preserved
170        use std::error::Error;
171        assert!(err.source().is_some());
172    }
173
174    #[test]
175    fn test_tool_error_convenience() {
176        let err = AgentError::tool("bash", "command not found");
177        assert_eq!(err.to_string(), "Tool 'bash' failed: command not found");
178    }
179
180    #[test]
181    fn test_server_connection_error() {
182        let err = AgentError::ServerConnection {
183            url: "http://localhost:8080".to_string(),
184            reason: "connection refused".to_string(),
185        };
186        assert!(err.to_string().contains("localhost:8080"));
187        assert!(err.to_string().contains("connection refused"));
188    }
189
190    #[test]
191    fn test_session_not_found() {
192        let err = AgentError::SessionNotFound {
193            id: "sess_123".to_string(),
194        };
195        assert_eq!(err.to_string(), "Session not found: sess_123");
196    }
197}