Skip to main content

rig_a2a/
executor.rs

1//! A Rig agent as an A2A agent executor.
2
3use 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
32/// The id of the text artifact each task's reply streams into.
33const RESPONSE_ARTIFACT: &str = "response";
34
35/// How many tasks run at once by default; more are rejected as busy.
36pub const DEFAULT_MAX_CONCURRENT_TASKS: usize = 32;
37/// How long one run may take by default before it is stopped.
38pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
39
40type Running = Arc<Mutex<HashMap<TaskId, AbortHandle>>>;
41
42tokio::task_local! {
43    /// The extensions the current run's request activated, set around each
44    /// poll of the run so tools and hooks running inside it can read them.
45    static ACTIVATED: Arc<[String]>;
46}
47
48/// The declared A2A extensions the request of the current agent run
49/// activated, sorted and without repeats.
50///
51/// Call it from a tool or a hook while an A2A run answers a request. The list
52/// holds only the URIs the server declares with
53/// [`A2aServer::extension`](crate::A2aServer::extension); an activated URI the
54/// server does not declare is left out. It is empty when the request activated
55/// none, and outside an A2A run.
56///
57/// The list is task-local. It is visible only on the task that polls the
58/// run. A tool that moves its work to `tokio::spawn`, `spawn_blocking` or
59/// another thread sees an empty list there. Read the list before spawning.
60///
61/// ```
62/// let activated: Vec<String> = rig_a2a::activated_extensions();
63/// assert!(activated.is_empty());
64/// ```
65#[must_use]
66pub fn activated_extensions() -> Vec<String> {
67    ACTIVATED
68        .try_with(|activated| activated.to_vec())
69        .unwrap_or_default()
70}
71
72/// The declared extensions a request activated, from its service params (the
73/// headers the SDK passes on, keyed in lowercase).
74fn 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
86/// A typed run, erased: the agent, the prompt and the history in; the answer
87/// as JSON and the run's transcript out, or what to tell the caller. `Send`
88/// and `Sync` because the A2A server shares the executor across tasks.
89type 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/// A Rig [`Agent`] as an A2A [`AgentExecutor`].
102///
103/// Each execution prompts the agent with the incoming message and the history
104/// of its `contextId`, streams the reply's text into one artifact, and ends the
105/// task completed, failed, or rejected when a part has no Rig content kind or
106/// the `contextId` is not 1 to 128 ASCII letters, digits, `-` or `_`. A
107/// completed run's messages join the context's history; see
108/// [`history_store`](Self::history_store) and
109/// [`history_window`](Self::history_window) for where it lives and how much
110/// of it the model sees. Cancelling a task drops its run.
111///
112/// Every task spends model tokens, so an executor bounds them: at most
113/// [`max_concurrent_tasks`](Self::max_concurrent_tasks) run at once (more are
114/// rejected as busy, before any model call) and each stops after
115/// [`max_run_duration`](Self::max_run_duration).
116#[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    /// The extensions the server declares; set by `A2aServer`.
126    declared: Arc<[String]>,
127}
128
129impl A2aExecutor {
130    /// An executor that answers every task with `agent`, keeping
131    /// conversations in memory.
132    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    /// The executor with `declared` as the extensions a run may see as
146    /// activated.
147    pub(crate) fn declaring(mut self, declared: Arc<[String]>) -> Self {
148        self.declared = declared;
149        self
150    }
151
152    /// Answer every task with a `T`, as one JSON data part: the agent runs
153    /// as [`Agent::prompt_typed`] does (with the conversation's history, and
154    /// two retries when the model's JSON does not parse as `T`). Use it to
155    /// serve an extractor or any agent whose callers want data, not prose.
156    #[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    /// Run at most `max` tasks at once (at least one); a task beyond that is
199    /// rejected as busy before it reaches the model. Defaults to
200    /// [`DEFAULT_MAX_CONCURRENT_TASKS`].
201    #[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    /// Stop a run that takes longer than `max`, failing its task. Defaults to
208    /// [`DEFAULT_MAX_RUN_DURATION`].
209    #[must_use]
210    pub fn max_run_duration(mut self, max: Duration) -> Self {
211        self.max_run = max;
212        self
213    }
214
215    /// Keep conversations in memory, at most `max` of them (at least one);
216    /// the oldest one started is forgotten first. This is the default, with
217    /// [`DEFAULT_MAX_CONTEXTS`]; it replaces a [`history_store`](Self::history_store).
218    #[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    /// Keep conversations in `store`, one session log per `contextId`, so
226    /// they survive restarts and several servers can share them: any
227    /// [`rig_memory`] store, such as `rig_memory::DirStore` (feature `fs`)
228    /// or the `rig-sqlite` and `rig-postgres` stores. Two servers saving one
229    /// conversation at once do not lose either turn.
230    #[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    /// Which newest messages of a conversation each request sends the
240    /// model, such as `rig_memory::recent::TokenBudget::new(8_000)` or
241    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
242    /// tool result is never sent without its call.
243    #[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
277/// Unregisters a task's abort handle when its run is dropped.
278struct 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        // The task's span: the agent's own spans (model calls, tools) nest
302        // under it, and it records how the task ended.
303        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        // Held until the run ends, however it ends (an abort drops it too).
345        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            // Each poll runs inside the scope, so a tool the model calls sees
398            // the activation. The run itself does not spawn tasks for tools.
399            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                    // The answer stands even if the history cannot be saved;
420                    // the next turn then starts without this one.
421                    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                    // The final answer replaces the streamed text, which can
425                    // include retried turns and text written before tool calls.
426                    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
445/// The task and context one execution reports on.
446struct 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    /// A piece of text of the response artifact; see [`Self::artifact`].
486    fn chunk(&self, text: String, append: bool, last_chunk: bool) -> StreamResponse {
487        self.artifact(vec![Part::text(text)], append, last_chunk)
488    }
489
490    /// Parts of the response artifact: appended to the parts before them, or
491    /// replacing them when `append` is false.
492    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
511/// The final answer's parts: its text, then any image the model produced.
512fn 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            // A provider-side file id or nothing: no bytes to send.
526            _ => 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
551/// What the caller is told when a run fails: enough to decide whether to
552/// retry, without the provider's own error text (which can name internals).
553///
554/// A failure arrives as the provider's error from an awaited run, or as its
555/// report from a streamed one; both carry the status and whether to retry.
556fn 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;