marona 5.2.0

Agent SDK with coordinated B2A and D2A protocols, realtime device streams, structured responses, MCP and A2A
Documentation
use std::{sync::Arc, time::Duration};

use crate::{core::Core, Error, Hub, Responses, Result, RuntimeMode, Skills};

const MARONA_API_KEY_REQUIRED: &str = "Marona Developer Key is required.\n\n\
Provide it through the SDK configuration or set the MARONA_API_KEY environment variable.\n\n\
Create/manage developer keys from the Marona Developer Portal.";

#[derive(Clone)]
pub struct MaronaBuilder {
    api_key: Option<String>,
    runtime_url: String,
    hub_url: String,
    mode: RuntimeMode,
    timeout: Duration,
    max_response_bytes: Option<usize>,
    client: Option<reqwest::Client>,
    headers: reqwest::header::HeaderMap,
}

impl std::fmt::Debug for MaronaBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MaronaBuilder")
            .field("api_key", &"[REDACTED]")
            .field("mode", &self.mode)
            .finish_non_exhaustive()
    }
}

impl Default for MaronaBuilder {
    fn default() -> Self {
        Self {
            api_key: None,
            runtime_url: "https://edge.marona.ai".into(),
            hub_url: "https://platform.marona.ai/api".into(),
            mode: RuntimeMode::Online,
            timeout: Duration::from_secs(360),
            max_response_bytes: None,
            client: None,
            headers: reqwest::header::HeaderMap::new(),
        }
    }
}

impl MaronaBuilder {
    pub fn api_key(mut self, value: impl Into<String>) -> Self {
        self.api_key = Some(value.into());
        self
    }
    pub fn runtime_url(mut self, value: impl Into<String>) -> Self {
        self.runtime_url = value.into();
        self
    }
    pub fn hub_url(mut self, value: impl Into<String>) -> Self {
        self.hub_url = value.into();
        self
    }
    pub fn mode(mut self, value: RuntimeMode) -> Self {
        self.mode = value;
        self
    }
    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = value;
        self
    }
    /// Limit bytes read per HTTP response, including error bodies and SSE streams.
    /// Defaults to no aggregate limit; individual SSE frames remain capped at 16 MiB.
    /// The limit applies after any decoding performed by a custom HTTP client.
    pub fn max_response_bytes(mut self, value: usize) -> Self {
        self.max_response_bytes = Some(value);
        self
    }
    pub fn http_client(mut self, value: reqwest::Client) -> Self {
        self.client = Some(value);
        self
    }
    pub fn headers(mut self, value: reqwest::header::HeaderMap) -> Self {
        self.headers = value;
        self
    }
    pub fn build(self) -> Result<Marona> {
        if self.max_response_bytes == Some(0) {
            return Err(Error::Configuration(
                "max_response_bytes must be greater than zero".into(),
            ));
        }
        let api_key = resolve_api_key(self.api_key, std::env::var("MARONA_API_KEY").ok())?;
        let mut core = Core::new(
            self.runtime_url,
            self.hub_url,
            Some(api_key),
            self.mode,
            self.timeout,
        )?;
        if let Some(client) = self.client {
            core.stream_client = client.clone();
            core.client = client;
        }
        core.max_response_bytes = self.max_response_bytes;
        core.headers = self.headers;
        core.headers.remove(reqwest::header::AUTHORIZATION);
        for value in core.headers.values_mut() {
            value.set_sensitive(true);
        }
        let core = Arc::new(core);
        Ok(Marona {
            hub: Hub { core: core.clone() },
            responses: Responses { core: core.clone() },
            skills: Skills { core: core.clone() },
            apps: crate::Apps { core: core.clone() },
            b2a: crate::B2AClient { core: core.clone() },
            #[cfg(feature = "realtime")]
            core,
        })
    }
}

fn resolve_api_key(explicit: Option<String>, environment: Option<String>) -> Result<String> {
    let candidate = match explicit {
        Some(value) => value,
        None => environment.unwrap_or_default(),
    };
    let resolved = candidate.trim();
    if resolved.is_empty() {
        return Err(Error::missing_api_key(MARONA_API_KEY_REQUIRED));
    }
    Ok(resolved.to_owned())
}

#[cfg(test)]
mod tests {
    use super::resolve_api_key;

    #[test]
    fn explicit_key_overrides_environment() {
        assert_eq!(
            resolve_api_key(
                Some(" mr_live_explicit ".into()),
                Some("mr_live_env".into())
            )
            .unwrap(),
            "mr_live_explicit"
        );
    }

    #[test]
    fn environment_key_is_used_when_explicit_key_is_omitted() {
        assert_eq!(
            resolve_api_key(None, Some(" mr_live_env ".into())).unwrap(),
            "mr_live_env"
        );
    }

    #[test]
    fn explicit_whitespace_key_is_rejected() {
        assert!(resolve_api_key(Some("   ".into()), Some("mr_live_env".into())).is_err());
    }
}

#[derive(Clone, Debug)]
pub struct Marona {
    pub hub: Hub,
    pub responses: Responses,
    pub skills: Skills,
    pub apps: crate::Apps,
    pub b2a: crate::B2AClient,
    #[cfg(feature = "realtime")]
    pub(crate) core: Arc<Core>,
}

impl Marona {
    pub fn builder() -> MaronaBuilder {
        MaronaBuilder::default()
    }
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        Self::builder().api_key(api_key).build()
    }
}