use crate::{Agent, Error, Input, Result, RunEvent, RunResult};
use async_trait::async_trait;
use serde_json::Value;
use std::{any::Any, collections::HashSet, sync::Arc};
#[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;
}
#[async_trait]
pub trait AgentProtocol: Any + Send + Sync {
fn name(&self) -> &str;
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 Err(Error::Validation(
"Multiple protocols are configured; select protocol by name".into(),
));
}
Ok(protocols.into_iter().next())
}