Skip to main content

codex_sdk_rs/
error.rs

1use serde_json::Value;
2use thiserror::Error;
3
4/// SDK result type.
5pub type Result<T> = std::result::Result<T, Error>;
6
7/// Typed classification for JSON-RPC failures.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum JsonRpcErrorKind {
10    Parse,
11    InvalidRequest,
12    MethodNotFound,
13    InvalidParams,
14    Internal,
15    ServerBusy,
16    RetryLimitExceeded,
17    Server,
18    Unknown,
19}
20
21/// Error object returned by the Codex app server.
22#[derive(Clone, Debug, PartialEq)]
23pub struct JsonRpcError {
24    pub code: i64,
25    pub message: String,
26    pub data: Option<Value>,
27    pub kind: JsonRpcErrorKind,
28}
29
30impl JsonRpcError {
31    pub(crate) fn new(code: i64, message: String, data: Option<Value>) -> Self {
32        let retry_limit = contains_retry_limit_text(&message);
33        let overloaded = data.as_ref().is_some_and(is_server_overloaded);
34        let kind = match code {
35            -32700 => JsonRpcErrorKind::Parse,
36            -32600 => JsonRpcErrorKind::InvalidRequest,
37            -32601 => JsonRpcErrorKind::MethodNotFound,
38            -32602 => JsonRpcErrorKind::InvalidParams,
39            -32603 => JsonRpcErrorKind::Internal,
40            -32099..=-32000 if retry_limit => JsonRpcErrorKind::RetryLimitExceeded,
41            -32099..=-32000 if overloaded => JsonRpcErrorKind::ServerBusy,
42            -32099..=-32000 => JsonRpcErrorKind::Server,
43            _ => JsonRpcErrorKind::Unknown,
44        };
45        Self {
46            code,
47            message,
48            data,
49            kind,
50        }
51    }
52
53    pub fn is_retryable(&self) -> bool {
54        matches!(
55            self.kind,
56            JsonRpcErrorKind::ServerBusy | JsonRpcErrorKind::RetryLimitExceeded
57        ) || self.data.as_ref().is_some_and(is_server_overloaded)
58    }
59}
60
61impl std::fmt::Display for JsonRpcError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(f, "JSON-RPC error {}: {}", self.code, self.message)
64    }
65}
66
67impl std::error::Error for JsonRpcError {}
68
69/// Errors produced by the SDK.
70#[derive(Debug, Error)]
71pub enum Error {
72    #[error("{0}")]
73    JsonRpc(#[from] JsonRpcError),
74    #[error("Codex transport closed: {0}")]
75    TransportClosed(String),
76    #[error("Codex binary was not found: {0}")]
77    BinaryNotFound(String),
78    #[error("failed to launch Codex: {0}")]
79    Launch(#[source] std::io::Error),
80    #[error("Codex I/O failed: {0}")]
81    Io(#[from] std::io::Error),
82    #[error("invalid JSON from Codex: {0}")]
83    Json(#[from] serde_json::Error),
84    #[error("invalid SDK configuration: {0}")]
85    InvalidConfiguration(String),
86    #[error("invalid app-server response for {method}: {message}")]
87    InvalidResponse {
88        method: &'static str,
89        message: String,
90    },
91    #[error("turn failed: {0}")]
92    TurnFailed(String),
93    #[error("turn stream ended before turn/completed")]
94    MissingTurnCompletion,
95    #[error("this handle's notification stream has already been consumed")]
96    StreamConsumed,
97    #[error("blocking SDK runtime failed: {0}")]
98    BlockingRuntime(String),
99}
100
101/// Returns whether an error represents transient server overload.
102pub fn is_retryable_error(error: &Error) -> bool {
103    matches!(error, Error::JsonRpc(error) if error.is_retryable())
104}
105
106fn contains_retry_limit_text(message: &str) -> bool {
107    let message = message.to_ascii_lowercase();
108    message.contains("retry limit") || message.contains("too many failed attempts")
109}
110
111fn is_server_overloaded(value: &Value) -> bool {
112    match value {
113        Value::String(value) => value.eq_ignore_ascii_case("server_overloaded"),
114        Value::Array(values) => values.iter().any(is_server_overloaded),
115        Value::Object(values) => values.values().any(is_server_overloaded),
116        _ => false,
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use serde_json::json;
124
125    #[test]
126    fn maps_standard_json_rpc_errors() {
127        let cases = [
128            (-32700, JsonRpcErrorKind::Parse),
129            (-32600, JsonRpcErrorKind::InvalidRequest),
130            (-32601, JsonRpcErrorKind::MethodNotFound),
131            (-32602, JsonRpcErrorKind::InvalidParams),
132            (-32603, JsonRpcErrorKind::Internal),
133            (-1, JsonRpcErrorKind::Unknown),
134        ];
135
136        for (code, expected) in cases {
137            assert_eq!(
138                JsonRpcError::new(code, "message".into(), None).kind,
139                expected
140            );
141        }
142    }
143
144    #[test]
145    fn detects_nested_overload_and_retry_limit_errors() {
146        let overloaded = JsonRpcError::new(
147            -32001,
148            "busy".into(),
149            Some(json!({"outer": [{"codexErrorInfo": "server_overloaded"}]})),
150        );
151        assert_eq!(overloaded.kind, JsonRpcErrorKind::ServerBusy);
152        assert!(overloaded.is_retryable());
153
154        let exhausted = JsonRpcError::new(-32001, "Retry limit reached".into(), None);
155        assert_eq!(exhausted.kind, JsonRpcErrorKind::RetryLimitExceeded);
156        assert!(exhausted.is_retryable());
157
158        let ordinary = JsonRpcError::new(-32001, "bad request".into(), Some(json!({"x": 1})));
159        assert_eq!(ordinary.kind, JsonRpcErrorKind::Server);
160        assert!(!ordinary.is_retryable());
161        assert!(!is_retryable_error(&Error::InvalidConfiguration(
162            "invalid".into()
163        )));
164        assert_eq!(
165            JsonRpcError::new(-32601, "missing".into(), None).to_string(),
166            "JSON-RPC error -32601: missing"
167        );
168    }
169}