1use std::sync::Arc;
12use std::time::Duration;
13
14use a2a::{
15 A2AError, AgentCard, Artifact, Message, Part, PartContent, Role, SendMessageRequest,
16 SendMessageResponse, StreamResponse, TaskState,
17};
18use a2a_client::auth::AuthInterceptor;
19use a2a_client::{A2AClient, A2AClientFactory, Transport};
20use base64::Engine;
21use base64::engine::general_purpose::STANDARD as BASE64;
22use futures::stream::BoxStream;
23use futures::{Stream, StreamExt};
24use rig_core::message::{
25 DocumentSourceKind, EmptyToolName, Image, ImageMediaType, MimeType, ToolName, ToolResultContent,
26};
27use rig_core::tool::{DynamicTool, ToolExecutionError, ToolOutput};
28use rig_core::wasm_compat::WasmBoxedStream;
29use serde::Deserialize;
30use serde_json::{Map, Value, json};
31
32use crate::v03;
33
34pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
38
39const MAX_TOOL_NAME: usize = 64;
41const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;
43const MAX_INLINE_TEXT: usize = 20_000;
45const MAX_CARD_BYTES: usize = 1024 * 1024;
47
48#[derive(Debug, thiserror::Error)]
50pub enum RemoteError {
51 #[error("A2A error {}: {}", .0.code, .0.message)]
53 A2a(#[from] A2AError),
54 #[error("HTTP: {0}")]
56 Http(#[from] reqwest::Error),
57 #[error("agent card: {0}")]
59 Card(String),
60 #[error("no answer within {0:?}")]
62 Timeout(Duration),
63}
64
65#[derive(Clone)]
67pub struct RemoteAgent {
68 card: AgentCard,
69 link: Link,
70 timeout: Duration,
71}
72
73#[derive(Clone)]
74enum Link {
75 V1(Arc<A2AClient<Box<dyn Transport>>>),
76 V03 {
77 http: reqwest::Client,
78 url: String,
79 bearer: Option<String>,
80 extensions: Vec<String>,
81 },
82}
83
84#[derive(Debug, Clone)]
86pub struct RemoteAgentBuilder {
87 base_url: String,
88 bearer: Option<String>,
89 extensions: Vec<String>,
90 timeout: Duration,
91}
92
93#[derive(Debug, Clone, PartialEq, Default)]
95pub struct Reply {
96 pub text: String,
99 pub data: Vec<Value>,
101 pub files: Vec<RemoteFile>,
103 pub context_id: Option<String>,
105 pub state: Option<TaskState>,
107}
108
109#[derive(Debug, Clone, PartialEq)]
111pub struct RemoteFile {
112 pub name: Option<String>,
114 pub media_type: Option<String>,
116 pub content: FileContent,
118}
119
120#[derive(Debug, Clone, PartialEq)]
122pub enum FileContent {
123 Bytes(Vec<u8>),
125 Url(String),
127}
128
129#[derive(Debug, Clone, PartialEq)]
131pub enum ReplyEvent {
132 Status(TaskState),
134 Text(String),
136 Rewrite(String),
138 Done(Reply),
140}
141
142impl RemoteAgent {
143 pub async fn connect(base_url: &str) -> Result<Self, RemoteError> {
147 Self::builder(base_url).connect().await
148 }
149
150 pub fn builder(base_url: impl Into<String>) -> RemoteAgentBuilder {
152 RemoteAgentBuilder {
153 base_url: base_url.into(),
154 bearer: None,
155 extensions: Vec::new(),
156 timeout: DEFAULT_TIMEOUT,
157 }
158 }
159
160 pub fn card(&self) -> &AgentCard {
162 &self.card
163 }
164
165 pub fn streams(&self) -> bool {
167 self.card.capabilities.streaming == Some(true)
168 }
169
170 pub async fn send(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
175 if self.streams() {
176 let mut events = self.stream(text, context_id).await?;
177 while let Some(event) = events.next().await {
178 if let ReplyEvent::Done(reply) = event? {
179 return Ok(reply);
180 }
181 }
182 return Err(A2AError::new(
183 a2a::error_code::INVALID_AGENT_RESPONSE,
184 "the stream ended without an answer",
185 )
186 .into());
187 }
188 self.whole(text, context_id).await
189 }
190
191 async fn whole(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
193 let message = user_message(text, context_id);
194 let answer = async {
195 Ok::<_, RemoteError>(match &self.link {
196 Link::V1(client) => match client.send_message(&request(message)).await? {
197 SendMessageResponse::Task(task) => StreamResponse::Task(task),
198 SendMessageResponse::Message(message) => StreamResponse::Message(message),
199 },
200 Link::V03 {
201 http,
202 url,
203 bearer,
204 extensions,
205 } => v03::send(http, url, bearer.as_deref(), extensions, &message).await?,
206 })
207 };
208 let answer = tracing::Instrument::instrument(answer, self.call_span());
209 let response = tokio::time::timeout(self.timeout, answer)
210 .await
211 .map_err(|_| RemoteError::Timeout(self.timeout))??;
212 let mut assembly = Assembly::default();
213 assembly.apply(response);
214 Ok(assembly.finish())
215 }
216
217 pub async fn stream(
226 &self,
227 text: &str,
228 context_id: Option<&str>,
229 ) -> Result<WasmBoxedStream<'static, Result<ReplyEvent, RemoteError>>, RemoteError> {
230 if !self.streams() {
231 let reply = self.whole(text, context_id).await?;
232 return Ok(Box::pin(futures::stream::iter([Ok(ReplyEvent::Done(
233 reply,
234 ))])));
235 }
236 let message = user_message(text, context_id);
237 let open = async {
238 Ok::<_, RemoteError>(match &self.link {
239 Link::V1(client) => client
240 .send_streaming_message(&request(message))
241 .await?
242 .map(|event| event.map_err(RemoteError::from))
243 .boxed(),
244 Link::V03 {
245 http,
246 url,
247 bearer,
248 extensions,
249 } => v03::stream(http, url, bearer.as_deref(), extensions, &message).await?,
250 })
251 };
252 let timeout = self.timeout;
253 let span = self.call_span();
254 let open = tracing::Instrument::instrument(open, span.clone());
255 let events = tokio::time::timeout(timeout, open)
256 .await
257 .map_err(|_| RemoteError::Timeout(timeout))??;
258 Ok(Box::pin(follow(events, timeout, span)))
259 }
260
261 fn call_span(&self) -> tracing::Span {
264 tracing::info_span!("a2a.call", otel.kind = "client", a2a.agent = %self.card.name)
265 }
266
267 pub fn into_tool(self) -> Result<DynamicTool, EmptyToolName> {
277 let name = ToolName::new(tool_name(&self.card.name))?;
278 let description = tool_description(&self.card);
279 let parameters = json!({
280 "type": "object",
281 "properties": {
282 "message": {
283 "type": "string",
284 "description": "What to ask or tell the agent, self-contained."
285 },
286 "context_id": {
287 "type": "string",
288 "description": "The context_id of an earlier reply, to continue that conversation."
289 }
290 },
291 "required": ["message"],
292 "additionalProperties": false
293 });
294 let tool =
295 DynamicTool::new_with_context(name, description, parameters, move |_context, args| {
296 let agent = self.clone();
297 Box::pin(async move {
298 let args = Args::deserialize(args).map_err(|error| {
299 ToolExecutionError::other(format!("invalid arguments: {error}"))
300 })?;
301 let reply = agent
302 .send(&args.message, args.context_id.as_deref())
303 .await
304 .map_err(|error| {
305 ToolExecutionError::other(format!("remote agent: {error}"))
306 })?;
307 tool_output(&reply)
308 })
309 });
310 Ok(tool)
311 }
312}
313
314impl RemoteAgentBuilder {
315 #[must_use]
317 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
318 self.bearer = Some(token.into());
319 self
320 }
321
322 #[must_use]
332 pub fn extension(mut self, uri: impl Into<String>) -> Self {
333 let uri = uri.into();
334 if !self.extensions.contains(&uri) {
335 self.extensions.push(uri);
336 }
337 self
338 }
339
340 #[must_use]
342 pub fn timeout(mut self, timeout: Duration) -> Self {
343 self.timeout = timeout;
344 self
345 }
346
347 pub async fn connect(self) -> Result<RemoteAgent, RemoteError> {
349 let http = reqwest::Client::builder()
352 .connect_timeout(self.timeout)
353 .build()?;
354 let card_url = format!(
355 "{}{}",
356 self.base_url.trim_end_matches('/'),
357 a2a_server::WELL_KNOWN_AGENT_CARD_PATH
358 );
359 let body = tokio::time::timeout(self.timeout, async {
360 let response = http.get(&card_url).send().await?.error_for_status()?;
361 read_capped(response, MAX_CARD_BYTES).await
362 })
363 .await
364 .map_err(|_| RemoteError::Timeout(self.timeout))??
365 .ok_or_else(|| RemoteError::Card(format!("larger than {MAX_CARD_BYTES} bytes")))?;
366 let card: Value = serde_json::from_slice(&body)
367 .map_err(|e| RemoteError::Card(format!("not JSON: {e}")))?;
368
369 if card.get("supportedInterfaces").is_some() {
370 let card: AgentCard = serde_json::from_value(card)
371 .map_err(|e| RemoteError::Card(format!("not a v1.0 card: {e}")))?;
372 let mut factory = A2AClientFactory::builder();
373 if let Some(token) = &self.bearer {
374 factory = factory.with_interceptor(Arc::new(AuthInterceptor::bearer(token)));
375 }
376 if !self.extensions.is_empty() {
377 let uris = self.extensions.join(", ");
379 factory = factory.with_interceptor(Arc::new(AuthInterceptor::custom(
380 a2a::SVC_PARAM_EXTENSIONS,
381 uris,
382 )));
383 }
384 #[cfg(feature = "otel")]
385 {
386 factory = factory.with_interceptor(Arc::new(crate::otel::TraceContext));
387 }
388 let client = factory.build().create_from_card(&card).await?;
389 return Ok(RemoteAgent {
390 card,
391 link: Link::V1(Arc::new(client)),
392 timeout: self.timeout,
393 });
394 }
395
396 let Some(url) = card.get("url").and_then(Value::as_str).map(str::to_owned) else {
397 return Err(RemoteError::Card(
398 "neither `supportedInterfaces` (v1.0) nor `url` (v0.3)".into(),
399 ));
400 };
401 Ok(RemoteAgent {
402 card: v1_card_from_v03(card, &url)?,
403 link: Link::V03 {
404 http,
405 url,
406 bearer: self.bearer,
407 extensions: self.extensions,
408 },
409 timeout: self.timeout,
410 })
411 }
412}
413
414fn follow(
417 mut events: BoxStream<'static, Result<StreamResponse, RemoteError>>,
418 timeout: Duration,
419 span: tracing::Span,
420) -> impl Stream<Item = Result<ReplyEvent, RemoteError>> + Send + 'static {
421 async_stream::try_stream! {
422 let _span = span;
423 let mut assembly = Assembly::default();
424 loop {
425 let next = tokio::time::timeout(timeout, events.next())
426 .await
427 .map_err(|_| RemoteError::Timeout(timeout))?;
428 let Some(event) = next else { break };
429 for reply_event in assembly.apply(event?) {
430 yield reply_event;
431 }
432 }
433 if !assembly.settled() {
437 Err(A2AError::new(
438 a2a::error_code::INVALID_AGENT_RESPONSE,
439 "the stream ended before the agent answered (refused, or the connection dropped)",
440 ))?;
441 }
442 yield ReplyEvent::Done(assembly.finish());
443 }
444}
445
446#[derive(Default)]
448struct Assembly {
449 context_id: Option<String>,
450 state: Option<TaskState>,
451 status_message: Option<Message>,
454 progress: String,
458 artifacts: Vec<Artifact>,
459 message: Option<Message>,
460 shown: String,
462}
463
464impl Assembly {
465 fn apply(&mut self, event: StreamResponse) -> Vec<ReplyEvent> {
467 let mut changes = Vec::new();
468 let mut set_state = |state: TaskState, assembly: &mut Self| {
469 if assembly.state.as_ref() != Some(&state) {
470 assembly.state = Some(state.clone());
471 changes.push(ReplyEvent::Status(state));
472 }
473 };
474 match event {
475 StreamResponse::Task(task) => {
476 self.context_id = Some(task.context_id);
477 self.artifacts = task.artifacts.unwrap_or_default();
478 self.note(&task.status.state, task.status.message);
479 set_state(task.status.state, self);
480 }
481 StreamResponse::Message(message) => {
482 if message.context_id.is_some() {
483 self.context_id = message.context_id.clone();
484 }
485 self.message = Some(message);
486 }
487 StreamResponse::StatusUpdate(update) => {
488 self.context_id = Some(update.context_id);
489 self.note(&update.status.state, update.status.message);
490 set_state(update.status.state, self);
491 }
492 StreamResponse::ArtifactUpdate(update) => {
493 self.context_id = Some(update.context_id);
494 self.merge(update.artifact, update.append.unwrap_or(false));
495 }
496 }
497 let text = self.current().text;
498 if text != self.shown {
499 changes.push(match text.strip_prefix(self.shown.as_str()) {
500 Some(more) => ReplyEvent::Text(more.to_owned()),
501 None => ReplyEvent::Rewrite(text.clone()),
502 });
503 self.shown = text;
504 }
505 changes
506 }
507
508 fn note(&mut self, state: &TaskState, message: Option<Message>) {
511 let Some(message) = message else { return };
512 if matches!(state, TaskState::Working | TaskState::Submitted) {
513 let text: Vec<&str> = message.parts.iter().filter_map(Part::as_text).collect();
514 self.progress.push_str(&text.concat());
515 } else {
516 self.status_message = Some(message);
517 }
518 }
519
520 fn merge(&mut self, artifact: Artifact, append: bool) {
523 let Some(existing) = self
524 .artifacts
525 .iter_mut()
526 .find(|known| known.artifact_id == artifact.artifact_id)
527 else {
528 self.artifacts.push(artifact);
529 return;
530 };
531 if !append {
532 *existing = artifact;
533 return;
534 }
535 for part in artifact.parts {
536 match (existing.parts.last_mut(), &part.content) {
537 (Some(last), PartContent::Text(more)) => match &mut last.content {
538 PartContent::Text(text) => text.push_str(more),
539 _ => existing.parts.push(part),
540 },
541 _ => existing.parts.push(part),
542 }
543 }
544 }
545
546 fn current(&self) -> Reply {
548 if let Some(message) = &self.message {
549 return reply_from_parts(message.parts.iter(), self.context_id.clone(), None);
550 }
551 let (context_id, state) = (self.context_id.clone(), self.state.clone());
552 let artifact_parts = self.artifacts.iter().flat_map(|artifact| &artifact.parts);
553 let finished = self.state == Some(TaskState::Completed);
557 if (finished || self.status_message.is_none()) && artifact_parts.clone().next().is_some() {
558 return reply_from_parts(artifact_parts, context_id, state);
559 }
560 if let Some(message) = &self.status_message {
561 return reply_from_parts(message.parts.iter(), context_id, state);
562 }
563 Reply {
564 text: self.progress.clone(),
565 context_id,
566 state,
567 ..Reply::default()
568 }
569 }
570
571 fn settled(&self) -> bool {
574 self.message.is_some()
575 || self.state.as_ref().is_some_and(|state| {
576 state.is_terminal()
577 || matches!(state, TaskState::InputRequired | TaskState::AuthRequired)
578 })
579 }
580
581 fn finish(self) -> Reply {
582 self.current()
583 }
584}
585
586fn reply_from_parts<'a>(
587 parts: impl Iterator<Item = &'a Part>,
588 context_id: Option<String>,
589 state: Option<TaskState>,
590) -> Reply {
591 let mut reply = Reply {
592 context_id,
593 state,
594 ..Reply::default()
595 };
596 let mut lines = Vec::new();
597 for part in parts {
598 let file = |content| RemoteFile {
599 name: part.filename.clone(),
600 media_type: part.media_type.clone(),
601 content,
602 };
603 match &part.content {
604 PartContent::Text(text) => lines.push(text.as_str()),
605 PartContent::Data(data) => reply.data.push(data.clone()),
606 PartContent::Raw(bytes) => reply.files.push(file(FileContent::Bytes(bytes.clone()))),
607 PartContent::Url(url) => reply.files.push(file(FileContent::Url(url.clone()))),
608 }
609 }
610 reply.text = lines.join("\n");
611 reply
612}
613
614fn tool_output(reply: &Reply) -> Result<ToolOutput, ToolExecutionError> {
616 let mut images = Vec::new();
617 let files: Vec<Value> = reply
618 .files
619 .iter()
620 .map(|file| describe_file(file, &mut images))
621 .collect();
622 let mut summary = Map::new();
623 summary.insert("reply".into(), json!(reply.text));
624 summary.insert("context_id".into(), json!(reply.context_id));
625 summary.insert(
626 "state".into(),
627 json!(reply.state.as_ref().map(v03::state_name)),
628 );
629 if !reply.data.is_empty() {
630 summary.insert("data".into(), json!(reply.data));
631 }
632 if !files.is_empty() {
633 summary.insert("files".into(), json!(files));
634 }
635 let mut content = vec![ToolResultContent::json(Value::Object(summary))];
636 content.extend(images);
637 ToolOutput::content(content)
638}
639
640fn describe_file(file: &RemoteFile, images: &mut Vec<ToolResultContent>) -> Value {
644 let mut described = Map::new();
645 described.insert("name".into(), json!(file.name));
646 described.insert("media_type".into(), json!(file.media_type));
647 let image_kind = |bytes: Option<&[u8]>| {
648 file.media_type
649 .as_deref()
650 .and_then(ImageMediaType::from_mime_type)
651 .or_else(|| bytes.and_then(ImageMediaType::sniff))
652 };
653 let image = |data, kind| {
654 ToolResultContent::Image(Image {
655 data,
656 media_type: Some(kind),
657 ..Default::default()
658 })
659 };
660 match &file.content {
661 FileContent::Url(url) => {
662 described.insert("url".into(), json!(url));
663 if let Some(kind) = image_kind(None) {
664 images.push(image(DocumentSourceKind::url(url), kind));
665 described.insert("shown".into(), json!("as an image below"));
666 }
667 }
668 FileContent::Bytes(bytes) => {
669 described.insert("size_bytes".into(), json!(bytes.len()));
670 let texty = file
671 .media_type
672 .as_deref()
673 .is_none_or(|media| media.starts_with("text/") || media == "application/json");
674 match (image_kind(Some(bytes)), std::str::from_utf8(bytes)) {
675 (Some(kind), _) if bytes.len() <= MAX_IMAGE_BYTES => {
676 images.push(image(
677 DocumentSourceKind::base64(BASE64.encode(bytes)),
678 kind,
679 ));
680 described.insert("shown".into(), json!("as an image below"));
681 }
682 (None, Ok(text)) if texty && bytes.len() <= MAX_INLINE_TEXT => {
683 described.insert("text".into(), json!(text));
684 }
685 _ => {
686 described.insert("shown".into(), json!("not shown: binary or too large"));
687 }
688 }
689 }
690 }
691 Value::Object(described)
692}
693
694pub(crate) async fn read_capped(
697 response: reqwest::Response,
698 limit: usize,
699) -> Result<Option<Vec<u8>>, reqwest::Error> {
700 let mut body = Vec::new();
701 let mut chunks = response.bytes_stream();
702 while let Some(chunk) = chunks.next().await {
703 body.extend_from_slice(&chunk?);
704 if body.len() > limit {
705 return Ok(None);
706 }
707 }
708 Ok(Some(body))
709}
710
711fn v1_card_from_v03(mut card: Value, url: &str) -> Result<AgentCard, RemoteError> {
715 if let Some(fields) = card.as_object_mut() {
716 fields.remove("securitySchemes");
717 fields.remove("security");
718 fields.insert(
719 "supportedInterfaces".into(),
720 json!([{"url": url, "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}]),
721 );
722 }
723 serde_json::from_value(card).map_err(|e| RemoteError::Card(format!("not a v0.3 card: {e}")))
724}
725
726fn user_message(text: &str, context_id: Option<&str>) -> Message {
727 let mut message = Message::new(Role::User, vec![Part::text(text)]);
728 message.context_id = context_id.map(str::to_owned);
729 message
730}
731
732fn request(message: Message) -> SendMessageRequest {
733 SendMessageRequest {
734 message,
735 configuration: None,
736 metadata: None,
737 tenant: None,
738 }
739}
740
741#[derive(Deserialize)]
742struct Args {
743 message: String,
744 context_id: Option<String>,
745}
746
747fn tool_name(agent_name: &str) -> String {
750 let mut name: String = agent_name
751 .trim()
752 .chars()
753 .map(|c| {
754 if c.is_ascii_alphanumeric() {
755 c.to_ascii_lowercase()
756 } else {
757 '_'
758 }
759 })
760 .collect();
761 name.truncate(MAX_TOOL_NAME);
762 let name = name.trim_matches('_');
763 if name.is_empty() {
764 "remote_agent".to_owned()
765 } else {
766 name.to_owned()
767 }
768}
769
770fn tool_description(card: &AgentCard) -> String {
771 let skills: Vec<String> = card
772 .skills
773 .iter()
774 .map(|skill| format!("- {}: {}", skill.name, skill.description))
775 .collect();
776 format!(
777 "Delegate to the remote agent \"{}\" (A2A). {}\nSkills:\n{}\n\
778 Pass the context_id of an earlier reply to continue the same conversation.",
779 card.name,
780 card.description,
781 skills.join("\n")
782 )
783}
784
785#[cfg(test)]
786mod tests;