use std::{collections::BTreeSet, sync::Arc};
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use uuid::Uuid;
use crate::{core::Core, Agent, AgentTool, Error, Result};
pub const B2A_PROTOCOL_VERSION: &str = "0.1";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct B2AIntent {
pub content: Value,
pub media_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub confidence: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub decoder: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provenance: Option<Value>,
}
impl B2AIntent {
pub fn new(content: impl Into<Value>) -> Result<Self> {
let content = content.into();
let value = Self {
media_type: if content.is_string() {
"text/plain"
} else {
"application/json"
}
.into(),
content,
confidence: None,
decoder: None,
provenance: None,
};
value.validate()?;
Ok(value)
}
pub fn with_confidence(mut self, confidence: f64) -> Result<Self> {
self.confidence = Some(confidence);
self.validate()?;
Ok(self)
}
pub fn validate(&self) -> Result<()> {
if !self.content.is_object()
&& !self
.content
.as_str()
.is_some_and(|value| !value.trim().is_empty())
{
return invalid("intent content must be a JSON object or nonempty string");
}
if !["application/json", "text/plain"].contains(&self.media_type.as_str()) {
return invalid("intent media_type must be application/json or text/plain");
}
if self.media_type == "text/plain" && !self.content.is_string() {
return invalid("text/plain intent content must be a string");
}
if self
.confidence
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
{
return invalid("confidence must be finite and between 0 and 1");
}
for (name, value) in [("decoder", &self.decoder), ("provenance", &self.provenance)] {
if value.as_ref().is_some_and(|value| !value.is_object()) {
return invalid(&format!("{name} must be a JSON object"));
}
}
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct B2AMessage {
pub protocol: String,
pub version: String,
pub message_id: String,
pub session_id: String,
pub sequence: u64,
#[serde(rename = "type")]
pub message_type: String,
pub timestamp: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
pub payload: Value,
}
impl B2AMessage {
pub fn new(
session_id: impl Into<String>,
sequence: u64,
message_type: impl Into<String>,
payload: Value,
) -> Result<Self> {
let value = Self {
protocol: "b2a".into(),
version: B2A_PROTOCOL_VERSION.into(),
message_id: Uuid::new_v4().to_string(),
session_id: session_id.into(),
sequence,
message_type: message_type.into(),
timestamp: OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|error| Error::Validation(error.to_string()))?,
expires_at: None,
payload,
};
value.validate()?;
Ok(value)
}
pub fn intent(
session_id: impl Into<String>,
sequence: u64,
intent: B2AIntent,
context_revision: u64,
execute: bool,
) -> Result<Self> {
intent.validate()?;
Self::new(
session_id,
sequence,
"intent.submit",
json!({
"intent": intent,
"context_revision": context_revision,
"execute": execute,
}),
)
}
pub fn clarification(
session_id: impl Into<String>,
sequence: u64,
intent: B2AIntent,
context_revision: u64,
execute: bool,
) -> Result<Self> {
let mut message = Self::intent(session_id, sequence, intent, context_revision, execute)?;
message.message_type = "intent.clarify".into();
Ok(message)
}
pub fn validate(&self) -> Result<()> {
if self.protocol != "b2a" || self.version != B2A_PROTOCOL_VERSION {
return invalid("this client supports B2A version 0.1");
}
nonempty(&self.message_id, "message_id")?;
nonempty(&self.session_id, "session_id")?;
nonempty(&self.message_type, "type")?;
if self.sequence == 0 {
return invalid("sequence must be at least one");
}
if !self.payload.is_object() {
return invalid("payload must be a JSON object");
}
validate_timestamp(&self.timestamp)?;
if let Some(expires_at) = &self.expires_at {
validate_timestamp(expires_at)?;
}
if ["intent.submit", "intent.clarify"].contains(&self.message_type.as_str()) {
let intent = self
.payload
.get("intent")
.ok_or_else(|| Error::Validation("B2A intent payload is missing intent".into()))?;
let intent: B2AIntent = serde_json::from_value(intent.clone())
.map_err(|error| Error::Validation(format!("invalid B2A intent: {error}")))?;
intent.validate()?;
if self
.payload
.get("context_revision")
.is_some_and(|value| value.as_u64().is_none())
{
return invalid("context_revision must be a nonnegative integer");
}
if self
.payload
.get("execute")
.is_some_and(|value| !value.is_boolean())
{
return invalid("execute must be a boolean");
}
}
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AOpenSession {
#[serde(skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
pub protocol_version: String,
pub user_id: String,
pub device_id: String,
pub consent: Value,
pub capabilities: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub agent: Option<Value>,
pub context: Value,
pub ttl_seconds: u64,
}
impl B2AOpenSession {
pub fn new(
user_id: impl Into<String>,
device_id: impl Into<String>,
consent: Value,
capabilities: Value,
) -> Self {
Self {
protocol_version: B2A_PROTOCOL_VERSION.into(),
conversation_id: None,
user_id: user_id.into(),
device_id: device_id.into(),
consent,
capabilities,
agent: None,
context: json!({}),
ttl_seconds: 3600,
}
}
pub fn with_agent(mut self, agent: &Agent) -> Result<Self> {
self.agent = Some(b2a_agent_config(agent)?);
Ok(self)
}
fn validate(&self) -> Result<()> {
if self.protocol_version != B2A_PROTOCOL_VERSION {
return invalid("this client supports B2A version 0.1");
}
nonempty(&self.user_id, "user_id")?;
nonempty(&self.device_id, "device_id")?;
if self.ttl_seconds == 0 {
return invalid("ttl_seconds must be greater than zero");
}
for (name, value) in [
("consent", &self.consent),
("capabilities", &self.capabilities),
("context", &self.context),
] {
if !value.is_object() {
return invalid(&format!("{name} must be a JSON object"));
}
}
if self.agent.as_ref().is_some_and(|value| !value.is_object()) {
return invalid("agent must be a JSON object");
}
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2ASession {
pub protocol: String,
pub version: String,
pub session_id: String,
pub state: String,
pub user_id: String,
pub device_id: String,
pub capabilities: Value,
pub consent: Value,
pub context: Value,
pub context_revision: u64,
pub next_sequence: u64,
pub expires_at: String,
pub created_at: String,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEvent {
pub protocol: String,
pub version: String,
pub event_id: String,
pub session_id: String,
pub sequence: u64,
#[serde(rename = "type")]
pub event_type: String,
#[serde(default)]
pub correlation_id: Option<String>,
pub timestamp: String,
pub payload: Value,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AAcknowledgment {
pub message_id: String,
pub status: String,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AExchange {
pub protocol: String,
pub version: String,
pub session_id: String,
pub ack: B2AAcknowledgment,
pub events: Vec<B2AEvent>,
pub session: B2ASession,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEventPage {
pub protocol: String,
pub version: String,
pub session_id: String,
pub events: Vec<B2AEvent>,
pub next_cursor: u64,
pub has_more: bool,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
pub type B2AEventStream = std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<Value>> + Send>>;
#[derive(Clone, Debug)]
pub struct B2AClient {
pub(crate) core: Arc<Core>,
}
impl B2AClient {
pub async fn capabilities(&self) -> Result<Value> {
self.core
.json(
&self.core.runtime_url,
Method::GET,
"/runtime/b2a/capabilities",
None,
)
.await
}
pub async fn open_session(&self, request: B2AOpenSession) -> Result<B2ASession> {
request.validate()?;
let body =
serde_json::to_value(request).map_err(|error| Error::Validation(error.to_string()))?;
self.core
.json(
&self.core.runtime_url,
Method::POST,
"/runtime/b2a/sessions",
Some(&body),
)
.await
}
pub async fn get_session(&self, session_id: &str) -> Result<B2ASession> {
self.core
.json(
&self.core.runtime_url,
Method::GET,
&session_path(session_id)?,
None,
)
.await
}
pub async fn close_session(&self, session_id: &str) -> Result<B2ASession> {
self.core
.json(
&self.core.runtime_url,
Method::DELETE,
&session_path(session_id)?,
None,
)
.await
}
pub async fn send_message(
&self,
session_id: &str,
message: &B2AMessage,
) -> Result<B2AExchange> {
message.validate()?;
if session_id != message.session_id {
return invalid("envelope session_id does not match the requested session");
}
let body =
serde_json::to_value(message).map_err(|error| Error::Validation(error.to_string()))?;
self.core
.json(
&self.core.runtime_url,
Method::POST,
&format!("{}/messages", session_path(session_id)?),
Some(&body),
)
.await
}
pub async fn stream_message(
&self,
session_id: &str,
message: &B2AMessage,
) -> Result<B2AEventStream> {
use futures_util::StreamExt;
message.validate()?;
if message.session_id != session_id {
return invalid("B2A stream session mismatch");
}
let response = self
.core
.stream_client
.post(format!(
"{}{}/messages/stream",
self.core.runtime_url,
session_path(session_id)?
))
.headers(self.core.headers.clone())
.bearer_auth(self.core.require_api_key()?)
.header("Accept", "text/event-stream")
.json(message)
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let body = self.core.response_body(response).await?;
return Err(Error::api(status, serde_json::from_slice(&body).ok()));
}
self.core.check_response(&response)?;
let core = self.core.clone();
let id = session_id.to_owned();
let mid = message.message_id.clone();
Ok(Box::pin(async_stream::try_stream! {
let mut source = response.bytes_stream();
let mut buffer = Vec::new();
let mut received = 0;
while let Some(chunk) = source.next().await {
let chunk = chunk?;
received = core.response_size(received, chunk.len())?;
buffer.extend_from_slice(&chunk);
while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
let line: Vec<u8> = buffer.drain(..=end).collect();
if !line.starts_with(b"data:") {continue;}
let event: Value = serde_json::from_slice(&line[5..]).map_err(|_| Error::Protocol("Invalid B2A stream JSON".into()))?;
if event["session_id"] != id || event["correlation_id"] != mid { Err(Error::Protocol("B2A stream identity mismatch".into()))?; }
if event["type"] == "exchange.completed" {
let exchange = &event["exchange"];
if exchange["protocol"] != "b2a" || exchange["version"] != "0.1" || exchange["session_id"] != id || exchange["session"]["session_id"] != id || exchange["ack"]["message_id"] != mid || !matches!(exchange["ack"]["status"].as_str(), Some("accepted" | "duplicate" | "processing")) {
Err(Error::Protocol("Invalid B2A exchange acknowledgment".into()))?;
}
}
yield event;
}
if buffer.len() > 1_048_576 { Err(Error::Protocol("B2A stream frame exceeds size limit".into()))?; }
}
if buffer.iter().any(|b| !b.is_ascii_whitespace()) { Err(Error::Protocol("Incomplete B2A stream frame".into()))?; }
}))
}
pub async fn events(&self, session_id: &str, after: u64, limit: u32) -> Result<B2AEventPage> {
if limit == 0 {
return invalid("event page limit must be greater than zero");
}
self.core
.json(
&self.core.runtime_url,
Method::GET,
&format!(
"{}/events?after={after}&limit={limit}",
session_path(session_id)?
),
None,
)
.await
}
}
fn session_path(id: &str) -> Result<String> {
nonempty(id, "session_id")?;
let encoded: String = url::form_urlencoded::byte_serialize(id.as_bytes()).collect();
Ok(format!("/runtime/b2a/sessions/{encoded}"))
}
fn nonempty(value: &str, name: &str) -> Result<()> {
if value.trim().is_empty() {
invalid(&format!("{name} must be nonempty"))
} else {
Ok(())
}
}
fn validate_timestamp(value: &str) -> Result<()> {
OffsetDateTime::parse(value, &Rfc3339)
.map(|_| ())
.map_err(|_| Error::Validation("B2A timestamps must use RFC3339 with a timezone".into()))
}
fn invalid<T>(message: &str) -> Result<T> {
Err(Error::Validation(format!("B2A {message}")))
}
pub fn b2a_agent_config(agent: &Agent) -> Result<Value> {
crate::agent::validate_graph(agent)?;
let mut apps = BTreeSet::new();
let mut skills = BTreeSet::new();
let mut all_apps = false;
let mut seen = BTreeSet::new();
fn visit(
agent: &Agent,
seen: &mut BTreeSet<String>,
apps: &mut BTreeSet<String>,
skills: &mut BTreeSet<String>,
all_apps: &mut bool,
) -> Result<()> {
if !seen.insert(agent.name.clone()) {
return Ok(());
}
if agent.hooks.is_some()
|| agent.instruction_provider.is_some()
|| !agent.input_guardrails.is_empty()
|| !agent.output_guardrails.is_empty()
|| !agent.peers.is_empty()
{
return invalid("native sessions cannot execute SDK callbacks, guardrails, dynamic instructions or SDK A2A peers");
}
if let Some(connection) = &agent.hub_tools {
*all_apps |= connection.unscoped;
if let Some(values) = connection.b2a_scope.get("apps").and_then(Value::as_array) {
apps.extend(values.iter().filter_map(Value::as_str).map(str::to_owned));
}
if let Some(values) = connection.b2a_scope.get("skills").and_then(Value::as_array) {
skills.extend(values.iter().filter_map(Value::as_str).map(str::to_owned));
}
}
for tool in &agent.tools {
match tool {
AgentTool::Function(_) => {
return invalid(
"native sessions require server-hosted tools, not local functions",
)
}
AgentTool::Delegation { agent, .. } => visit(agent, seen, apps, skills, all_apps)?,
}
}
for handoff in &agent.handoffs {
if handoff.input_filter.is_some() {
return invalid("native sessions cannot execute local handoff input filters");
}
visit(&handoff.agent, seen, apps, skills, all_apps)?;
}
Ok(())
}
visit(agent, &mut seen, &mut apps, &mut skills, &mut all_apps)?;
let mut result = json!({
"name": agent.name,
"instructions": agent.instructions,
"model": agent.model,
"tool_choice": agent.tool_choice,
"tools_enabled": agent.hub_tools.is_some() || !agent.tools.is_empty() || !agent.handoffs.is_empty(),
"max_turns": agent.max_turns,
"model_settings": agent.model_settings,
"multi_agent": crate::agent::graph_value(agent),
"connection_scope": {"all_apps": all_apps, "apps": apps, "skills": skills},
"output": crate::agent::output_request(agent),
});
if let Some(routing) = &agent.routing {
result["routing"] = json!(routing);
}
Ok(result)
}