use crate::{Agent, Error, Input, Result, RunEvent, RunResult};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::{
any::Any,
collections::{HashMap, HashSet, VecDeque},
sync::Arc,
time::Duration,
};
use tokio::sync::{mpsc, oneshot};
#[async_trait]
pub trait ProtocolSession: Send {
async fn send(&mut self, input: &Value) -> Result<()>;
async fn next_event(&mut self) -> Result<Option<RunEvent>>;
async fn close(&mut self) -> Result<()>;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn supports_delivery(&self) -> bool {
false
}
async fn deliver(&mut self, _message: &Value) -> Result<()> {
Err(Error::Validation(
"Protocol does not support canonical delivery".into(),
))
}
fn supports_feedback(&self) -> bool {
false
}
async fn deliver_feedback(&mut self, _message: &Value) -> Result<()> {
Err(Error::Validation(
"Protocol does not support feedback delivery".into(),
))
}
async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
self.next_event().await
}
fn result(&self) -> Option<RunResult> {
None
}
}
#[async_trait]
pub trait AgentProtocol: Any + Send + Sync {
fn name(&self) -> &str;
fn accepts(&self, input: &Value) -> bool {
input["protocol"].as_str() == Some(self.name())
}
async fn capabilities(&self) -> Result<Value> {
Ok(json!({}))
}
async fn connect(
&self,
agent: &Agent,
user_id: &str,
session_id: &str,
) -> Result<Box<dyn ProtocolSession>>;
async fn run(
&self,
agent: &Agent,
input: Input,
user_id: &str,
session_id: &str,
) -> Result<RunResult>;
}
pub(crate) fn select(agent: &Agent, name: Option<&str>) -> Result<Option<Arc<dyn AgentProtocol>>> {
let mut protocols = agent.protocols.clone();
if let Some(config) = &agent.b2a {
protocols.push(Arc::new(config.clone()));
}
let mut names = HashSet::new();
for protocol in &protocols {
if protocol.name().trim().is_empty() || !names.insert(protocol.name().to_owned()) {
return Err(Error::Validation(
"Protocols must have nonempty, unique names".into(),
));
}
}
if let Some(name) = name {
return protocols
.into_iter()
.find(|p| p.name() == name)
.map(Some)
.ok_or_else(|| Error::Validation(format!("No configured protocol named {name}")));
}
if protocols.len() > 1 {
return Ok(Some(Arc::new(Coordinator { protocols })));
}
Ok(protocols.into_iter().next())
}
struct Coordinator {
protocols: Vec<Arc<dyn AgentProtocol>>,
}
#[async_trait]
impl AgentProtocol for Coordinator {
fn name(&self) -> &str {
"coordinated"
}
async fn connect(
&self,
agent: &Agent,
user_id: &str,
session_id: &str,
) -> Result<Box<dyn ProtocolSession>> {
Ok(Box::new(
CoordinatedSession::open(agent, &self.protocols, user_id, session_id).await?,
))
}
async fn run(
&self,
agent: &Agent,
input: Input,
user_id: &str,
session_id: &str,
) -> Result<RunResult> {
let input = serde_json::to_value(input).map_err(|e| Error::Validation(e.to_string()))?;
let mut session =
CoordinatedSession::open(agent, &self.protocols, user_id, session_id).await?;
let outcome = async {
session.send(&input).await?;
while let Some(event) = session.next_event().await? {
if event.event_type == "feedback" {
if let Some(message) = event.data.get("message") {
if message["payload"]["kind"] == "feedback"
&& message["payload"]["status"] != "succeeded"
{
return Err(Error::Protocol(format!(
"Protocol action outcome: {}",
message["payload"]["status"]
)));
}
}
}
if event.event_type == "exchange.completed"
&& event
.data
.get("action_status")
.and_then(Value::as_str)
.is_some_and(|s| s != "succeeded")
{
return Err(Error::Protocol(format!(
"Protocol action outcome: {}",
event.data["action_status"]
)));
}
if event.event_type == "protocol.route.failed" {
return Err(Error::Protocol(format!(
"Protocol route failed: {}",
Value::Object(event.data)
)));
}
if let Some(error) = &session.route_failure {
return Err(Error::Protocol(error.clone()));
}
if matches!(
event.event_type.as_str(),
"feedback" | "exchange.completed" | "protocol.route.completed"
) && session.pending.is_empty()
{
if let Some(result) = session.result() {
return Ok(result);
}
}
}
Err(Error::Protocol(
"Coordinated session closed before completion".into(),
))
}
.await;
let closed = session.close().await;
match outcome {
Ok(value) => {
closed?;
Ok(value)
}
Err(error) => Err(error),
}
}
}
enum Command {
Feedback(Value, oneshot::Sender<Result<()>>),
Send(Value, bool, oneshot::Sender<Result<()>>),
Close(oneshot::Sender<Result<()>>),
}
struct ChildEvent {
name: String,
event: Result<RunEvent>,
result: Option<RunResult>,
}
#[derive(Clone)]
pub struct ProtocolConnection {
commands: mpsc::Sender<Command>,
}
impl ProtocolConnection {
pub async fn send(&self, input: &Value) -> Result<()> {
self.call(input, false).await
}
pub async fn deliver_feedback(&self, message: &Value) -> Result<()> {
let (tx, rx) = oneshot::channel();
self.commands
.send(Command::Feedback(message.clone(), tx))
.await
.map_err(|_| Error::Protocol("Protocol session stopped".into()))?;
rx.await
.map_err(|_| Error::Protocol("Protocol session stopped".into()))?
}
pub async fn deliver(&self, message: &Value) -> Result<()> {
self.call(message, true).await
}
async fn call(&self, value: &Value, canonical: bool) -> Result<()> {
let (tx, rx) = oneshot::channel();
self.commands
.send(Command::Send(value.clone(), canonical, tx))
.await
.map_err(|_| Error::Protocol("Protocol session stopped".into()))?;
rx.await
.map_err(|_| Error::Protocol("Protocol session stopped".into()))?
}
}
#[derive(Clone)]
struct PendingRoute {
origin: String,
target: String,
route_id: String,
hops: u64,
}
pub struct CoordinatedSession {
pub session_id: String,
children: HashMap<String, ProtocolConnection>,
configurations: Vec<Arc<dyn AgentProtocol>>,
tasks: Vec<tokio::task::JoinHandle<()>>,
events: mpsc::Receiver<ChildEvent>,
queue: VecDeque<RunEvent>,
seen: HashSet<String>,
pending: HashMap<String, PendingRoute>,
last_result: Option<RunResult>,
route_failure: Option<String>,
closed: bool,
}
impl CoordinatedSession {
async fn open(
agent: &Agent,
protocols: &[Arc<dyn AgentProtocol>],
user_id: &str,
session_id: &str,
) -> Result<Self> {
let mut configured = agent.clone();
let mut declarations = Vec::new();
for protocol in protocols {
declarations.push(
json!({"protocol":protocol.name(),"capabilities":protocol.capabilities().await?}),
);
}
configured
.metadata
.insert("_marona_protocol_capabilities".into(), json!(declarations));
let mut opened = Vec::<(String, Box<dyn ProtocolSession>)>::new();
for protocol in protocols {
match protocol.connect(&configured, user_id, session_id).await {
Ok(mut child) => {
if !child.supports_delivery() || !child.supports_feedback() {
let _ = child.close().await;
for (_, mut previous) in opened {
let _ = previous.close().await;
}
return Err(Error::Validation(format!("Protocol {} must implement canonical delivery and bounded event reads for coordination",protocol.name())));
}
opened.push((protocol.name().to_owned(), child));
}
Err(error) => {
for (_, mut previous) in opened {
let _ = previous.close().await;
}
return Err(error);
}
}
}
let (tx, events) = mpsc::channel(128);
let mut children = HashMap::new();
let mut tasks = Vec::new();
for (name, mut child) in opened {
let (commands, mut rx) = mpsc::channel(32);
children.insert(name.clone(), ProtocolConnection { commands });
let tx = tx.clone();
tasks.push(tokio::spawn(async move {
loop {
match rx.try_recv() {
Ok(Command::Feedback(value, reply)) => {
let _ = reply.send(child.deliver_feedback(&value).await);
}
Ok(Command::Send(value, canonical, reply)) => {
let result = if canonical {
child.deliver(&value).await
} else {
child.send(&value).await
};
let _ = reply.send(result);
}
Ok(Command::Close(reply)) => {
let _ = reply.send(child.close().await);
return;
}
Err(mpsc::error::TryRecvError::Disconnected) => break,
Err(mpsc::error::TryRecvError::Empty) => match child.poll_event().await {
Ok(Some(event)) => {
if tx
.send(ChildEvent {
name: name.clone(),
event: Ok(event),
result: child.result(),
})
.await
.is_err()
{
break;
}
}
Ok(None) => tokio::time::sleep(Duration::from_millis(10)).await,
Err(error) => {
let _ = tx
.send(ChildEvent {
name: name.clone(),
event: Err(error),
result: None,
})
.await;
break;
}
},
}
}
let _ = child.close().await;
}));
}
Ok(Self {
session_id: session_id.into(),
children,
configurations: protocols.to_vec(),
tasks,
events,
queue: VecDeque::new(),
seen: HashSet::new(),
pending: HashMap::new(),
last_result: None,
route_failure: None,
closed: false,
})
}
pub fn protocol(&self, name: &str) -> Result<ProtocolConnection> {
self.children
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("No attached protocol named {name}")))
}
pub async fn send_to(&mut self, input: &Value, protocol: Option<&str>) -> Result<()> {
let name = if let Some(name) = protocol {
name.to_owned()
} else if let Some(name) = input["protocol"].as_str() {
name.to_owned()
} else {
let candidates: Vec<_> = self
.configurations
.iter()
.filter(|p| p.accepts(input))
.collect();
if candidates.len() != 1 {
return Err(Error::Validation(
"Input is ambiguous; provide a canonical protocol or explicit selection".into(),
));
}
candidates[0].name().to_owned()
};
self.protocol(&name)?.send(input).await
}
pub async fn send_signal(&mut self, signal: &Value) -> Result<()> {
self.send_to(signal, Some("b2a")).await
}
async fn route(&mut self, source: &str, data: &Value) -> Result<()> {
let route_id = data["route_id"]
.as_str()
.filter(|v| !v.is_empty())
.ok_or_else(|| Error::Validation("Route ID is required".into()))?
.to_owned();
if self.seen.contains(&route_id) {
return Ok(());
}
if self.seen.len() >= 4096 {
return Err(Error::Validation(
"Protocol route history capacity reached; open a new session".into(),
));
}
self.seen.insert(route_id.clone());
let outcome = async {
let target = data["target_protocol"]
.as_str()
.ok_or_else(|| Error::Validation("Missing route target".into()))?;
let hops=match data.get("hops"){None=>0,Some(v)=>v.as_u64().ok_or_else(||Error::Validation("Malformed route hop count".into()))?};
let mut visited=match data.get("visited"){None=>Vec::new(),Some(Value::Array(v)) if v.len()<=9 && v.iter().all(|p|p.as_str().is_some_and(|s|!s.is_empty()))=>v.clone(),_=>return Err(Error::Validation("Malformed route lineage".into()))};
if visited.contains(&json!(target)){return Err(Error::Validation("Protocol route lineage loop".into()));}
if !visited.contains(&json!(source)){visited.push(json!(source));}visited.push(json!(target));
if hops >= 8 || target == source {
return Err(Error::Validation("Protocol route loop or hop limit".into()));
}
let mut message = data["message"].clone();
if message["protocol"] != target
|| message["type"] != "message"
|| message["source"] != "agent"
{
return Err(Error::Validation(
"Route must contain a canonical agent message for its target".into(),
));
}
let correlation = data["correlation_id"]
.as_str()
.or_else(|| message["message_id"].as_str())
.ok_or_else(|| Error::Validation("Route correlation is required".into()))?
.to_owned();
message["correlation_id"] = json!(correlation);
message["payload"]["source_protocol"] = json!(source);
message["payload"]["route_id"] = json!(route_id);
message["payload"]["hops"] = json!(hops + 1);
message["payload"]["coordination"]=json!({"route_id":route_id,"origin_protocol":source,"hops":hops+1,"visited":visited});
let pending = PendingRoute {
origin: source.into(),
target:target.into(),
route_id: route_id.clone(),
hops: hops + 1,
};
let mut identifiers = vec![correlation.clone()];
if let Some(id) = message["message_id"].as_str() {
identifiers.push(id.to_owned());
}
if let Some(id) = message["payload"]["action_id"].as_str() {
identifiers.push(id.to_owned());
}
for id in identifiers {
self.pending.insert(id, pending.clone());
}
if let Err(error) = self.protocol(target)?.deliver(&message).await {
self.pending.retain(|_, value| value.route_id != route_id);
return Err(error);
}
Ok(())
}
.await;
if let Err(error) = outcome {
self.route_failure = Some(error.to_string());
self.queue.push_back(route_event(
"protocol.route.failed",
&route_id,
source,
Some(error.to_string()),
));
}
Ok(())
}
async fn handle(&mut self, item: ChildEvent) -> Result<RunEvent> {
let mut event = item.event?;
if item.result.is_some() {
self.last_result = item.result;
}
if event.event_type == "protocol.route" {
self.route(&item.name, &Value::Object(event.data.clone()))
.await?;
} else {
let envelope = event
.data
.get("message")
.cloned()
.unwrap_or_else(|| Value::Object(event.data.clone()));
for route in envelope["payload"]["routes"]
.as_array()
.into_iter()
.flatten()
{
self.route(&item.name, route).await?;
}
if event.event_type == "feedback" || envelope["payload"]["kind"] == "feedback" {
let identifiers = [
envelope["correlation_id"].as_str(),
envelope["message_id"].as_str(),
envelope["payload"]["action_id"].as_str(),
];
let pending = identifiers
.into_iter()
.flatten()
.find_map(|id| self.pending.get(id).cloned());
if let Some(pending) = pending {
if item.name != pending.target {
return Err(Error::Validation(
"Protocol feedback came from a different route target".into(),
));
}
let status = envelope["payload"]["status"]
.as_str()
.unwrap_or("succeeded");
let terminal = !["accepted", "executing"].contains(&status);
let outcome = if pending.hops >= 8 {
Err(Error::Validation("Protocol feedback hop limit".into()))
} else {
self.protocol(&pending.origin)?
.deliver_feedback(&envelope)
.await
};
if outcome.is_err() || (terminal && status != "succeeded") {
self.route_failure = Some(
outcome
.as_ref()
.err()
.map(|e| e.to_string())
.unwrap_or_else(|| format!("Protocol outcome: {status}")),
);
}
if terminal || outcome.is_err() {
self.pending
.retain(|_, value| value.route_id != pending.route_id);
self.queue.push_back(route_event(
if outcome.is_ok() && status == "succeeded" {
"protocol.route.completed"
} else {
"protocol.route.failed"
},
&pending.route_id,
&pending.origin,
outcome.err().map(|e| e.to_string()).or_else(|| {
if status != "succeeded" {
Some(format!("Protocol outcome: {status}"))
} else {
None
}
}),
));
}
}
}
}
event.data.insert("protocol".into(), json!(item.name));
if !event.data.contains_key("source") {
event.data.insert("source".into(), json!(item.name));
}
Ok(event)
}
}
fn route_event(kind: &str, id: &str, target: &str, error: Option<String>) -> RunEvent {
RunEvent {
event_type: kind.into(),
delta: None,
output: Value::Null,
data: json!({"route_id":id,"target_protocol":target,"error":error})
.as_object()
.unwrap()
.clone(),
}
}
#[async_trait]
impl ProtocolSession for CoordinatedSession {
fn supports_delivery(&self) -> bool {
true
}
fn result(&self) -> Option<RunResult> {
self.last_result.clone()
}
async fn send(&mut self, input: &Value) -> Result<()> {
self.send_to(input, None).await
}
async fn deliver(&mut self, message: &Value) -> Result<()> {
let name = message["protocol"]
.as_str()
.ok_or_else(|| Error::Validation("Missing target protocol".into()))?;
self.protocol(name)?.deliver(message).await
}
async fn next_event(&mut self) -> Result<Option<RunEvent>> {
if let Some(event) = self.queue.pop_front() {
return Ok(Some(event));
}
match self.events.recv().await {
Some(item) => Ok(Some(self.handle(item).await?)),
None => Ok(None),
}
}
async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
if let Some(event) = self.queue.pop_front() {
return Ok(Some(event));
}
match self.events.try_recv() {
Ok(item) => Ok(Some(self.handle(item).await?)),
Err(_) => Ok(None),
}
}
async fn close(&mut self) -> Result<()> {
if self.closed {
return Ok(());
}
self.closed = true;
let mut acknowledgements = Vec::new();
for child in self.children.values() {
let (tx, rx) = oneshot::channel();
if child.commands.send(Command::Close(tx)).await.is_ok() {
acknowledgements.push(rx);
}
}
let closing = async {
let mut error = None;
for ack in acknowledgements {
if let Ok(Err(value)) = ack.await {
error.get_or_insert(value);
}
}
match error {
Some(error) => Err(error),
None => Ok(()),
}
};
tokio::pin!(closing);
let result = loop {
tokio::select! {result=&mut closing=>break result,_=self.events.recv()=>{}}
};
for task in self.tasks.drain(..) {
let _ = task.await;
}
result
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl Drop for CoordinatedSession {
fn drop(&mut self) {
for task in self.tasks.drain(..) {
task.abort();
}
}
}