marona 5.2.0

Agent SDK with coordinated B2A and D2A protocols, realtime device streams, structured responses, MCP and A2A
Documentation
use std::fmt;

use serde_json::Value;

#[derive(Debug, Clone, PartialEq)]
pub struct GatewayError {
    pub message: String,
    pub status: Option<u16>,
    pub code: String,
    pub request_id: Option<String>,
    pub retryable: bool,
    pub required_action: Option<String>,
    pub retry_after_ms: Option<u64>,
    pub details: Option<Value>,
}

impl GatewayError {
    pub fn new(message: impl Into<String>, code: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            status: None,
            code: code.into(),
            request_id: None,
            retryable: false,
            required_action: None,
            retry_after_ms: None,
            details: None,
        }
    }

    pub fn status(mut self, value: u16) -> Self {
        self.status = Some(value);
        self
    }

    pub fn required_action(mut self, value: impl Into<String>) -> Self {
        self.required_action = Some(value.into());
        self
    }
}

impl fmt::Display for GatewayError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

/// A schema mismatch with recoverable output, equivalent to Python's
/// `MaronaOutputValidationError`. Do not log `raw_output`.
#[derive(Clone, PartialEq)]
pub struct OutputValidationError {
    pub agent_name: String,
    pub raw_output: Value,
    pub validation_errors: Vec<String>,
}

impl fmt::Debug for OutputValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OutputValidationError")
            .field("agent_name", &self.agent_name)
            .field("raw_output", &"[REDACTED]")
            .field("validation_errors", &self.validation_errors)
            .finish()
    }
}

