use std::path::PathBuf;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AgentError {
#[error("Configuration file not found: {path}")]
ConfigNotFound {
path: PathBuf,
},
#[error("Invalid configuration: {message}")]
ConfigInvalid {
message: String,
},
#[error("Failed to connect to server at {url}: {reason}")]
ServerConnection {
url: String,
reason: String,
},
#[error("Server error: {message}")]
ServerError {
message: String,
},
#[error("Provider error: {0}")]
Provider(String),
#[error("Tool '{tool}' failed: {reason}")]
ToolExecution {
tool: String,
reason: String,
},
#[error("IO error: {context}")]
Io {
context: String,
#[source]
source: std::io::Error,
},
#[error("Session not found: {id}")]
SessionNotFound {
id: String,
},
#[error("Unexpected error: {0}")]
Unexpected(String),
}
impl AgentError {
pub fn io(context: impl Into<String>, source: std::io::Error) -> Self {
Self::Io {
context: context.into(),
source,
}
}
pub fn tool(tool: impl Into<String>, reason: impl Into<String>) -> Self {
Self::ToolExecution {
tool: tool.into(),
reason: reason.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_not_found_display() {
let err = AgentError::ConfigNotFound {
path: PathBuf::from("/path/to/config.toml"),
};
assert_eq!(
err.to_string(),
"Configuration file not found: /path/to/config.toml"
);
}
#[test]
fn test_error_with_source() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let err = AgentError::io("reading config", io_err);
assert_eq!(err.to_string(), "IO error: reading config");
use std::error::Error;
assert!(err.source().is_some());
}
#[test]
fn test_tool_error_convenience() {
let err = AgentError::tool("bash", "command not found");
assert_eq!(err.to_string(), "Tool 'bash' failed: command not found");
}
#[test]
fn test_server_connection_error() {
let err = AgentError::ServerConnection {
url: "http://localhost:8080".to_string(),
reason: "connection refused".to_string(),
};
assert!(err.to_string().contains("localhost:8080"));
assert!(err.to_string().contains("connection refused"));
}
#[test]
fn test_session_not_found() {
let err = AgentError::SessionNotFound {
id: "sess_123".to_string(),
};
assert_eq!(err.to_string(), "Session not found: sess_123");
}
}