use std::collections::HashMap;
use std::sync::Arc;
use chrono::{DateTime, Utc};
use serde_json::Value;
use super::continuation::A2aContinuations;
use super::outcome::call_error_value;
use super::source::Transport;
use crate::tenant::TenantContext;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct A2aRoute {
pub agent_id: String,
pub base_url: String,
pub auth_header_name: Option<String>,
pub auth_team: Option<String>,
pub requires_auth: bool,
}
impl A2aRoute {
pub fn unauthenticated(agent_id: impl Into<String>, base_url: impl Into<String>) -> Self {
Self {
agent_id: agent_id.into(),
base_url: base_url.into(),
auth_header_name: None,
auth_team: None,
requires_auth: false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct A2aToolEntry {
pub description: String,
}
#[derive(Clone, Debug, Default)]
pub struct A2aToolCatalog {
pub(super) tools: HashMap<String, A2aToolEntry>,
pub(super) errors: HashMap<String, String>,
pub(super) caller: Option<Arc<Transport>>,
}
impl A2aToolCatalog {
#[cfg(test)]
pub(crate) fn for_tests(entries: &[(&str, &str)], down: &[&str]) -> Self {
Self {
tools: entries
.iter()
.map(|(id, description)| {
(
(*id).to_string(),
A2aToolEntry {
description: (*description).to_string(),
},
)
})
.collect(),
errors: down
.iter()
.map(|id| ((*id).to_string(), "card unreachable (test)".to_string()))
.collect(),
caller: None,
}
}
pub fn is_configured(&self, agent_id: &str) -> bool {
self.tools.contains_key(agent_id) || self.errors.contains_key(agent_id)
}
pub fn tool_entry(&self, agent_id: &str) -> Option<&A2aToolEntry> {
self.tools.get(agent_id)
}
pub fn error_for(&self, agent_id: &str) -> Option<&str> {
self.errors.get(agent_id).map(String::as_str)
}
pub async fn dispatch(&self, agent_id: &str, args: &Value) -> Value {
let mut scratch = A2aContinuations::default();
self.dispatch_in_conversation(
agent_id,
args,
&TenantContext::new("", ""),
&mut scratch,
Utc::now(),
)
.await
}
pub async fn dispatch_in_conversation(
&self,
agent_id: &str,
args: &Value,
tenant: &TenantContext,
continuations: &mut A2aContinuations,
now: DateTime<Utc>,
) -> Value {
let caller = self
.caller
.as_ref()
.filter(|_| self.is_configured(agent_id));
let Some(caller) = caller else {
let reason = self
.error_for(agent_id)
.map(|cause| format!("a2a agent {agent_id} is unavailable: {cause}"))
.unwrap_or_else(|| format!("unknown a2a agent '{agent_id}'"));
return call_error_value(agent_id, &reason);
};
let prior = continuations.resume(tenant, agent_id, now);
match caller
.send(agent_id, &args_to_text(args), prior.as_ref())
.await
{
Ok(reply) => {
let context_id = reply
.context_id
.or_else(|| prior.as_ref().map(|c| c.context_id.clone()));
match context_id {
Some(context_id) => {
continuations.remember(tenant, agent_id, context_id, reply.task_id, now);
}
None => continuations.forget(agent_id),
}
reply.outcome.to_value(agent_id)
}
Err(reason) => {
tracing::warn!(agent = %agent_id, error = %reason, "a2a tool call failed");
call_error_value(agent_id, &reason)
}
}
}
}
fn args_to_text(args: &Value) -> String {
match args {
Value::String(text) => text.clone(),
Value::Object(map) => match map.get("message") {
Some(Value::String(text)) => text.clone(),
_ => args.to_string(),
},
_ => args.to_string(),
}
}
#[cfg(test)]
mod args_tests {
use super::args_to_text;
use serde_json::json;
#[test]
fn a_bare_string_is_sent_as_is() {
assert_eq!(args_to_text(&json!("hello")), "hello");
}
#[test]
fn an_object_with_a_message_field_sends_that_field() {
assert_eq!(
args_to_text(&json!({ "message": "hello", "x": 1 })),
"hello"
);
}
#[test]
fn anything_else_is_sent_as_json_so_no_argument_is_dropped() {
assert_eq!(
args_to_text(&json!({ "city": "Jakarta" })),
r#"{"city":"Jakarta"}"#
);
assert_eq!(args_to_text(&json!({ "message": 42 })), r#"{"message":42}"#);
}
}