codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
//! Error types for the Agent system
//!
//! This module defines custom error types using `thiserror`.
//! These errors provide clear, user-friendly messages while
//! preserving the underlying error chain for debugging.
//!
//! # Usage
//!
//! ```rust
//! use codive_core::AgentError;
//!
//! fn load_config(path: &std::path::Path) -> Result<(), AgentError> {
//!     if !path.exists() {
//!         return Err(AgentError::ConfigNotFound {
//!             path: path.to_path_buf(),
//!         });
//!     }
//!     Ok(())
//! }
//! ```

use std::path::PathBuf;
use thiserror::Error;

/// Errors that can occur in the Agent system
///
/// This enum covers all error cases across the agent:
/// - Configuration errors
/// - Server/network errors
/// - Provider (LLM) errors
/// - Tool execution errors
/// - I/O errors
#[derive(Error, Debug)]
pub enum AgentError {
    // =========================================================================
    // Configuration Errors
    // =========================================================================
    /// Configuration file not found at the specified path
    #[error("Configuration file not found: {path}")]
    ConfigNotFound {
        /// The path that was searched
        path: PathBuf,
    },

    /// Configuration file exists but is invalid
    #[error("Invalid configuration: {message}")]
    ConfigInvalid {
        /// Description of what's wrong
        message: String,
    },

    // =========================================================================
    // Server/Network Errors
    // =========================================================================
    /// Failed to establish connection to server
    #[error("Failed to connect to server at {url}: {reason}")]
    ServerConnection {
        /// The URL we tried to connect to
        url: String,
        /// Why the connection failed
        reason: String,
    },

    /// Server returned an error response
    #[error("Server error: {message}")]
    ServerError {
        /// Error message from server
        message: String,
    },

    // =========================================================================
    // Provider (LLM) Errors
    // =========================================================================
    /// Error from an LLM provider (Anthropic, OpenAI, etc.)
    #[error("Provider error: {0}")]
    Provider(String),

    // =========================================================================
    // Tool Errors
    // =========================================================================
    /// A tool failed to execute
    #[error("Tool '{tool}' failed: {reason}")]
    ToolExecution {
        /// Name of the tool that failed
        tool: String,
        /// Why it failed
        reason: String,
    },

    // =========================================================================
    // I/O Errors
    // =========================================================================
    /// I/O operation failed with context
    #[error("IO error: {context}")]
    Io {
        /// What we were trying to do
        context: String,
        /// The underlying I/O error
        #[source]
        source: std::io::Error,
    },

    // =========================================================================
    // Session Errors
    // =========================================================================
    /// Session not found
    #[error("Session not found: {id}")]
    SessionNotFound {
        /// The session ID that wasn't found
        id: String,
    },

    // =========================================================================
    // Generic Errors
    // =========================================================================
    /// An unexpected error occurred
    #[error("Unexpected error: {0}")]
    Unexpected(String),
}

// ============================================================================
// Convenience constructors
// ============================================================================

impl AgentError {
    /// Create an I/O error with context
    pub fn io(context: impl Into<String>, source: std::io::Error) -> Self {
        Self::Io {
            context: context.into(),
            source,
        }
    }

    /// Create a tool execution error
    pub fn tool(tool: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::ToolExecution {
            tool: tool.into(),
            reason: reason.into(),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[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");

        // Verify source is preserved
        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");
    }
}