Skip to main content

rig_a2a/
executor.rs

1//! A Rig agent as an A2A agent executor.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5use std::time::Duration;
6
7use a2a::{
8    A2AError, Artifact, Message, Part, Role, StreamResponse, Task, TaskArtifactUpdateEvent, TaskId,
9    TaskState, TaskStatus, TaskStatusUpdateEvent, new_message_id,
10};
11use a2a_server::{AgentExecutor, ExecutorContext};
12use base64::Engine;
13use base64::engine::general_purpose::STANDARD as BASE64;
14use futures::StreamExt;
15use futures::stream::{AbortHandle, Abortable, BoxStream};
16use rig_agent::Agent;
17use rig_agent::agent::MultiTurnStreamItem;
18use rig_agent::completion::{PromptError, StructuredOutputError};
19use rig_core::message::{AssistantContent, DocumentSourceKind, MimeType};
20use rig_core::streaming::{Item, StreamEvent};
21use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
22use rig_memory::AsyncStore;
23use rig_memory::recent::{Recent, TokenBudget, view};
24
25use crate::history::{
26    DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
27    valid_context_id,
28};
29use crate::parts::user_message;
30
31/// The id of the text artifact each task's reply streams into.
32const RESPONSE_ARTIFACT: &str = "response";
33
34/// How many tasks run at once by default; more are rejected as busy.
35pub const DEFAULT_MAX_CONCURRENT_TASKS: usize = 32;
36/// How long one run may take by default before it is stopped.
37pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
38
39type Running = Arc<Mutex<HashMap<TaskId, AbortHandle>>>;
40
41/// A typed run, erased: the agent, the prompt and the history in; the answer
42/// as JSON and the run's transcript out, or what to tell the caller. `Send`
43/// and `Sync` because the A2A server shares the executor across tasks.
44type TypedAnswer = Arc<
45    dyn Fn(
46            Agent,
47            rig_core::message::Message,
48            Vec<rig_core::message::Message>,
49        ) -> WasmBoxedFuture<
50            'static,
51            Result<(serde_json::Value, Vec<rig_core::message::Message>), String>,
52        > + Send
53        + Sync,
54>;
55
56/// A Rig [`Agent`] as an A2A [`AgentExecutor`].
57///
58/// Each execution prompts the agent with the incoming message and the history
59/// of its `contextId`, streams the reply's text into one artifact, and ends the
60/// task completed, failed, or rejected when a part has no Rig content kind or
61/// the `contextId` is not 1 to 128 ASCII letters, digits, `-` or `_`. A
62/// completed run's messages join the context's history; see
63/// [`history_store`](Self::history_store) and
64/// [`history_window`](Self::history_window) for where it lives and how much
65/// of it the model sees. Cancelling a task drops its run.
66///
67/// Every task spends model tokens, so an executor bounds them: at most
68/// [`max_concurrent_tasks`](Self::max_concurrent_tasks) run at once (more are
69/// rejected as busy, before any model call) and each stops after
70/// [`max_run_duration`](Self::max_run_duration).
71#[derive(Clone)]
72pub struct A2aExecutor {
73    agent: Agent,
74    history: Arc<dyn HistoryStore>,
75    window: Arc<dyn Recent>,
76    running: Running,
77    slots: Arc<tokio::sync::Semaphore>,
78    max_run: Duration,
79    typed: Option<TypedAnswer>,
80}
81
82impl A2aExecutor {
83    /// An executor that answers every task with `agent`, keeping
84    /// conversations in memory.
85    pub fn new(agent: Agent) -> Self {
86        Self {
87            agent,
88            history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
89            window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
90            running: Arc::default(),
91            slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_TASKS)),
92            max_run: DEFAULT_MAX_RUN_DURATION,
93            typed: None,
94        }
95    }
96
97    /// Answer every task with a `T`, as one JSON data part: the agent runs
98    /// as [`Agent::prompt_typed`] does (with the conversation's history, and
99    /// two retries when the model's JSON does not parse as `T`). Use it to
100    /// serve an extractor or any agent whose callers want data, not prose.
101    #[must_use]
102    pub fn typed<T>(mut self) -> Self
103    where
104        T: schemars::JsonSchema
105            + serde::de::DeserializeOwned
106            + serde::Serialize
107            + WasmCompatSend
108            + WasmCompatSync
109            + 'static,
110    {
111        self.typed = Some(Arc::new(|agent, prompt, history| {
112            Box::pin(async move {
113                let response = agent
114                    .prompt_typed::<T>(prompt)
115                    .history(history)
116                    .retries(2)
117                    .await
118                    .map_err(|error| {
119                        tracing::warn!(%error, "A2A typed task failed");
120                        match &error {
121                            StructuredOutputError::Prompt(prompt) => failure_message(prompt),
122                            _ => "The agent could not produce a structured answer.",
123                        }
124                        .to_owned()
125                    })?;
126                let value =
127                    serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
128                Ok((value, response.messages))
129            })
130        }));
131        self
132    }
133
134    /// Run at most `max` tasks at once (at least one); a task beyond that is
135    /// rejected as busy before it reaches the model. Defaults to
136    /// [`DEFAULT_MAX_CONCURRENT_TASKS`].
137    #[must_use]
138    pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
139        self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
140        self
141    }
142
143    /// Stop a run that takes longer than `max`, failing its task. Defaults to
144    /// [`DEFAULT_MAX_RUN_DURATION`].
145    #[must_use]
146    pub fn max_run_duration(mut self, max: Duration) -> Self {
147        self.max_run = max;
148        self
149    }
150
151    /// Keep conversations in memory, at most `max` of them (at least one);
152    /// the oldest one started is forgotten first. This is the default, with
153    /// [`DEFAULT_MAX_CONTEXTS`]; it replaces a [`history_store`](Self::history_store).
154    #[must_use]
155    pub fn max_contexts(mut self, max: usize) -> Self {
156        self.history = Arc::new(InMemory::new(max));
157        self
158    }
159
160    /// Keep conversations in `store`, one session log per `contextId`, so
161    /// they survive restarts and several servers can share them: any
162    /// [`rig_memory`] store, such as `rig_memory::DirStore` (feature `fs`)
163    /// or the `rig-sqlite` and `rig-postgres` stores. Two servers saving one
164    /// conversation at once do not lose either turn.
165    #[must_use]
166    pub fn history_store<S>(mut self, store: S) -> Self
167    where
168        S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
169    {
170        self.history = Arc::new(Persistent(store));
171        self
172    }
173
174    /// Which newest messages of a conversation each request sends the
175    /// model, such as `rig_memory::recent::TokenBudget::new(8_000)` or
176    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
177    /// tool result is never sent without its call.
178    #[must_use]
179    pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
180        self.window = Arc::new(window);
181        self
182    }
183}
184
185impl AgentExecutor for A2aExecutor {
186    fn execute(
187        &self,
188        ctx: ExecutorContext,
189    ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
190        let (handle, registration) = AbortHandle::new_pair();
191        lock(&self.running).insert(ctx.task_id.clone(), handle);
192        let registered = Registered {
193            running: Arc::clone(&self.running),
194            task_id: ctx.task_id.clone(),
195        };
196        let run = run(self.clone(), ctx, registered);
197        Abortable::new(run, registration).boxed()
198    }
199
200    fn cancel(&self, ctx: ExecutorContext) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
201        if let Some(handle) = lock(&self.running).remove(&ctx.task_id) {
202            handle.abort();
203        }
204        let ids = Ids {
205            task: ctx.task_id,
206            context: ctx.context_id,
207        };
208        futures::stream::iter([Ok(ids.status(TaskState::Canceled, None))]).boxed()
209    }
210}
211
212/// Unregisters a task's abort handle when its run is dropped.
213struct Registered {
214    running: Running,
215    task_id: TaskId,
216}
217
218impl Drop for Registered {
219    fn drop(&mut self) {
220        lock(&self.running).remove(&self.task_id);
221    }
222}
223
224fn run(
225    executor: A2aExecutor,
226    ctx: ExecutorContext,
227    registered: Registered,
228) -> impl futures::Stream<Item = Result<StreamResponse, A2AError>> + Send + 'static {
229    async_stream::stream! {
230        let _registered = registered;
231        let ids = Ids {
232            task: ctx.task_id,
233            context: ctx.context_id,
234        };
235        // The task's span: the agent's own spans (model calls, tools) nest
236        // under it, and it records how the task ended.
237        let span = tracing::info_span!(
238            "a2a.task",
239            otel.kind = "server",
240            a2a.task_id = %ids.task,
241            a2a.context_id = %ids.context,
242            a2a.state = tracing::field::Empty,
243        );
244        #[cfg(feature = "otel")]
245        crate::otel::continue_trace(&span, &ctx.service_params, &ids.context);
246        let end = |state: &'static str| {
247            span.record("a2a.state", state);
248        };
249        let Some(message) = ctx.message else {
250            end("failed");
251            yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("No message to answer."))));
252            return;
253        };
254        let mut history = ctx
255            .stored_task
256            .and_then(|task| task.history)
257            .unwrap_or_default();
258        if history.last().map(|last| &last.message_id) != Some(&message.message_id) {
259            history.push(message.clone());
260        }
261        if !valid_context_id(&ids.context) {
262            let reason = ids.agent_message(
263                "contextId must be 1 to 128 ASCII letters, digits, `-` or `_`.",
264            );
265            end("rejected");
266            yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
267            return;
268        }
269        let prompt = match user_message(&message) {
270            Ok(prompt) => prompt,
271            Err(unsupported) => {
272                let reason = ids.agent_message(unsupported.to_string());
273                end("rejected");
274                yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
275                return;
276            }
277        };
278        // Held until the run ends, however it ends (an abort drops it too).
279        let Ok(_slot) = Arc::clone(&executor.slots).try_acquire_owned() else {
280            let reason = ids.agent_message("The agent is busy; try again shortly.");
281            end("rejected_busy");
282            yield Ok(StreamResponse::Task(ids.task(TaskState::Rejected, Some(reason), history)));
283            return;
284        };
285        yield Ok(StreamResponse::Task(ids.task(TaskState::Working, None, history)));
286
287        let prior = match executor.history.load(&ids.context).await {
288            Ok(messages) => view(&messages, executor.window.as_ref())
289                .iter()
290                .map(|message| (**message).clone())
291                .collect::<Vec<_>>(),
292            Err(error) => {
293                tracing::warn!(parent: &span, %error, "could not load the conversation");
294                end("failed");
295                yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The conversation could not be loaded."))));
296                return;
297            }
298        };
299        let deadline = tokio::time::Instant::now() + executor.max_run;
300        if let Some(typed) = &executor.typed {
301            let answer = tracing::Instrument::instrument(typed(executor.agent.clone(), prompt, prior), span.clone());
302            match tokio::time::timeout_at(deadline, answer).await {
303                Err(_) => {
304                    end("failed_timeout");
305                    yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
306                }
307                Ok(Err(reason)) => {
308                    end("failed");
309                    yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(reason))));
310                }
311                Ok(Ok((value, messages))) => {
312                    if let Err(error) = executor.history.append(&ids.context, messages).await {
313                        tracing::warn!(parent: &span, %error, "could not save the conversation");
314                    }
315                    let mut data = Part::text("");
316                    data.content = a2a::PartContent::Data(value);
317                    data.media_type = Some("application/json".to_owned());
318                    end("completed");
319                    yield Ok(ids.artifact(vec![data], false, true));
320                    yield Ok(ids.status(TaskState::Completed, None));
321                }
322            }
323            return;
324        }
325        let mut stream = span.in_scope(|| executor.agent.prompt(prompt).history(prior).stream());
326        let mut streamed = false;
327        loop {
328            let item = match tokio::time::timeout_at(deadline, stream.next()).await {
329                Ok(Some(item)) => item,
330                Ok(None) => break,
331                Err(_) => {
332                    tracing::warn!(parent: &span, max = ?executor.max_run, "A2A run took too long");
333                    end("failed_timeout");
334                    yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run took longer than allowed."))));
335                    return;
336                }
337            };
338            match item {
339                Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
340                    text,
341                    ..
342                }))) => {
343                    yield Ok(ids.chunk(text, streamed, false));
344                    streamed = true;
345                }
346                Ok(MultiTurnStreamItem::FinalResponse(response)) => {
347                    // The answer stands even if the history cannot be saved;
348                    // the next turn then starts without this one.
349                    if let Err(error) = executor.history.append(&ids.context, response.messages.clone()).await {
350                        tracing::warn!(parent: &span, %error, "could not save the conversation");
351                    }
352                    // The final answer replaces the streamed text, which can
353                    // include retried turns and text written before tool calls.
354                    end("completed");
355                    yield Ok(ids.artifact(answer_parts(&response.output(), &response.content), false, true));
356                    yield Ok(ids.status(TaskState::Completed, None));
357                    return;
358                }
359                Ok(_) => {}
360                Err(error) => {
361                    tracing::warn!(parent: &span, %error, "A2A task failed");
362                    end("failed");
363                    yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message(failure_message(&error)))));
364                    return;
365                }
366            }
367        }
368        end("failed");
369        yield Ok(ids.status(TaskState::Failed, Some(ids.agent_message("The agent run ended without an answer."))));
370    }
371}
372
373/// The task and context one execution reports on.
374struct Ids {
375    task: TaskId,
376    context: String,
377}
378
379impl Ids {
380    fn agent_message(&self, text: impl Into<String>) -> Message {
381        Message {
382            message_id: new_message_id(),
383            context_id: Some(self.context.clone()),
384            task_id: Some(self.task.clone()),
385            role: Role::Agent,
386            parts: vec![Part::text(text)],
387            metadata: None,
388            extensions: None,
389            reference_task_ids: None,
390        }
391    }
392
393    fn task(&self, state: TaskState, message: Option<Message>, history: Vec<Message>) -> Task {
394        Task {
395            id: self.task.clone(),
396            context_id: self.context.clone(),
397            status: status(state, message),
398            artifacts: None,
399            history: Some(history),
400            metadata: None,
401        }
402    }
403
404    fn status(&self, state: TaskState, message: Option<Message>) -> StreamResponse {
405        StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
406            task_id: self.task.clone(),
407            context_id: self.context.clone(),
408            status: status(state, message),
409            metadata: None,
410        })
411    }
412
413    /// A piece of text of the response artifact; see [`Self::artifact`].
414    fn chunk(&self, text: String, append: bool, last_chunk: bool) -> StreamResponse {
415        self.artifact(vec![Part::text(text)], append, last_chunk)
416    }
417
418    /// Parts of the response artifact: appended to the parts before them, or
419    /// replacing them when `append` is false.
420    fn artifact(&self, parts: Vec<Part>, append: bool, last_chunk: bool) -> StreamResponse {
421        StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
422            task_id: self.task.clone(),
423            context_id: self.context.clone(),
424            artifact: Artifact {
425                artifact_id: RESPONSE_ARTIFACT.to_owned(),
426                name: Some(RESPONSE_ARTIFACT.to_owned()),
427                description: None,
428                parts,
429                metadata: None,
430                extensions: None,
431            },
432            append: Some(append),
433            last_chunk: Some(last_chunk),
434            metadata: None,
435        })
436    }
437}
438
439/// The final answer's parts: its text, then any image the model produced.
440fn answer_parts(text: &str, content: &[AssistantContent]) -> Vec<Part> {
441    let mut parts = vec![Part::text(text)];
442    for item in content {
443        let AssistantContent::Image(image) = item else {
444            continue;
445        };
446        let content = match &image.data {
447            DocumentSourceKind::Url(url) => a2a::PartContent::Url(url.clone()),
448            DocumentSourceKind::Raw(bytes) => a2a::PartContent::Raw(bytes.clone()),
449            DocumentSourceKind::Base64(data) => match BASE64.decode(data) {
450                Ok(bytes) => a2a::PartContent::Raw(bytes),
451                Err(_) => continue,
452            },
453            // A provider-side file id or nothing: no bytes to send.
454            _ => continue,
455        };
456        let mut part = Part::text("");
457        part.content = content;
458        part.media_type = image
459            .media_type
460            .as_ref()
461            .map(|kind| kind.to_mime_type().to_owned());
462        parts.push(part);
463    }
464    parts
465}
466
467fn status(state: TaskState, message: Option<Message>) -> TaskStatus {
468    TaskStatus {
469        state,
470        message,
471        timestamp: Some(chrono::Utc::now()),
472    }
473}
474
475fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
476    mutex.lock().unwrap_or_else(PoisonError::into_inner)
477}
478
479/// What the caller is told when a run fails: enough to decide whether to
480/// retry, without the provider's own error text (which can name internals).
481///
482/// A failure arrives as the provider's error from an awaited run, or as its
483/// report from a streamed one; both carry the status and whether to retry.
484fn failure_message(failure: &PromptError) -> &'static str {
485    let (status, retryable) = match failure {
486        PromptError::Provider(provider) => (
487            failure
488                .provider_response_status()
489                .map(|status| status.as_u16()),
490            provider.is_retryable(),
491        ),
492        PromptError::Report(report) => (
493            report.http_status.or(report
494                .provider_response_status()
495                .map(|status| status.as_u16())),
496            report.retryable,
497        ),
498        PromptError::MaxTurns { .. } => {
499            return "The agent used up its turns without finishing.";
500        }
501        _ => (None, false),
502    };
503    match status {
504        Some(429) => "The model provider is rate limiting this agent; try again in a moment.",
505        Some(401 | 403) => "The model provider rejected this agent's credentials.",
506        Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
507        Some(_) => "The model provider rejected the request.",
508        None if retryable => "The model provider could not be reached; try again shortly.",
509        None => "The agent run failed.",
510    }
511}
512
513#[cfg(test)]
514mod tests;