codex-sdk-rs 0.1.0

Rust SDK for the OpenAI Codex app server
Documentation
use serde_json::Value;
use thiserror::Error;

/// SDK result type.
pub type Result<T> = std::result::Result<T, Error>;

/// Typed classification for JSON-RPC failures.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JsonRpcErrorKind {
    Parse,
    InvalidRequest,
    MethodNotFound,
    InvalidParams,
    Internal,
    ServerBusy,
    RetryLimitExceeded,
    Server,
    Unknown,
}

/// Error object returned by the Codex app server.
#[derive(Clone, Debug, PartialEq)]
pub struct JsonRpcError {
    pub code: i64,
    pub message: String,
    pub data: Option<Value>,
    pub kind: JsonRpcErrorKind,
}

impl JsonRpcError {
    pub(crate) fn new(code: i64, message: String, data: Option<Value>) -> Self {
        let retry_limit = contains_retry_limit_text(&message);
        let overloaded = data.as_ref().is_some_and(is_server_overloaded);
        let kind = match code {
            -32700 => JsonRpcErrorKind::Parse,
            -32600 => JsonRpcErrorKind::InvalidRequest,
            -32601 => JsonRpcErrorKind::MethodNotFound,
            -32602 => JsonRpcErrorKind::InvalidParams,
            -32603 => JsonRpcErrorKind::Internal,
            -32099..=-32000 if retry_limit => JsonRpcErrorKind::RetryLimitExceeded,
            -32099..=-32000 if overloaded => JsonRpcErrorKind::ServerBusy,
            -32099..=-32000 => JsonRpcErrorKind::Server,
            _ => JsonRpcErrorKind::Unknown,
        };
        Self {
            code,
            message,
            data,
            kind,
        }
    }

    pub fn is_retryable(&self) -> bool {
        matches!(
            self.kind,
            JsonRpcErrorKind::ServerBusy | JsonRpcErrorKind::RetryLimitExceeded
        ) || self.data.as_ref().is_some_and(is_server_overloaded)
    }
}

impl std::fmt::Display for JsonRpcError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "JSON-RPC error {}: {}", self.code, self.message)
    }
}

impl std::error::Error for JsonRpcError {}

/// Errors produced by the SDK.
#[derive(Debug, Error)]
pub enum Error {
    #[error("{0}")]
    JsonRpc(#[from] JsonRpcError),
    #[error("Codex transport closed: {0}")]
    TransportClosed(String),
    #[error("Codex binary was not found: {0}")]
    BinaryNotFound(String),
    #[error("failed to launch Codex: {0}")]
    Launch(#[source] std::io::Error),
    #[error("Codex I/O failed: {0}")]
    Io(#[from] std::io::Error),
    #[error("invalid JSON from Codex: {0}")]
    Json(#[from] serde_json::Error),
    #[error("invalid SDK configuration: {0}")]
    InvalidConfiguration(String),
    #[error("invalid app-server response for {method}: {message}")]
    InvalidResponse {
        method: &'static str,
        message: String,
    },
    #[error("turn failed: {0}")]
    TurnFailed(String),
    #[error("turn stream ended before turn/completed")]
    MissingTurnCompletion,
    #[error("this handle's notification stream has already been consumed")]
    StreamConsumed,
    #[error("blocking SDK runtime failed: {0}")]
    BlockingRuntime(String),
}

/// Returns whether an error represents transient server overload.
pub fn is_retryable_error(error: &Error) -> bool {
    matches!(error, Error::JsonRpc(error) if error.is_retryable())
}

fn contains_retry_limit_text(message: &str) -> bool {
    let message = message.to_ascii_lowercase();
    message.contains("retry limit") || message.contains("too many failed attempts")
}

fn is_server_overloaded(value: &Value) -> bool {
    match value {
        Value::String(value) => value.eq_ignore_ascii_case("server_overloaded"),
        Value::Array(values) => values.iter().any(is_server_overloaded),
        Value::Object(values) => values.values().any(is_server_overloaded),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn maps_standard_json_rpc_errors() {
        let cases = [
            (-32700, JsonRpcErrorKind::Parse),
            (-32600, JsonRpcErrorKind::InvalidRequest),
            (-32601, JsonRpcErrorKind::MethodNotFound),
            (-32602, JsonRpcErrorKind::InvalidParams),
            (-32603, JsonRpcErrorKind::Internal),
            (-1, JsonRpcErrorKind::Unknown),
        ];

        for (code, expected) in cases {
            assert_eq!(
                JsonRpcError::new(code, "message".into(), None).kind,
                expected
            );
        }
    }

    #[test]
    fn detects_nested_overload_and_retry_limit_errors() {
        let overloaded = JsonRpcError::new(
            -32001,
            "busy".into(),
            Some(json!({"outer": [{"codexErrorInfo": "server_overloaded"}]})),
        );
        assert_eq!(overloaded.kind, JsonRpcErrorKind::ServerBusy);
        assert!(overloaded.is_retryable());

        let exhausted = JsonRpcError::new(-32001, "Retry limit reached".into(), None);
        assert_eq!(exhausted.kind, JsonRpcErrorKind::RetryLimitExceeded);
        assert!(exhausted.is_retryable());

        let ordinary = JsonRpcError::new(-32001, "bad request".into(), Some(json!({"x": 1})));
        assert_eq!(ordinary.kind, JsonRpcErrorKind::Server);
        assert!(!ordinary.is_retryable());
        assert!(!is_retryable_error(&Error::InvalidConfiguration(
            "invalid".into()
        )));
        assert_eq!(
            JsonRpcError::new(-32601, "missing".into(), None).to_string(),
            "JSON-RPC error -32601: missing"
        );
    }
}