marona 4.0.0

Universal Model Gateway and MCP/Skill SDK with mandatory project-scoped Marona authentication
Documentation
//! Agent-bound B2A lifecycle, with independent pluggable neural providers.
use crate::{
    Agent, B2AClient, B2ACodec, B2ADecodeResult, B2ADecodeStatus, B2AEncodedFeedback, B2AMessage,
    B2AOpenSession, B2ASession, Error, Result,
};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::{
    collections::{BTreeSet, VecDeque},
    sync::Arc,
    time::Duration,
};

#[async_trait]
pub trait B2AProvider: Send + Sync {
    async fn decode(&self, signal: &Value) -> Result<B2ADecodeResult>;
    async fn encode(
        &self,
        response: &Value,
        profile: &str,
        context: &Value,
        media_types: &[&str],
    ) -> Result<B2AEncodedFeedback>;
}
#[async_trait]
impl B2AProvider for B2ACodec {
    async fn decode(&self, signal: &Value) -> Result<B2ADecodeResult> {
        self.decode(signal, true).await
    }
    async fn encode(
        &self,
        response: &Value,
        profile: &str,
        context: &Value,
        media_types: &[&str],
    ) -> Result<B2AEncodedFeedback> {
        self.encode_with(response, profile, true, context, media_types)
            .await
    }
}
#[derive(Clone)]
pub struct B2A {
    pub provider: Arc<dyn B2AProvider>,
    pub output_profile: String,
    pub output_media_types: Vec<String>,
    pub context: Value,
    pub execute: bool,
}
impl B2A {
    pub fn new(provider: impl B2AProvider + 'static, output_profile: impl Into<String>) -> Self {
        Self {
            provider: Arc::new(provider),
            output_profile: output_profile.into(),
            output_media_types: vec!["application/json".into()],
            context: json!({}),
            execute: true,
        }
    }
}
#[derive(Clone, Debug)]
pub struct B2ASessionEvent {
    pub event_type: String,
    pub data: Value,
    pub response_id: Option<String>,
    pub feedback: Option<B2AEncodedFeedback>,
}
pub struct B2AConnection {
    client: B2AClient,
    config: B2A,
    snapshot: B2ASession,
    pub session_id: String,
    pub protocol_session_id: String,
    cursor: u64,
    queue: VecDeque<B2ASessionEvent>,
    pending: BTreeSet<String>,
    closed: bool,
    failed: bool,
}
fn bad(message: &str) -> Error {
    Error::Validation(message.into())
}
impl B2AConnection {
    pub fn status(&self) -> &str {
        if self.closed {
            "closed"
        } else if self.failed {
            "failed"
        } else {
            &self.snapshot.state
        }
    }
    async fn active(&mut self) -> Result<()> {
        if self.closed || self.failed {
            return Err(bad("B2A connection is inactive"));
        }
        self.snapshot = self.client.get_session(&self.protocol_session_id).await?;
        let scopes = self.snapshot.consent["scopes"].as_array();
        if self.snapshot.state != "active"
            || self.snapshot.consent["granted"] != true
            || !["intent", "feedback"]
                .iter()
                .all(|s| scopes.is_some_and(|v| v.contains(&json!(s))))
        {
            return Err(bad("B2A session is inactive or authorization was revoked"));
        }
        Ok(())
    }
    pub async fn send_signal(&mut self, signal: &Value) -> Result<()> {
        self.active().await?;
        if !signal.is_object() {
            return Err(bad("Signal must be a JSON object"));
        }
        let decoded = self.config.provider.decode(signal).await?;
        let Some(intent) = decoded.intent else {
            if decoded.status == B2ADecodeStatus::Decoded {
                return Err(bad("Decoder returned no intent"));
            }
            self.queue.push_back(B2ASessionEvent {
                event_type: "signal.status".into(),
                data: json!({"status":decoded.status,"uncertainty":decoded.uncertainty}),
                response_id: None,
                feedback: None,
            });
            return Ok(());
        };
        if decoded.status != B2ADecodeStatus::Decoded {
            return Err(bad("Abstaining decoder returned an intent"));
        }
        self.active().await?;
        let message = B2AMessage::intent(
            &self.protocol_session_id,
            self.snapshot.next_sequence,
            intent,
            self.snapshot.context_revision,
            self.config.execute,
        )?;
        self.send(message).await
    }
    async fn send(&mut self, message: B2AMessage) -> Result<()> {
        // Mark before awaiting: cancellation or a lost response must not allow a new send.
        self.failed = true;
        let exchange = self
            .client
            .send_message(&self.protocol_session_id, &message)
            .await?;
        self.snapshot = exchange.session;
        self.failed = false;
        if let Err(error) = self.poll().await {
            self.failed = true;
            return Err(error);
        }
        Ok(())
    }
    async fn poll(&mut self) -> Result<()> {
        let page = self
            .client
            .events(&self.protocol_session_id, self.cursor, 100)
            .await?;
        for event in page.events {
            if event.sequence <= self.cursor {
                continue;
            }
            let feedback = if event.event_type == "agent.response" {
                self.active().await?;
                let media: Vec<&str> = self
                    .config
                    .output_media_types
                    .iter()
                    .map(String::as_str)
                    .collect();
                let value = self
                    .config
                    .provider
                    .encode(
                        &event.payload,
                        &self.config.output_profile,
                        &self.snapshot.context,
                        &media,
                    )
                    .await?;
                if value.profile != self.config.output_profile
                    || !self.config.output_media_types.contains(&value.media_type)
                {
                    return Err(bad("Encoder output does not match the interface"));
                }
                self.active().await?;
                self.pending.insert(event.event_id.clone());
                Some(value)
            } else {
                None
            };
            if event.event_type == "session.closed" {
                self.closed = true;
            }
            self.queue.push_back(B2ASessionEvent {
                event_type: if feedback.is_some() {
                    "feedback".into()
                } else {
                    event.event_type
                },
                data: event.payload,
                response_id: Some(event.event_id),
                feedback,
            });
            self.cursor = event.sequence;
        }
        Ok(())
    }
    pub async fn update_context(&mut self, context: Value) -> Result<()> {
        if !context.is_object() {
            return Err(bad("Context must be a JSON object"));
        }
        self.active().await?;
        self.send(B2AMessage::new(
            &self.protocol_session_id,
            self.snapshot.next_sequence,
            "context.update",
            json!({"base_revision":self.snapshot.context_revision,"context":context}),
        )?)
        .await
    }
    pub async fn respond_to_approval(&mut self, approval_id: &str, approved: bool) -> Result<()> {
        if approval_id.trim().is_empty() {
            return Err(bad("Approval ID is required"));
        }
        self.active().await?;
        self.send(B2AMessage::new(
            &self.protocol_session_id,
            self.snapshot.next_sequence,
            "approval.respond",
            json!({"approval_id":approval_id,"decision":if approved {"approve"} else {"reject"}}),
        )?)
        .await
    }
    pub async fn acknowledge_feedback(&mut self, response_id: &str, presented: bool) -> Result<()> {
        self.active().await?;
        if !self.pending.contains(response_id) {
            return Err(bad("Feedback response is not pending"));
        }
        self.send(B2AMessage::new(
            &self.protocol_session_id,
            self.snapshot.next_sequence,
            "feedback.ack",
            json!({"response_id":response_id,"status":if presented {"presented"} else {"failed"}}),
        )?)
        .await?;
        self.pending.remove(response_id);
        Ok(())
    }
    pub async fn next_event(&mut self) -> Result<Option<B2ASessionEvent>> {
        loop {
            if self.closed {
                return Ok(None);
            }
            if let Some(event) = self.queue.pop_front() {
                if event.feedback.is_some() {
                    self.active().await?;
                }
                return Ok(Some(event));
            }
            if self.failed {
                return Err(bad(
                    "B2A connection failed; no automatic replay was attempted",
                ));
            }
            if let Err(error) = self.poll().await {
                self.failed = true;
                return Err(error);
            }
            if self.queue.is_empty() {
                tokio::time::sleep(Duration::from_millis(250)).await;
            }
        }
    }
    pub async fn close(&mut self) -> Result<()> {
        if !self.closed {
            self.closed = true;
            self.client.close_session(&self.protocol_session_id).await?;
        }
        Ok(())
    }
}
pub struct B2ARunner;
impl B2ARunner {
    pub async fn connect(agent: &Agent, user_id: &str, session_id: &str) -> Result<B2AConnection> {
        let config = agent
            .b2a
            .clone()
            .ok_or_else(|| bad("Configure Agent.b2a before connecting"))?;
        if user_id.trim().is_empty()
            || session_id.trim().is_empty()
            || config.output_profile.trim().is_empty()
            || config.output_media_types.is_empty()
            || !config.context.is_object()
        {
            return Err(bad("Invalid B2A configuration or identity"));
        }
        let client = agent.marona.b2a.clone();
        let mut request = B2AOpenSession::new(
            user_id,
            uuid::Uuid::new_v4().to_string(),
            json!({"granted":true,"scopes":["intent","feedback","context"]}),
            json!({"input":["semantic.intent"],"output":config.output_media_types}),
        )
        .with_agent(agent)?;
        request.conversation_id = Some(session_id.into());
        request.context = config.context.clone();
        let snapshot = client.open_session(request).await?;
        Ok(B2AConnection {
            protocol_session_id: snapshot.session_id.clone(),
            session_id: session_id.into(),
            snapshot,
            client,
            config,
            cursor: 0,
            queue: VecDeque::new(),
            pending: BTreeSet::new(),
            closed: false,
            failed: false,
        })
    }
}