rig-a2a 0.47.9

Serve Rig agents over the Agent2Agent (A2A) protocol and call remote A2A agents as Rig tools, built on the official A2A Rust SDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! A Rig agent as an A2A agent executor.

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;

/// The id of the text artifact each task's reply streams into.
const RESPONSE_ARTIFACT: &str = "response";

/// How many tasks run at once by default; more are rejected as busy.
pub const DEFAULT_MAX_CONCURRENT_TASKS: usize = 32;
/// How long one run may take by default before it is stopped.
pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);

type Running = Arc<Mutex<HashMap<TaskId, AbortHandle>>>;

tokio::task_local! {
    /// The extensions the current run's request activated, set around each
    /// poll of the run so tools and hooks running inside it can read them.
    static ACTIVATED: Arc<[String]>;
}

/// The declared A2A extensions the request of the current agent run
/// activated, sorted and without repeats.
///
/// Call it from a tool or a hook while an A2A run answers a request. The list
/// holds only the URIs the server declares with
/// [`A2aServer::extension`](crate::A2aServer::extension); an activated URI the
/// server does not declare is left out. It is empty when the request activated
/// none, and outside an A2A run.
///
/// The list is task-local. It is visible only on the task that polls the
/// run. A tool that moves its work to `tokio::spawn`, `spawn_blocking` or
/// another thread sees an empty list there. Read the list before spawning.
///
/// ```
/// let activated: Vec<String> = rig_a2a::activated_extensions();
/// assert!(activated.is_empty());
/// ```
#[must_use]
pub fn activated_extensions() -> Vec<String> {
    ACTIVATED
        .try_with(|activated| activated.to_vec())
        .unwrap_or_default()
}

/// The declared extensions a request activated, from its service params (the
/// headers the SDK passes on, keyed in lowercase).
fn activated_from(params: &ServiceParams, declared: &[String]) -> Arc<[String]> {
    crate::server::activated_in(
        params
            .get(crate::server::EXTENSIONS_HEADER.as_str())
            .into_iter()
            .flatten()
            .map(String::as_str),
        declared,
    )
    .into()
}

/// A typed run, erased: the agent, the prompt and the history in; the answer
/// as JSON and the run's transcript out, or what to tell the caller. `Send`
/// and `Sync` because the A2A server shares the executor across tasks.
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,
>;

/// A Rig [`Agent`] as an A2A [`AgentExecutor`].
///
/// Each execution prompts the agent with the incoming message and the history
/// of its `contextId`, streams the reply's text into one artifact, and ends the
/// task completed, failed, or rejected when a part has no Rig content kind or
/// the `contextId` is not 1 to 128 ASCII letters, digits, `-` or `_`. A
/// completed run's messages join the context's history; see
/// [`history_store`](Self::history_store) and
/// [`history_window`](Self::history_window) for where it lives and how much
/// of it the model sees. Cancelling a task drops its run.
///
/// Every task spends model tokens, so an executor bounds them: at most
/// [`max_concurrent_tasks`](Self::max_concurrent_tasks) run at once (more are
/// rejected as busy, before any model call) and each stops after
/// [`max_run_duration`](Self::max_run_duration).
#[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>,
    /// The extensions the server declares; set by `A2aServer`.
    declared: Arc<[String]>,
}

impl A2aExecutor {
    /// An executor that answers every task with `agent`, keeping
    /// conversations in memory.
    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()),
        }
    }

    /// The executor with `declared` as the extensions a run may see as
    /// activated.
    pub(crate) fn declaring(mut self, declared: Arc<[String]>) -> Self {
        self.declared = declared;
        self
    }

    /// Answer every task with a `T`, as one JSON data part: the agent runs
    /// as [`Agent::prompt_typed`] does (with the conversation's history, and
    /// two retries when the model's JSON does not parse as `T`). Use it to
    /// serve an extractor or any agent whose callers want data, not prose.
    #[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
    }

    /// Run at most `max` tasks at once (at least one); a task beyond that is
    /// rejected as busy before it reaches the model. Defaults to
    /// [`DEFAULT_MAX_CONCURRENT_TASKS`].
    #[must_use]
    pub fn max_concurrent_tasks(mut self, max: usize) -> Self {
        self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
        self
    }

    /// Stop a run that takes longer than `max`, failing its task. Defaults to
    /// [`DEFAULT_MAX_RUN_DURATION`].
    #[must_use]
    pub fn max_run_duration(mut self, max: Duration) -> Self {
        self.max_run = max;
        self
    }

    /// Keep conversations in memory, at most `max` of them (at least one);
    /// the oldest one started is forgotten first. This is the default, with
    /// [`DEFAULT_MAX_CONTEXTS`]; it replaces a [`history_store`](Self::history_store).
    #[must_use]
    #[doc(alias = "max_sessions")]
    pub fn max_contexts(mut self, max: usize) -> Self {
        self.history = Arc::new(InMemory::new(max));
        self
    }

    /// Keep conversations in `store`, one session log per `contextId`, so
    /// they survive restarts and several servers can share them: any
    /// [`rig_memory`] store, such as `rig_memory::DirStore` (feature `fs`)
    /// or the `rig-sqlite` and `rig-postgres` stores. Two servers saving one
    /// conversation at once do not lose either turn.
    #[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
    }

    /// Which newest messages of a conversation each request sends the
    /// model, such as `rig_memory::recent::TokenBudget::new(8_000)` or
    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
    /// tool result is never sent without its call.
    #[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()
    }
}

/// Unregisters a task's abort handle when its run is dropped.
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,
        };
        // The task's span: the agent's own spans (model calls, tools) nest
        // under it, and it records how the task ended.
        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;
            }
        };
        // Held until the run ends, however it ends (an abort drops it too).
        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 {
            // Each poll runs inside the scope, so a tool the model calls sees
            // the activation. The run itself does not spawn tasks for tools.
            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)) => {
                    // The answer stands even if the history cannot be saved;
                    // the next turn then starts without this one.
                    if executor.history.append(&ids.context, response.messages.clone()).await.is_err() {
                        tracing::warn!(parent: &span, kind = "store_error", "could not save the conversation");
                    }
                    // The final answer replaces the streamed text, which can
                    // include retried turns and text written before tool calls.
                    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."))));
    }
}

/// The task and context one execution reports on.
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,
        })
    }

    /// A piece of text of the response artifact; see [`Self::artifact`].
    fn chunk(&self, text: String, append: bool, last_chunk: bool) -> StreamResponse {
        self.artifact(vec![Part::text(text)], append, last_chunk)
    }

    /// Parts of the response artifact: appended to the parts before them, or
    /// replacing them when `append` is false.
    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,
        })
    }
}

/// The final answer's parts: its text, then any image the model produced.
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,
            },
            // A provider-side file id or nothing: no bytes to send.
            _ => 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)
}

/// What the caller is told when a run fails: enough to decide whether to
/// retry, without the provider's own error text (which can name internals).
///
/// A failure arrives as the provider's error from an awaited run, or as its
/// report from a streamed one; both carry the status and whether to retry.
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;