use crate::{
Agent, B2AClient, B2ACodec, B2ADecodeResult, B2ADecodeStatus, B2AEncodedFeedback, B2AMessage,
B2AOpenSession, B2ASession, Error, Result,
};
use async_trait::async_trait;
use futures_util::StreamExt;
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>,
agent: Agent,
last_result: Option<crate::RunResult>,
closed: bool,
failed: bool,
pub streaming: bool,
stream: Option<crate::b2a::B2AEventStream>,
preview: String,
}
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
|| ![
if self.snapshot.version == "1.0" {
"message"
} else {
"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<()> {
if self.stream.is_some() {
return Err(bad("Wait for feedback before sending another signal"));
}
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 message = match decoded.message {
Some(message) => Some(message),
None => decoded.intent.map(|intent| B2AMessage::multimodal("neural_decoder", vec![json!({"type": if intent.content.is_string() {"text"} else {"legacy:semantic"},"data":intent.content})])).transpose()?,
};
let Some(message) = message 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 = message.bind(
&self.protocol_session_id,
self.snapshot.next_sequence,
self.snapshot.context_revision,
self.config.execute,
)?;
self.send(message).await
}
async fn send(&mut self, mut message: B2AMessage) -> Result<()> {
message.version.clone_from(&self.snapshot.version);
self.failed = true;
if self.streaming && matches!(message.message_type.as_str(), "message" | "intent.submit") {
self.preview.clear();
let mut stream = self
.client
.stream_message(&self.protocol_session_id, &message)
.await?;
let started = stream
.next()
.await
.ok_or_else(|| bad("B2A stream closed before acceptance"))??;
if started["type"] != "stream.started" {
return Err(bad("Missing B2A acceptance"));
}
self.stream = Some(stream);
self.failed = false;
return Ok(());
}
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 receive_stream(&mut self) -> Result<()> {
let event = self.stream.as_mut().unwrap().next().await.ok_or_else(|| {
bad("B2A stream disconnected before completion; no replay attempted")
})??;
match event["type"].as_str() {
Some("message") => {
let message = B2AMessage::from_value(event.clone())?;
let mut text: String = message.payload["content"]
.as_array()
.unwrap()
.iter()
.filter(|v| v["type"] == "text")
.filter_map(|v| v["data"].as_str())
.collect();
self.queue.push_back(B2ASessionEvent {
event_type: "message".into(),
data: event,
response_id: None,
feedback: None,
});
if message
.stream
.as_ref()
.is_some_and(|v| v["mode"] == "delta")
{
text = format!("{}{text}", self.preview);
}
if let Some(delta) = text.strip_prefix(&self.preview) {
self.queue.push_back(B2ASessionEvent {
event_type: "agent.delta".into(),
data: json!({"delta":delta}),
response_id: None,
feedback: None,
});
}
self.preview = text;
}
Some("agent.delta") => {
if !event["payload"]["delta"].is_string() {
return Err(bad("Invalid B2A text delta"));
}
self.queue.push_back(B2ASessionEvent {
event_type: "agent.delta".into(),
data: event["payload"].clone(),
response_id: None,
feedback: None,
});
}
Some("exchange.completed") => {
let exchange: crate::b2a::B2AExchange =
serde_json::from_value(event["exchange"].clone())
.map_err(|_| bad("Invalid B2A exchange"))?;
if exchange.session.session_id != self.protocol_session_id {
return Err(bad("B2A exchange identity mismatch"));
}
self.snapshot = exchange.session;
self.stream = None;
self.poll().await?;
}
Some("stream.failed") => return Err(bad("B2A stream failed; no replay attempted")),
_ => {}
}
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 matches!(event.event_type.as_str(), "message" | "agent.response") {
let envelope = serde_json::to_value(&event).map_err(|e| bad(&e.to_string()))?;
if event.event_type == "message" {
B2AMessage::from_value(envelope.clone())?;
}
self.active().await?;
self.last_result =
completed_result(&self.agent, &event.payload, &self.session_id).await?;
if event.event_type == "message" {
self.queue.push_back(B2ASessionEvent {
event_type: "message".into(),
data: envelope.clone(),
response_id: Some(event.event_id.clone()),
feedback: None,
});
}
let media: Vec<&str> = self
.config
.output_media_types
.iter()
.map(String::as_str)
.collect();
let value = self
.config
.provider
.encode(
if event.event_type == "message" {
&envelope
} else {
&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",
));
}
let received = if self.stream.is_some() {
self.receive_stream().await
} else {
self.poll().await
};
if let Err(error) = received {
self.failed = true;
self.stream = None;
return Err(error);
}
if self.queue.is_empty() && self.stream.is_none() {
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
}
pub async fn close(&mut self) -> Result<()> {
if !self.closed {
self.closed = true;
self.stream = None;
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 selected = crate::protocols::select(agent, Some("b2a"))?.unwrap();
let config = (selected.as_ref() as &dyn std::any::Any)
.downcast_ref::<B2A>()
.ok_or_else(|| bad("Configure B2A in Agent.protocols"))?
.clone();
Self::open(agent, config, user_id, session_id).await
}
async fn open(
agent: &Agent,
config: B2A,
user_id: &str,
session_id: &str,
) -> Result<B2AConnection> {
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":["message","feedback","context"]}),
json!({"input":["message"],"output":config.output_media_types}),
)
.with_agent(agent)?;
request.protocol_version = "1.0".into();
request.conversation_id = Some(session_id.into());
request.context = config.context.clone();
let capabilities = client.capabilities().await?;
let streaming = capabilities["transports"]
.as_array()
.is_some_and(|values| values.contains(&json!("http-sse")));
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(),
agent: agent.clone(),
last_result: None,
closed: false,
failed: false,
streaming,
stream: None,
preview: String::new(),
})
}
}
pub(crate) async fn completed_result(
agent: &Agent,
payload: &Value,
session_id: &str,
) -> Result<Option<crate::RunResult>> {
if payload["status"] != "completed" {
return Ok(None);
}
let response = crate::responses::response_from_value(payload["response"].clone())?;
if response.status != "completed"
|| response.extra.get("needs_permission") == Some(&json!(true))
|| response.extra.get("needs_service_connection") == Some(&json!(true))
{
return Err(bad(
"Completed protocol event contains an incomplete runtime response",
));
}
let active = response
.agent
.get("active_agent")
.and_then(Value::as_str)
.unwrap_or(&agent.name)
.to_owned();
let owner =
crate::agent::find_agent(agent, &active).ok_or_else(|| bad("Unknown active Agent"))?;
let context = crate::AgentContext {
user_id: None,
session_id: session_id.into(),
agent_name: owner.name.clone(),
metadata: owner.metadata.clone(),
};
let output = crate::agent::validate_output(owner, response.output.clone(), &context).await?;
Ok(Some(crate::RunResult {
output,
last_agent: response
.agent
.get("last_agent")
.and_then(Value::as_str)
.unwrap_or(&active)
.into(),
active_agent: active,
agent_runs: response
.agent
.get("runs")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|v| serde_json::from_value(v.clone()).ok())
.collect(),
usage: response.usage.clone(),
routing: response.routing.clone(),
trace_id: response
.agent
.get("trace_id")
.and_then(Value::as_str)
.map(str::to_owned),
a2a_events: Vec::new(),
response,
}))
}
#[async_trait]
impl crate::AgentProtocol for B2A {
fn name(&self) -> &str {
"b2a"
}
fn accepts(&self, input: &Value) -> bool {
input["protocol"] == "b2a"
|| (input.get("protocol").is_none()
&& input.is_object()
&& ["signal_id", "samples", "recording_id", "neural_data"]
.iter()
.any(|key| input.get(key).is_some()))
}
async fn capabilities(&self) -> Result<Value> {
Ok(
json!({"input":["message"],"output":self.output_media_types,"output_profile":self.output_profile}),
)
}
async fn connect(
&self,
agent: &Agent,
user_id: &str,
session_id: &str,
) -> Result<Box<dyn crate::ProtocolSession>> {
Ok(Box::new(
B2ARunner::open(agent, self.clone(), user_id, session_id).await?,
))
}
async fn run(
&self,
agent: &Agent,
input: crate::Input,
user_id: &str,
session_id: &str,
) -> Result<crate::RunResult> {
let signal = match input {
crate::Input::Message(v) if v.is_object() => v,
_ => return Err(bad("Signal must be a JSON object")),
};
let mut session = B2ARunner::open(agent, self.clone(), user_id, session_id).await?;
let outcome = tokio::time::timeout(Duration::from_millis(agent.timeout_ms), async {
session.send_signal(&signal).await?;
while let Some(event) = session.next_event().await? {
if event.event_type == "feedback" {
if let Some(mut result) = session.last_result.take() {
result.response.extra.insert(
"protocol_feedback".into(),
serde_json::to_value(&event.feedback)
.map_err(|e| Error::Protocol(e.to_string()))?,
);
return Ok(result);
}
}
if ["feedback", "signal.status", "error", "session.closed"]
.contains(&event.event_type.as_str())
{
return Err(Error::Protocol(format!(
"B2A run did not complete: {}",
event.data
)));
}
}
Err(bad("B2A session closed before a response"))
})
.await
.map_err(|_| Error::Timeout(agent.timeout_ms))
.and_then(|v| v);
let closed = session.close().await;
match outcome {
Err(error) => Err(error),
Ok(result) => {
closed?;
Ok(result)
}
}
}
}
#[async_trait]
impl crate::ProtocolSession for B2AConnection {
fn supports_feedback(&self) -> bool {
true
}
fn supports_delivery(&self) -> bool {
true
}
fn result(&self) -> Option<crate::RunResult> {
self.last_result.clone()
}
async fn deliver(&mut self, input: &Value) -> Result<()> {
let message = B2AMessage::from_value(input.clone())?;
self.active().await?;
if message.source == "agent" {
let media: Vec<&str> = self
.config
.output_media_types
.iter()
.map(String::as_str)
.collect();
let feedback = self
.config
.provider
.encode(
input,
&self.config.output_profile,
&self.snapshot.context,
&media,
)
.await?;
if feedback.profile != self.config.output_profile
|| !self
.config
.output_media_types
.contains(&feedback.media_type)
{
return Err(bad("Encoder output does not match the interface"));
}
self.queue.push_back(B2ASessionEvent {
event_type: "feedback".into(),
data: input.clone(),
response_id: Some(message.message_id.clone()),
feedback: Some(feedback),
});
return Ok(());
}
let message = message.bind(
&self.protocol_session_id,
self.snapshot.next_sequence,
self.snapshot.context_revision,
self.config.execute,
)?;
self.send(message).await
}
async fn deliver_feedback(&mut self, original: &Value) -> Result<()> {
let mut content = original["payload"]["content"]
.as_array()
.cloned()
.unwrap_or_default();
if content.is_empty() {
content.push(json!({"type":"protocol:feedback","data":original["payload"]}));
}
let mut message = B2AMessage::multimodal("agent", content)?;
message.payload["source_protocol"] = original["protocol"].clone();
message.payload["correlation_id"] = original["correlation_id"].clone();
<Self as crate::ProtocolSession>::deliver(
self,
&serde_json::to_value(message).map_err(|e| bad(&e.to_string()))?,
)
.await
}
async fn poll_event(&mut self) -> Result<Option<crate::RunEvent>> {
if self.queue.is_empty() && !self.closed {
if self.stream.is_some() {
self.receive_stream().await?;
} else {
self.poll().await?;
}
}
if self.queue.is_empty() {
return Ok(None);
}
<Self as crate::ProtocolSession>::next_event(self).await
}
async fn send(&mut self, input: &Value) -> Result<()> {
if input["protocol"] == "b2a" {
<Self as crate::ProtocolSession>::deliver(self, input).await
} else {
self.send_signal(input).await
}
}
async fn next_event(&mut self) -> Result<Option<crate::RunEvent>> {
Ok(B2AConnection::next_event(self).await?.map(|event| {
let mut data = event.data.as_object().cloned().unwrap_or_default();
if let Some(feedback) = event.feedback {
data.insert(
"feedback".into(),
serde_json::to_value(feedback).expect("feedback is JSON"),
);
}
if let Some(id) = event.response_id {
data.insert("response_id".into(), json!(id));
}
crate::RunEvent {
event_type: event.event_type,
delta: None,
output: self
.last_result
.as_ref()
.map(|r| r.output.clone())
.unwrap_or(Value::Null),
data,
}
}))
}
async fn close(&mut self) -> Result<()> {
B2AConnection::close(self).await
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}