Skip to main content

tea_coding/
error.rs

1use thiserror::Error;
2
3/// Stable coding-product failure classification.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum CodingErrorCode {
6    /// Configuration or resource input was malformed or exceeded bounds.
7    InvalidInput,
8    /// A required path or resource was absent.
9    NotFound,
10    /// Project-local input was not trusted for the requested mode.
11    ProjectNotTrusted,
12    /// Persistent state could not be read or committed.
13    Persistence,
14    /// Credential resolution failed without exposing the credential.
15    Credential,
16    /// Provider construction or model execution failed.
17    Provider,
18    /// Policy denied or could not authorize an operation.
19    PolicyDenied,
20    /// An owned run was cancelled.
21    Cancelled,
22    /// Runtime assembly or execution failed.
23    Runtime,
24}
25
26/// Bounded path- and secret-independent coding-product error.
27#[derive(Debug, Clone, PartialEq, Eq, Error)]
28#[error("{code:?}: {message}")]
29pub struct CodingError {
30    code: CodingErrorCode,
31    message: String,
32}
33
34impl CodingError {
35    pub(crate) fn new(code: CodingErrorCode, message: impl Into<String>) -> Self {
36        let mut message = message.into();
37        if message.is_empty() {
38            "coding operation failed".clone_into(&mut message);
39        }
40        message.retain(|character| character != '\0');
41        if message.len() > 512 {
42            let boundary = message
43                .char_indices()
44                .map(|(index, _)| index)
45                .take_while(|index| *index <= 512)
46                .last()
47                .unwrap_or(0);
48            message.truncate(boundary);
49        }
50        Self { code, message }
51    }
52
53    /// Returns the stable machine-readable classification.
54    #[must_use]
55    pub const fn code(&self) -> CodingErrorCode {
56        self.code
57    }
58
59    /// Returns the bounded safe diagnostic.
60    #[must_use]
61    pub fn message(&self) -> &str {
62        &self.message
63    }
64}
65
66impl From<tea::RuntimeError> for CodingError {
67    fn from(error: tea::RuntimeError) -> Self {
68        let code = match error.code() {
69            tea::RuntimeErrorCode::ProviderFailure
70            | tea::RuntimeErrorCode::UnknownProvider
71            | tea::RuntimeErrorCode::UnknownModel => CodingErrorCode::Provider,
72            tea::RuntimeErrorCode::PolicyFailure => CodingErrorCode::PolicyDenied,
73            tea::RuntimeErrorCode::Cancelled => CodingErrorCode::Cancelled,
74            tea::RuntimeErrorCode::InvalidRequest
75            | tea::RuntimeErrorCode::UnknownProfile
76            | tea::RuntimeErrorCode::UnknownTool
77            | tea::RuntimeErrorCode::UnknownPolicyRule => CodingErrorCode::InvalidInput,
78            tea::RuntimeErrorCode::SessionFailure => CodingErrorCode::Persistence,
79            _ => CodingErrorCode::Runtime,
80        };
81        let message = match code {
82            CodingErrorCode::Provider if error.is_safe_diagnostic() => error.message(),
83            CodingErrorCode::Provider => "model provider operation failed",
84            CodingErrorCode::Persistence => "session persistence operation failed",
85            CodingErrorCode::Runtime => "coding runtime operation failed",
86            CodingErrorCode::Cancelled => "coding operation was cancelled",
87            CodingErrorCode::PolicyDenied
88            | CodingErrorCode::Credential
89            | CodingErrorCode::InvalidInput
90            | CodingErrorCode::NotFound
91            | CodingErrorCode::ProjectNotTrusted => error.message(),
92        };
93        Self::new(code, message)
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn normalized_provider_diagnostic_survives_product_error_conversion() {
103        let kernel = tea_kernel::KernelError::provider_failure(
104            tea_kernel::KernelErrorCode::ModelFailure,
105            "HTTP 403: blocked by gateway WAF",
106        );
107        let runtime = tea::RuntimeError::from(kernel);
108        let coding = CodingError::from(runtime);
109        assert_eq!(coding.code(), CodingErrorCode::Provider);
110        assert_eq!(coding.message(), "HTTP 403: blocked by gateway WAF");
111    }
112
113    #[test]
114    fn untrusted_provider_runtime_messages_stay_generic() {
115        let runtime = tea::RuntimeError::new(
116            tea::RuntimeErrorCode::ProviderFailure,
117            "sk-seeded-cli-credential-must-never-persist",
118        );
119        let coding = CodingError::from(runtime);
120        assert_eq!(coding.message(), "model provider operation failed");
121    }
122}