impl fmt::Display for OutputValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Agent output did not match the required schema")
    }
}

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

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("{0}")]
    OutputValidation(#[from] Box<OutputValidationError>),
    #[error("{0}")]
    Api(Box<GatewayError>),
    #[error("{0}")]
    Authentication(Box<GatewayError>),
    #[error("{0}")]
    InvalidModelNamespace(Box<GatewayError>),
    #[error("{0}")]
    Model(Box<GatewayError>),
    #[error("{0}")]
    InsufficientCredits(Box<GatewayError>),
    #[error("{0}")]
    Provider(Box<GatewayError>),
    #[error("{0}")]
    CustomModel(Box<GatewayError>),
    #[error("{0}")]
    Billing(Box<GatewayError>),
    #[error("{0}")]
    Service(Box<GatewayError>),
    #[error("invalid configuration: {0}")]
    Configuration(String),
    #[error("invalid input: {0}")]
    Validation(String),
    #[error("permission required: {0}")]
    PermissionRequired(String),
    #[error("approval required: {0}")]
    ApprovalRequired(String),
    #[error("service connection required: {0}")]
    ServiceConnectionRequired(String),
    #[error("offline capability unavailable: {0}")]
    OfflineUnavailable(String),
    #[error("transport error: {0}")]
    Transport(#[from] reqwest::Error),
    #[error("protocol error: {0}")]
    Protocol(String),
    #[error("timeout after {0} ms")]
    Timeout(u64),
    #[error("function tool error: {0}")]
    Tool(String),
    #[error("A2A error: {0}")]
    A2A(String),
    #[error("realtime error: {0}")]
    Realtime(String),
}

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

impl Error {
    pub fn gateway(&self) -> Option<&GatewayError> {
        match self {
            Self::Api(error)
            | Self::Authentication(error)
            | Self::InvalidModelNamespace(error)
            | Self::Model(error)
            | Self::InsufficientCredits(error)
            | Self::Provider(error)
            | Self::CustomModel(error)
            | Self::Billing(error)
            | Self::Service(error) => Some(error),
            _ => None,
        }
    }

    pub(crate) fn api(status: reqwest::StatusCode, payload: Option<Value>) -> Self {
        Self::from_payload(
            Some(status.as_u16()),
            payload,
            "Marona could not complete the request.",
        )
    }

    pub(crate) fn stream(payload: &Value) -> Self {
        Self::from_payload(
            Some(500),
            Some(payload.clone()),
            "Marona Runtime stream failed.",
        )
    }

    fn from_payload(status: Option<u16>, payload: Option<Value>, fallback: &str) -> Self {
        let error = payload.as_ref().and_then(|value| value.get("error"));
        let code = error
            .and_then(|value| value.get("code"))
            .and_then(Value::as_str)
            .unwrap_or("INTERNAL_ERROR")
            .to_owned();
        let mut details = GatewayError {
            message: error
                .and_then(|value| value.get("message"))
                .and_then(Value::as_str)
                .unwrap_or(fallback)
                .to_owned(),
            status,
            code: code.clone(),
            request_id: error
                .and_then(|value| value.get("request_id"))
                .and_then(Value::as_str)
                .map(str::to_owned),
            retryable: error
                .and_then(|value| value.get("retryable"))
                .and_then(Value::as_bool)
                .unwrap_or(false),
            required_action: error
                .and_then(|value| value.get("required_action"))
                .and_then(Value::as_str)
                .map(str::to_owned),
            retry_after_ms: error
                .and_then(|value| value.get("retry_after_ms"))
                .and_then(Value::as_u64),
            details: error.and_then(|value| value.get("details")).cloned(),
        };
        if details.message.trim().is_empty() {
            details.message = fallback.to_owned();
        }
        match code.as_str() {
            "MARONA_API_KEY_REQUIRED"
            | "INVALID_MARONA_API_KEY"
            | "MARONA_API_KEY_REVOKED"
            | "MARONA_API_KEY_EXPIRED" => Self::Authentication(Box::new(details)),
            "INVALID_MODEL_NAMESPACE" => Self::InvalidModelNamespace(Box::new(details)),
            "INSUFFICIENT_CREDITS" => Self::InsufficientCredits(Box::new(details)),
            "BILLING_ERROR" => Self::Billing(Box::new(details)),
            "MARONA_SERVICE_UNAVAILABLE" | "INTERNAL_ERROR" => Self::Service(Box::new(details)),
            value if value.starts_with("MODEL_") => Self::Model(Box::new(details)),
            value if value.starts_with("PROVIDER_") => Self::Provider(Box::new(details)),
            value if value.starts_with("CUSTOM_MODEL_") => Self::CustomModel(Box::new(details)),
            _ => Self::Api(Box::new(details)),
        }
    }

    pub(crate) fn missing_api_key(message: impl Into<String>) -> Self {
        Self::Authentication(Box::new(
            GatewayError::new(message, "MARONA_API_KEY_REQUIRED")
                .status(401)
                .required_action("CONFIGURE_MARONA_API_KEY"),
        ))
    }

    pub(crate) fn invalid_model_namespace() -> Self {
        Self::InvalidModelNamespace(Box::new(
            GatewayError::new(
                "Models executed through Marona must use the marona/* namespace.",
                "INVALID_MODEL_NAMESPACE",
            )
            .status(400)
            .required_action("USE_OR_REGISTER_A_MARONA_MODEL"),
        ))
    }
}

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

    #[test]
    fn complete_gateway_error_code_matrix_is_preserved() {
        let codes = [
            "MARONA_API_KEY_REQUIRED",
            "INVALID_MARONA_API_KEY",
            "INVALID_MODEL_NAMESPACE",
            "MODEL_NOT_FOUND",
            "MODEL_DISABLED",
            "MODEL_ACCESS_DENIED",
            "MODEL_ALIAS_RESERVED",
            "MODEL_ALIAS_ALREADY_EXISTS",
            "PROVIDER_AUTHENTICATION_FAILED",
            "PROVIDER_RATE_LIMITED",
            "CUSTOM_MODEL_UNAVAILABLE",
            "CUSTOM_MODEL_AUTHENTICATION_FAILED",
            "CUSTOM_MODEL_TIMEOUT",
            "INSUFFICIENT_CREDITS",
            "RATE_LIMIT_EXCEEDED",
            "MARONA_SERVICE_UNAVAILABLE",
            "INTERNAL_ERROR",
        ];
        for code in codes {
            let error = Error::api(
                reqwest::StatusCode::BAD_REQUEST,
                Some(json!({
                    "error": {
                        "code": code,
                        "message": "Safe public message",
                        "request_id": "req_matrix",
                        "retryable": false,
                    }
                })),
            );
            let details = error.gateway().expect("gateway error details");
            assert_eq!(details.code, code);
            assert_eq!(details.request_id.as_deref(), Some("req_matrix"));
        }
    }
}