use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use a2a::{
A2AError, Artifact, Message, Part, Role, StreamResponse, Task, TaskArtifactUpdateEvent, TaskId,
TaskState, TaskStatus, TaskStatusUpdateEvent, new_message_id,
};
use a2a_server::{AgentExecutor, ExecutorContext, ServiceParams};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use futures::StreamExt;
use futures::stream::{AbortHandle, Abortable, BoxStream};
use rig_agent::Agent;
use rig_agent::agent::MultiTurnStreamItem;
use rig_agent::completion::{PromptError, StructuredOutputError};
use rig_core::message::{AssistantContent, DocumentSourceKind, MimeType};
use rig_core::streaming::{Item, StreamEvent};
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use rig_memory::AsyncStore;
use rig_memory::recent::{Recent, TokenBudget, view};
use crate::history::{
DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
valid_context_id,
};
use crate::parts::user_message;
const RESPONSE_ARTIFACT: &str = "response";
pub const DEFAULT_MAX_CONCURRENT_TASKS: usize = 32;
pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
type Running = Arc<Mutex<HashMap<TaskId, AbortHandle>>>;
tokio::task_local! {
static ACTIVATED: Arc<[String]>;
}
#[must_use]
pub fn activated_extensions() -> Vec<String> {
ACTIVATED
.try_with(|activated| activated.to_vec())
.unwrap_or_default()
}
fn activated_from(params: &ServiceParams, declared: &[String]) -> Arc<[String]> {
let mut activated: Vec<String> = params
.get(crate::server::EXTENSIONS_HEADER.as_str())
.into_iter()
.flatten()
.flat_map(|value| value.split(','))
.map(str::trim)
.filter(|uri| declared.iter().any(|declared| declared == uri))
.map(str::to_owned)
.collect();
activated.sort_unstable();
activated.dedup();
activated.into()
}
type TypedAnswer = Arc<
dyn Fn(
Agent,
rig_core::message::Message,
Vec<rig_core::message::Message>,
) -> WasmBoxedFuture<
'static,
Result<(serde_json::Value, Vec<rig_core::message::Message>), String>,
> + Send
+ Sync,
>;
#[derive(Clone)]
pub struct A2aExecutor {
agent: Agent,
history: Arc<dyn HistoryStore>,
window: Arc<dyn Recent>,
running: Running,
slots: Arc<tokio::sync::Semaphore>,
max_run: Duration,
typed: Option<TypedAnswer>,
declared: Arc<[String]>,
}
impl A2aExecutor {
pub fn new(agent: Agent) -> Self {
Self {
agent,
history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
running: Arc::default(),
slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_TASKS)),
max_run: DEFAULT_MAX_RUN_DURATION,
typed: None,
declared: Arc::from(Vec::new()),
}
}
pub(crate) fn declaring(mut self, declared: Arc<[String]>) -> Self {
self.declared = declared;
self
}
#[must_use]
pub fn typed<T>(mut self) -> Self
where
T: schemars::JsonSchema
+ serde::de::DeserializeOwned
+ serde::Serialize
+ WasmCompatSend
+ WasmCompatSync
+ 'static,
{
self.typed = Some(Arc::new(|agent, prompt, history| {
Box::pin(async move {
let response = agent
.prompt_typed::<T>(prompt)
.history(history)
.retries(2)
.await
.map_err(|error| {
let reason = match &error {
StructuredOutputError::Prompt(prompt) => status_message(prompt),
_ => "not a structured answer",
};
tracing::warn!(
kind = "run_failed",
reason = reason,
"A2A typed task failed"
);
match &error {
StructuredOutputError::Prompt(prompt) => {
failure_message(prompt).into_owned()
}
_ => "The agent could not produce a structured answer.".to_owned(),
}
})?;
let value =
serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
Ok((value, response.messages))
})
}));
self
}
#[must_use]
pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
self
}
#[must_use]
pub fn max_run_duration(mut self, max: Duration) -> Self {
self.max_run = max;
self
}
#[must_use]
#[doc(alias = "max_sessions")]
pub fn max_contexts(mut self, max: usize) -> Self {
self.history = Arc::new(InMemory::new(max));
self
}
#[must_use]
pub fn history_store<S>(mut self, store: S) -> Self
where
S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
{
self.history = Arc::new(Persistent(store));
self
}
#[must_use]
pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
self.window = Arc::new(window);
self
}
}
impl AgentExecutor for A2aExecutor {
fn execute(
&self,
ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
let (handle, registration) = AbortHandle::new_pair();
lock(&self.running).insert(ctx.task_id.clone(), handle);
let registered = Registered {
running: Arc::clone(&self.running),
task_id: ctx.task_id.clone(),
};
let run = run(self.clone(), ctx, registered);
Abortable::new(run, registration).boxed()
}
fn cancel(&self, ctx: ExecutorContext) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
if let Some(handle) = lock(&self.running).remove(&ctx.task_id) {
handle.abort();
}
let ids = Ids {
task: ctx.task_id,
context: ctx.context_id,
};
futures::stream::iter([Ok(ids.status(TaskState::Canceled, None))]).boxed()
}
}
struct Registered {
running: Running,
task_id: TaskId,
}
impl Drop for Registered {
fn drop(&mut self) {
lock(&self.running).remove(&self.task_id);
}
}
fn run(
executor: A2aExecutor,
ctx: ExecutorContext,
registered: Registered,
) -> impl futures::Stream<Item = Result<StreamResponse, A2AError>> + Send + 'static {
async_stream::stream! {
let _registered = registered;
let activated = activated_from(&ctx.service_params, &executor.declared);
let ids = Ids {
task: ctx.task_id,
context: ctx.context_id,
};
let span = tracing::info_span!(
"a2a.task",
otel.kind = "server",
a2a.task_id = %ids.task,
a2a.context_id = %ids.context,
a2a.state = tracing::field::Empty,
);
#[cfg(feature = "otel")]
crate::otel::continue_trace(&span, &ctx.service_params, &ids.context);
let end = |state: &'static str| {
span.record("a2a.state", state);
};
let Some(message) = ctx.message else {
end("failed");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("No message to answer."))));
return;
};
let mut history = ctx
.stored_task
.and_then(|task| task.history)
.unwrap_or_default();
if history.last().map(|last| &last.message_id) != Some(&message.message_id) {
history.push(message.clone());
}
if !valid_context_id(&ids.context) {
let reason = ids.agent_message(
"contextId must be 1 to 128 ASCII letters, digits, `-` or `_`.",
);
end("rejected");
yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
return;
}
let prompt = match user_message(&message) {
Ok(prompt) => prompt,
Err(unsupported) => {
let reason = ids.agent_message(unsupported.to_string());
end("rejected");
yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
return;
}
};
let Ok(_slot) = Arc::clone(&executor.slots).try_acquire_owned() else {
let reason = ids.agent_message("The agent is busy; try again shortly.");
end("rejected_busy");
yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
return;
};
yield Ok(StreamResponse::Task(ids.task(TaskState::Working, None, history)));
let prior = match executor.history.load(&ids.context).await {
Ok(messages) => view(&messages, executor.window.as_ref())
.iter()
.map(|message| (**message).clone())
.collect::<Vec<_>>(),
Err(_) => {
tracing::warn!(parent: &span, kind = "store_error", "could not load the conversation");
end("failed");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The conversation could not be loaded."))));
return;
}
};
let deadline = tokio::time::Instant::now() + executor.max_run;
if let Some(typed) = &executor.typed {
let answer = ACTIVATED.scope(
Arc::clone(&activated),
tracing::Instrument::instrument(typed(executor.agent.clone(), prompt, prior), span.clone()),
);
match tokio::time::timeout_at(deadline, answer).await {
Err(_) => {
end("failed_timeout");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
}
Ok(Err(reason)) => {
end("failed");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(reason))));
}
Ok(Ok((value, messages))) => {
if executor.history.append(&ids.context, messages).await.is_err() {
tracing::warn!(parent: &span, kind = "store_error", "could not save the conversation");
}
let mut data = Part::text("");
data.content = a2a::PartContent::Data(value);
data.media_type = Some("application/json".to_owned());
end("completed");
yield Ok(ids.artifact(vec![data], false, true));
yield Ok(ids.status(TaskState::Completed, None));
}
}
return;
}
let mut stream = span.in_scope(|| executor.agent.prompt(prompt).history(prior).stream());
let mut streamed = false;
loop {
let next = ACTIVATED.scope(Arc::clone(&activated), stream.next());
let item = match tokio::time::timeout_at(deadline, next).await {
Ok(Some(item)) => item,
Ok(None) => break,
Err(_) => {
tracing::warn!(parent: &span, max = ?executor.max_run, "A2A run took too long");
end("failed_timeout");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
return;
}
};
match item {
Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
text,
..
}))) => {
yield Ok(ids.chunk(text, streamed, false));
streamed = true;
}
Ok(MultiTurnStreamItem::FinalResponse(response)) => {
if executor.history.append(&ids.context, response.messages.clone()).await.is_err() {
tracing::warn!(parent: &span, kind = "store_error", "could not save the conversation");
}
end("completed");
yield Ok(ids.artifact(answer_parts(&response.output(), &response.content), false, true));
yield Ok(ids.status(TaskState::Completed, None));
return;
}
Ok(_) => {}
Err(error) => {
tracing::warn!(parent: &span, kind = "run_failed", reason = status_message(&error), "A2A task failed");
end("failed");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(failure_message(&error).into_owned()))));
return;
}
}
}
end("failed");
yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run ended without an answer."))));
}
}
struct Ids {
task: TaskId,
context: String,
}
impl Ids {
fn agent_message(&self, text: impl Into<String>) -> Message {
Message {
message_id: new_message_id(),
context_id: Some(self.context.clone()),
task_id: Some(self.task.clone()),
role: Role::Agent,
parts: vec![Part::text(text)],
metadata: None,
extensions: None,
reference_task_ids: None,
}
}
fn task(&self, state: TaskState, message: Option<Message>, history: Vec<Message>) -> Task {
Task {
id: self.task.clone(),
context_id: self.context.clone(),
status: status(state, message),
artifacts: None,
history: Some(history),
metadata: None,
}
}
fn status(&self, state: TaskState, message: Option<Message>) -> StreamResponse {
StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
task_id: self.task.clone(),
context_id: self.context.clone(),
status: status(state, message),
metadata: None,
})
}
fn chunk(&self, text: String, append: bool, last_chunk: bool) -> StreamResponse {
self.artifact(vec![Part::text(text)], append, last_chunk)
}
fn artifact(&self, parts: Vec<Part>, append: bool, last_chunk: bool) -> StreamResponse {
StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
task_id: self.task.clone(),
context_id: self.context.clone(),
artifact: Artifact {
artifact_id: RESPONSE_ARTIFACT.to_owned(),
name: Some(RESPONSE_ARTIFACT.to_owned()),
description: None,
parts,
metadata: None,
extensions: None,
},
append: Some(append),
last_chunk: Some(last_chunk),
metadata: None,
})
}
}
fn answer_parts(text: &str, content: &[AssistantContent]) -> Vec<Part> {
let mut parts = vec![Part::text(text)];
for item in content {
let AssistantContent::Image(image) = item else {
continue;
};
let content = match &image.data {
DocumentSourceKind::Url(url) => a2a::PartContent::Url(url.clone()),
DocumentSourceKind::Raw(bytes) => a2a::PartContent::Raw(bytes.clone()),
DocumentSourceKind::Base64(data) => match BASE64.decode(data) {
Ok(bytes) => a2a::PartContent::Raw(bytes),
Err(_) => continue,
},
_ => continue,
};
let mut part = Part::text("");
part.content = content;
part.media_type = image
.media_type
.as_ref()
.map(|kind| kind.to_mime_type().to_owned());
parts.push(part);
}
parts
}
fn status(state: TaskState, message: Option<Message>) -> TaskStatus {
TaskStatus {
state,
message,
timestamp: Some(chrono::Utc::now()),
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
fn failure_message(failure: &PromptError) -> Cow<'static, str> {
if let PromptError::MaxTurns { max_turns, .. } = failure {
return Cow::Owned(if *max_turns <= 1 {
"The agent reached its turn limit (1); agents with tools usually need AgentBuilder::default_max_turns(n) with n >= 2.".to_owned()
} else {
format!(
"The agent reached its turn limit ({max_turns}); raise AgentBuilder::default_max_turns above {max_turns} if the task needs more steps."
)
});
}
Cow::Borrowed(status_message(failure))
}
fn status_message(failure: &PromptError) -> &'static str {
let (status, retryable) = match failure {
PromptError::Provider(provider) => (
failure
.provider_response_status()
.map(|status| status.as_u16()),
provider.is_retryable(),
),
PromptError::Report(report) => (
report.http_status.or(report
.provider_response_status()
.map(|status| status.as_u16())),
report.retryable,
),
_ => (None, false),
};
match status {
Some(429) => "The model provider is rate limiting this agent; try again in a moment.",
Some(401 | 403) => "The model provider rejected this agent's credentials.",
Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
Some(_) => "The model provider rejected the request.",
None if retryable => "The model provider could not be reached; try again shortly.",
None => "The agent run failed.",
}
}
#[cfg(test)]
mod tests;