1use std::borrow::Cow;
4use std::collections::HashMap;
5use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
6use std::time::Duration;
7
8use a2a::{
9 A2AError, Artifact, Message, Part, Role, StreamResponse, Task, TaskArtifactUpdateEvent, TaskId,
10 TaskState, TaskStatus, TaskStatusUpdateEvent, new_message_id,
11};
12use a2a_server::{AgentExecutor, ExecutorContext, ServiceParams};
13use base64::Engine;
14use base64::engine::general_purpose::STANDARD as BASE64;
15use futures::StreamExt;
16use futures::stream::{AbortHandle, Abortable, BoxStream};
17use rig_agent::Agent;
18use rig_agent::agent::MultiTurnStreamItem;
19use rig_agent::completion::{PromptError, StructuredOutputError};
20use rig_core::message::{AssistantContent, DocumentSourceKind, MimeType};
21use rig_core::streaming::{Item, StreamEvent};
22use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
23use rig_memory::AsyncStore;
24use rig_memory::recent::{Recent, TokenBudget, view};
25
26use crate::history::{
27 DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
28 valid_context_id,
29};
30use crate::parts::user_message;
31
32const RESPONSE_ARTIFACT: &str = "response";
34
35pub const DEFAULT_MAX_CONCURRENT_TASKS: usize = 32;
37pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
39
40type Running = Arc<Mutex<HashMap<TaskId, AbortHandle>>>;
41
42tokio::task_local! {
43 static ACTIVATED: Arc<[String]>;
46}
47
48#[must_use]
66pub fn activated_extensions() -> Vec<String> {
67 ACTIVATED
68 .try_with(|activated| activated.to_vec())
69 .unwrap_or_default()
70}
71
72fn activated_from(params: &ServiceParams, declared: &[String]) -> Arc<[String]> {
75 crate::server::activated_in(
76 params
77 .get(crate::server::EXTENSIONS_HEADER.as_str())
78 .into_iter()
79 .flatten()
80 .map(String::as_str),
81 declared,
82 )
83 .into()
84}
85
86type TypedAnswer = Arc<
90 dyn Fn(
91 Agent,
92 rig_core::message::Message,
93 Vec<rig_core::message::Message>,
94 ) -> WasmBoxedFuture<
95 'static,
96 Result<(serde_json::Value, Vec<rig_core::message::Message>), String>,
97 > + Send
98 + Sync,
99>;
100
101#[derive(Clone)]
117pub struct A2aExecutor {
118 agent: Agent,
119 history: Arc<dyn HistoryStore>,
120 window: Arc<dyn Recent>,
121 running: Running,
122 slots: Arc<tokio::sync::Semaphore>,
123 max_run: Duration,
124 typed: Option<TypedAnswer>,
125 declared: Arc<[String]>,
127}
128
129impl A2aExecutor {
130 pub fn new(agent: Agent) -> Self {
133 Self {
134 agent,
135 history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
136 window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
137 running: Arc::default(),
138 slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_TASKS)),
139 max_run: DEFAULT_MAX_RUN_DURATION,
140 typed: None,
141 declared: Arc::from(Vec::new()),
142 }
143 }
144
145 pub(crate) fn declaring(mut self, declared: Arc<[String]>) -> Self {
148 self.declared = declared;
149 self
150 }
151
152 #[must_use]
157 pub fn typed<T>(mut self) -> Self
158 where
159 T: schemars::JsonSchema
160 + serde::de::DeserializeOwned
161 + serde::Serialize
162 + WasmCompatSend
163 + WasmCompatSync
164 + 'static,
165 {
166 self.typed = Some(Arc::new(|agent, prompt, history| {
167 Box::pin(async move {
168 let response = agent
169 .prompt_typed::<T>(prompt)
170 .history(history)
171 .retries(2)
172 .await
173 .map_err(|error| {
174 let reason = match &error {
175 StructuredOutputError::Prompt(prompt) => status_message(prompt),
176 _ => "not a structured answer",
177 };
178 tracing::warn!(
179 kind = "run_failed",
180 reason = reason,
181 "A2A typed task failed"
182 );
183 match &error {
184 StructuredOutputError::Prompt(prompt) => {
185 failure_message(prompt).into_owned()
186 }
187 _ => "The agent could not produce a structured answer.".to_owned(),
188 }
189 })?;
190 let value =
191 serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
192 Ok((value, response.messages))
193 })
194 }));
195 self
196 }
197
198 #[must_use]
202 pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
203 self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
204 self
205 }
206
207 #[must_use]
210 pub fn max_run_duration(mut self, max: Duration) -> Self {
211 self.max_run = max;
212 self
213 }
214
215 #[must_use]
219 #[doc(alias = "max_sessions")]
220 pub fn max_contexts(mut self, max: usize) -> Self {
221 self.history = Arc::new(InMemory::new(max));
222 self
223 }
224
225 #[must_use]
231 pub fn history_store<S>(mut self, store: S) -> Self
232 where
233 S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
234 {
235 self.history = Arc::new(Persistent(store));
236 self
237 }
238
239 #[must_use]
244 pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
245 self.window = Arc::new(window);
246 self
247 }
248}
249
250impl AgentExecutor for A2aExecutor {
251 fn execute(
252 &self,
253 ctx: ExecutorContext,
254 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
255 let (handle, registration) = AbortHandle::new_pair();
256 lock(&self.running).insert(ctx.task_id.clone(), handle);
257 let registered = Registered {
258 running: Arc::clone(&self.running),
259 task_id: ctx.task_id.clone(),
260 };
261 let run = run(self.clone(), ctx, registered);
262 Abortable::new(run, registration).boxed()
263 }
264
265 fn cancel(&self, ctx: ExecutorContext) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
266 if let Some(handle) = lock(&self.running).remove(&ctx.task_id) {
267 handle.abort();
268 }
269 let ids = Ids {
270 task: ctx.task_id,
271 context: ctx.context_id,
272 };
273 futures::stream::iter([Ok(ids.status(TaskState::Canceled, None))]).boxed()
274 }
275}
276
277struct Registered {
279 running: Running,
280 task_id: TaskId,
281}
282
283impl Drop for Registered {
284 fn drop(&mut self) {
285 lock(&self.running).remove(&self.task_id);
286 }
287}
288
289fn run(
290 executor: A2aExecutor,
291 ctx: ExecutorContext,
292 registered: Registered,
293) -> impl futures::Stream<Item = Result<StreamResponse, A2AError>> + Send + 'static {
294 async_stream::stream! {
295 let _registered = registered;
296 let activated = activated_from(&ctx.service_params, &executor.declared);
297 let ids = Ids {
298 task: ctx.task_id,
299 context: ctx.context_id,
300 };
301 let span = tracing::info_span!(
304 "a2a.task",
305 otel.kind = "server",
306 a2a.task_id = %ids.task,
307 a2a.context_id = %ids.context,
308 a2a.state = tracing::field::Empty,
309 );
310 #[cfg(feature = "otel")]
311 crate::otel::continue_trace(&span, &ctx.service_params, &ids.context);
312 let end = |state: &'static str| {
313 span.record("a2a.state", state);
314 };
315 let Some(message) = ctx.message else {
316 end("failed");
317 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("No message to answer."))));
318 return;
319 };
320 let mut history = ctx
321 .stored_task
322 .and_then(|task| task.history)
323 .unwrap_or_default();
324 if history.last().map(|last| &last.message_id) != Some(&message.message_id) {
325 history.push(message.clone());
326 }
327 if !valid_context_id(&ids.context) {
328 let reason = ids.agent_message(
329 "contextId must be 1 to 128 ASCII letters, digits, `-` or `_`.",
330 );
331 end("rejected");
332 yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
333 return;
334 }
335 let prompt = match user_message(&message) {
336 Ok(prompt) => prompt,
337 Err(unsupported) => {
338 let reason = ids.agent_message(unsupported.to_string());
339 end("rejected");
340 yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
341 return;
342 }
343 };
344 let Ok(_slot) = Arc::clone(&executor.slots).try_acquire_owned() else {
346 let reason = ids.agent_message("The agent is busy; try again shortly.");
347 end("rejected_busy");
348 yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
349 return;
350 };
351 yield Ok(StreamResponse::Task(ids.task(TaskState::Working, None, history)));
352
353 let prior = match executor.history.load(&ids.context).await {
354 Ok(messages) => view(&messages, executor.window.as_ref())
355 .iter()
356 .map(|message| (**message).clone())
357 .collect::<Vec<_>>(),
358 Err(_) => {
359 tracing::warn!(parent: &span, kind = "store_error", "could not load the conversation");
360 end("failed");
361 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The conversation could not be loaded."))));
362 return;
363 }
364 };
365 let deadline = tokio::time::Instant::now() + executor.max_run;
366 if let Some(typed) = &executor.typed {
367 let answer = ACTIVATED.scope(
368 Arc::clone(&activated),
369 tracing::Instrument::instrument(typed(executor.agent.clone(), prompt, prior), span.clone()),
370 );
371 match tokio::time::timeout_at(deadline, answer).await {
372 Err(_) => {
373 end("failed_timeout");
374 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
375 }
376 Ok(Err(reason)) => {
377 end("failed");
378 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(reason))));
379 }
380 Ok(Ok((value, messages))) => {
381 if executor.history.append(&ids.context, messages).await.is_err() {
382 tracing::warn!(parent: &span, kind = "store_error", "could not save the conversation");
383 }
384 let mut data = Part::text("");
385 data.content = a2a::PartContent::Data(value);
386 data.media_type = Some("application/json".to_owned());
387 end("completed");
388 yield Ok(ids.artifact(vec![data], false, true));
389 yield Ok(ids.status(TaskState::Completed, None));
390 }
391 }
392 return;
393 }
394 let mut stream = span.in_scope(|| executor.agent.prompt(prompt).history(prior).stream());
395 let mut streamed = false;
396 loop {
397 let next = ACTIVATED.scope(Arc::clone(&activated), stream.next());
400 let item = match tokio::time::timeout_at(deadline, next).await {
401 Ok(Some(item)) => item,
402 Ok(None) => break,
403 Err(_) => {
404 tracing::warn!(parent: &span, max = ?executor.max_run, "A2A run took too long");
405 end("failed_timeout");
406 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
407 return;
408 }
409 };
410 match item {
411 Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
412 text,
413 ..
414 }))) => {
415 yield Ok(ids.chunk(text, streamed, false));
416 streamed = true;
417 }
418 Ok(MultiTurnStreamItem::FinalResponse(response)) => {
419 if executor.history.append(&ids.context, response.messages.clone()).await.is_err() {
422 tracing::warn!(parent: &span, kind = "store_error", "could not save the conversation");
423 }
424 end("completed");
427 yield Ok(ids.artifact(answer_parts(&response.output(), &response.content), false, true));
428 yield Ok(ids.status(TaskState::Completed, None));
429 return;
430 }
431 Ok(_) => {}
432 Err(error) => {
433 tracing::warn!(parent: &span, kind = "run_failed", reason = status_message(&error), "A2A task failed");
434 end("failed");
435 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(failure_message(&error).into_owned()))));
436 return;
437 }
438 }
439 }
440 end("failed");
441 yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run ended without an answer."))));
442 }
443}
444
445struct Ids {
447 task: TaskId,
448 context: String,
449}
450
451impl Ids {
452 fn agent_message(&self, text: impl Into<String>) -> Message {
453 Message {
454 message_id: new_message_id(),
455 context_id: Some(self.context.clone()),
456 task_id: Some(self.task.clone()),
457 role: Role::Agent,
458 parts: vec![Part::text(text)],
459 metadata: None,
460 extensions: None,
461 reference_task_ids: None,
462 }
463 }
464
465 fn task(&self, state: TaskState, message: Option<Message>, history: Vec<Message>) -> Task {
466 Task {
467 id: self.task.clone(),
468 context_id: self.context.clone(),
469 status: status(state, message),
470 artifacts: None,
471 history: Some(history),
472 metadata: None,
473 }
474 }
475
476 fn status(&self, state: TaskState, message: Option<Message>) -> StreamResponse {
477 StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
478 task_id: self.task.clone(),
479 context_id: self.context.clone(),
480 status: status(state, message),
481 metadata: None,
482 })
483 }
484
485 fn chunk(&self, text: String, append: bool, last_chunk: bool) -> StreamResponse {
487 self.artifact(vec![Part::text(text)], append, last_chunk)
488 }
489
490 fn artifact(&self, parts: Vec<Part>, append: bool, last_chunk: bool) -> StreamResponse {
493 StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
494 task_id: self.task.clone(),
495 context_id: self.context.clone(),
496 artifact: Artifact {
497 artifact_id: RESPONSE_ARTIFACT.to_owned(),
498 name: Some(RESPONSE_ARTIFACT.to_owned()),
499 description: None,
500 parts,
501 metadata: None,
502 extensions: None,
503 },
504 append: Some(append),
505 last_chunk: Some(last_chunk),
506 metadata: None,
507 })
508 }
509}
510
511fn answer_parts(text: &str, content: &[AssistantContent]) -> Vec<Part> {
513 let mut parts = vec![Part::text(text)];
514 for item in content {
515 let AssistantContent::Image(image) = item else {
516 continue;
517 };
518 let content = match &image.data {
519 DocumentSourceKind::Url(url) => a2a::PartContent::Url(url.clone()),
520 DocumentSourceKind::Raw(bytes) => a2a::PartContent::Raw(bytes.clone()),
521 DocumentSourceKind::Base64(data) => match BASE64.decode(data) {
522 Ok(bytes) => a2a::PartContent::Raw(bytes),
523 Err(_) => continue,
524 },
525 _ => continue,
527 };
528 let mut part = Part::text("");
529 part.content = content;
530 part.media_type = image
531 .media_type
532 .as_ref()
533 .map(|kind| kind.to_mime_type().to_owned());
534 parts.push(part);
535 }
536 parts
537}
538
539fn status(state: TaskState, message: Option<Message>) -> TaskStatus {
540 TaskStatus {
541 state,
542 message,
543 timestamp: Some(chrono::Utc::now()),
544 }
545}
546
547fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
548 mutex.lock().unwrap_or_else(PoisonError::into_inner)
549}
550
551fn failure_message(failure: &PromptError) -> Cow<'static, str> {
557 if let PromptError::MaxTurns { max_turns, .. } = failure {
558 return Cow::Owned(if *max_turns <= 1 {
559 "The agent reached its turn limit (1); agents with tools usually need AgentBuilder::default_max_turns(n) with n >= 2.".to_owned()
560 } else {
561 format!(
562 "The agent reached its turn limit ({max_turns}); raise AgentBuilder::default_max_turns above {max_turns} if the task needs more steps."
563 )
564 });
565 }
566 Cow::Borrowed(status_message(failure))
567}
568
569fn status_message(failure: &PromptError) -> &'static str {
570 let (status, retryable) = match failure {
571 PromptError::Provider(provider) => (
572 failure
573 .provider_response_status()
574 .map(|status| status.as_u16()),
575 provider.is_retryable(),
576 ),
577 PromptError::Report(report) => (
578 report.http_status.or(report
579 .provider_response_status()
580 .map(|status| status.as_u16())),
581 report.retryable,
582 ),
583 _ => (None, false),
584 };
585 match status {
586 Some(429) => "The model provider is rate limiting this agent; try again in a moment.",
587 Some(401 | 403) => "The model provider rejected this agent's credentials.",
588 Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
589 Some(_) => "The model provider rejected the request.",
590 None if retryable => "The model provider could not be reached; try again shortly.",
591 None => "The agent run failed.",
592 }
593}
594
595#[cfg(test)]
596mod tests;