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;
45
46#[derive(Debug, thiserror::Error)]
48pub enum RemoteError {
49 #[error("A2A error {}: {}", .0.code, .0.message)]
51 A2a(#[from] A2AError),
52 #[error("HTTP: {0}")]
54 Http(#[from] reqwest::Error),
55 #[error("agent card: {0}")]
57 Card(String),
58 #[error("no answer within {0:?}")]
60 Timeout(Duration),
61}
62
63#[derive(Clone)]
65pub struct RemoteAgent {
66 card: AgentCard,
67 link: Link,
68 timeout: Duration,
69}
70
71#[derive(Clone)]
72enum Link {
73 V1(Arc<A2AClient<Box<dyn Transport>>>),
74 V03 {
75 http: reqwest::Client,
76 url: String,
77 bearer: Option<String>,
78 },
79}
80
81#[derive(Debug, Clone)]
83pub struct RemoteAgentBuilder {
84 base_url: String,
85 bearer: Option<String>,
86 timeout: Duration,
87}
88
89#[derive(Debug, Clone, PartialEq, Default)]
91pub struct Reply {
92 pub text: String,
95 pub data: Vec<Value>,
97 pub files: Vec<RemoteFile>,
99 pub context_id: Option<String>,
101 pub state: Option<TaskState>,
103}
104
105#[derive(Debug, Clone, PartialEq)]
107pub struct RemoteFile {
108 pub name: Option<String>,
110 pub media_type: Option<String>,
112 pub content: FileContent,
114}
115
116#[derive(Debug, Clone, PartialEq)]
118pub enum FileContent {
119 Bytes(Vec<u8>),
121 Url(String),
123}
124
125#[derive(Debug, Clone, PartialEq)]
127pub enum ReplyEvent {
128 Status(TaskState),
130 Text(String),
132 Rewrite(String),
134 Done(Reply),
136}
137
138impl RemoteAgent {
139 pub async fn connect(base_url: &str) -> Result<Self, RemoteError> {
142 Self::builder(base_url).connect().await
143 }
144
145 pub fn builder(base_url: impl Into<String>) -> RemoteAgentBuilder {
147 RemoteAgentBuilder {
148 base_url: base_url.into(),
149 bearer: None,
150 timeout: DEFAULT_TIMEOUT,
151 }
152 }
153
154 pub fn card(&self) -> &AgentCard {
156 &self.card
157 }
158
159 pub fn streams(&self) -> bool {
161 self.card.capabilities.streaming == Some(true)
162 }
163
164 pub async fn send(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
169 if self.streams() {
170 let mut events = self.stream(text, context_id).await?;
171 while let Some(event) = events.next().await {
172 if let ReplyEvent::Done(reply) = event? {
173 return Ok(reply);
174 }
175 }
176 return Err(A2AError::new(
177 a2a::error_code::INVALID_AGENT_RESPONSE,
178 "the stream ended without an answer",
179 )
180 .into());
181 }
182 self.whole(text, context_id).await
183 }
184
185 async fn whole(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
187 let message = user_message(text, context_id);
188 let answer = async {
189 Ok::<_, RemoteError>(match &self.link {
190 Link::V1(client) => match client.send_message(&request(message)).await? {
191 SendMessageResponse::Task(task) => StreamResponse::Task(task),
192 SendMessageResponse::Message(message) => StreamResponse::Message(message),
193 },
194 Link::V03 { http, url, bearer } => {
195 v03::send(http, url, bearer.as_deref(), &message).await?
196 }
197 })
198 };
199 let answer = tracing::Instrument::instrument(answer, self.call_span());
200 let response = tokio::time::timeout(self.timeout, answer)
201 .await
202 .map_err(|_| RemoteError::Timeout(self.timeout))??;
203 let mut assembly = Assembly::default();
204 assembly.apply(response);
205 Ok(assembly.finish())
206 }
207
208 pub async fn stream(
213 &self,
214 text: &str,
215 context_id: Option<&str>,
216 ) -> Result<WasmBoxedStream<'static, Result<ReplyEvent, RemoteError>>, RemoteError> {
217 if !self.streams() {
218 let reply = self.whole(text, context_id).await?;
219 return Ok(Box::pin(futures::stream::iter([Ok(ReplyEvent::Done(
220 reply,
221 ))])));
222 }
223 let message = user_message(text, context_id);
224 let open = async {
225 Ok::<_, RemoteError>(match &self.link {
226 Link::V1(client) => client
227 .send_streaming_message(&request(message))
228 .await?
229 .map(|event| event.map_err(RemoteError::from))
230 .boxed(),
231 Link::V03 { http, url, bearer } => {
232 v03::stream(http, url, bearer.as_deref(), &message).await?
233 }
234 })
235 };
236 let timeout = self.timeout;
237 let span = self.call_span();
238 let open = tracing::Instrument::instrument(open, span.clone());
239 let events = tokio::time::timeout(timeout, open)
240 .await
241 .map_err(|_| RemoteError::Timeout(timeout))??;
242 Ok(Box::pin(follow(events, timeout, span)))
243 }
244
245 fn call_span(&self) -> tracing::Span {
248 tracing::info_span!("a2a.call", otel.kind = "client", a2a.agent = %self.card.name)
249 }
250
251 pub fn into_tool(self) -> Result<DynamicTool, EmptyToolName> {
261 let name = ToolName::new(tool_name(&self.card.name))?;
262 let description = tool_description(&self.card);
263 let parameters = json!({
264 "type": "object",
265 "properties": {
266 "message": {
267 "type": "string",
268 "description": "What to ask or tell the agent, self-contained."
269 },
270 "context_id": {
271 "type": "string",
272 "description": "The context_id of an earlier reply, to continue that conversation."
273 }
274 },
275 "required": ["message"],
276 "additionalProperties": false
277 });
278 let tool =
279 DynamicTool::new_with_context(name, description, parameters, move |_context, args| {
280 let agent = self.clone();
281 Box::pin(async move {
282 let args = Args::deserialize(args).map_err(|error| {
283 ToolExecutionError::other(format!("invalid arguments: {error}"))
284 })?;
285 let reply = agent
286 .send(&args.message, args.context_id.as_deref())
287 .await
288 .map_err(|error| {
289 ToolExecutionError::other(format!("remote agent: {error}"))
290 })?;
291 tool_output(&reply)
292 })
293 });
294 Ok(tool)
295 }
296}
297
298impl RemoteAgentBuilder {
299 #[must_use]
301 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
302 self.bearer = Some(token.into());
303 self
304 }
305
306 #[must_use]
308 pub fn timeout(mut self, timeout: Duration) -> Self {
309 self.timeout = timeout;
310 self
311 }
312
313 pub async fn connect(self) -> Result<RemoteAgent, RemoteError> {
315 let http = reqwest::Client::builder()
318 .connect_timeout(self.timeout)
319 .build()?;
320 let card_url = format!(
321 "{}{}",
322 self.base_url.trim_end_matches('/'),
323 a2a_server::WELL_KNOWN_AGENT_CARD_PATH
324 );
325 let card: Value = tokio::time::timeout(self.timeout, async {
326 http.get(&card_url)
327 .send()
328 .await?
329 .error_for_status()?
330 .json()
331 .await
332 })
333 .await
334 .map_err(|_| RemoteError::Timeout(self.timeout))??;
335
336 if card.get("supportedInterfaces").is_some() {
337 let card: AgentCard = serde_json::from_value(card)
338 .map_err(|e| RemoteError::Card(format!("not a v1.0 card: {e}")))?;
339 let mut factory = A2AClientFactory::builder();
340 if let Some(token) = &self.bearer {
341 factory = factory.with_interceptor(Arc::new(AuthInterceptor::bearer(token)));
342 }
343 #[cfg(feature = "otel")]
344 {
345 factory = factory.with_interceptor(Arc::new(crate::otel::TraceContext));
346 }
347 let client = factory.build().create_from_card(&card).await?;
348 return Ok(RemoteAgent {
349 card,
350 link: Link::V1(Arc::new(client)),
351 timeout: self.timeout,
352 });
353 }
354
355 let Some(url) = card.get("url").and_then(Value::as_str).map(str::to_owned) else {
356 return Err(RemoteError::Card(
357 "neither `supportedInterfaces` (v1.0) nor `url` (v0.3)".into(),
358 ));
359 };
360 Ok(RemoteAgent {
361 card: v1_card_from_v03(card, &url)?,
362 link: Link::V03 {
363 http,
364 url,
365 bearer: self.bearer,
366 },
367 timeout: self.timeout,
368 })
369 }
370}
371
372fn follow(
375 mut events: BoxStream<'static, Result<StreamResponse, RemoteError>>,
376 timeout: Duration,
377 span: tracing::Span,
378) -> impl Stream<Item = Result<ReplyEvent, RemoteError>> + Send + 'static {
379 async_stream::try_stream! {
380 let _span = span;
381 let mut assembly = Assembly::default();
382 loop {
383 let next = tokio::time::timeout(timeout, events.next())
384 .await
385 .map_err(|_| RemoteError::Timeout(timeout))?;
386 let Some(event) = next else { break };
387 for reply_event in assembly.apply(event?) {
388 yield reply_event;
389 }
390 }
391 if !assembly.settled() {
395 Err(A2AError::new(
396 a2a::error_code::INVALID_AGENT_RESPONSE,
397 "the stream ended before the agent answered (refused, or the connection dropped)",
398 ))?;
399 }
400 yield ReplyEvent::Done(assembly.finish());
401 }
402}
403
404#[derive(Default)]
406struct Assembly {
407 context_id: Option<String>,
408 state: Option<TaskState>,
409 status_message: Option<Message>,
412 progress: String,
416 artifacts: Vec<Artifact>,
417 message: Option<Message>,
418 shown: String,
420}
421
422impl Assembly {
423 fn apply(&mut self, event: StreamResponse) -> Vec<ReplyEvent> {
425 let mut changes = Vec::new();
426 let mut set_state = |state: TaskState, assembly: &mut Self| {
427 if assembly.state.as_ref() != Some(&state) {
428 assembly.state = Some(state.clone());
429 changes.push(ReplyEvent::Status(state));
430 }
431 };
432 match event {
433 StreamResponse::Task(task) => {
434 self.context_id = Some(task.context_id);
435 self.artifacts = task.artifacts.unwrap_or_default();
436 self.note(&task.status.state, task.status.message);
437 set_state(task.status.state, self);
438 }
439 StreamResponse::Message(message) => {
440 if message.context_id.is_some() {
441 self.context_id = message.context_id.clone();
442 }
443 self.message = Some(message);
444 }
445 StreamResponse::StatusUpdate(update) => {
446 self.context_id = Some(update.context_id);
447 self.note(&update.status.state, update.status.message);
448 set_state(update.status.state, self);
449 }
450 StreamResponse::ArtifactUpdate(update) => {
451 self.context_id = Some(update.context_id);
452 self.merge(update.artifact, update.append.unwrap_or(false));
453 }
454 }
455 let text = self.current().text;
456 if text != self.shown {
457 changes.push(match text.strip_prefix(self.shown.as_str()) {
458 Some(more) => ReplyEvent::Text(more.to_owned()),
459 None => ReplyEvent::Rewrite(text.clone()),
460 });
461 self.shown = text;
462 }
463 changes
464 }
465
466 fn note(&mut self, state: &TaskState, message: Option<Message>) {
469 let Some(message) = message else { return };
470 if matches!(state, TaskState::Working | TaskState::Submitted) {
471 let text: Vec<&str> = message.parts.iter().filter_map(Part::as_text).collect();
472 self.progress.push_str(&text.concat());
473 } else {
474 self.status_message = Some(message);
475 }
476 }
477
478 fn merge(&mut self, artifact: Artifact, append: bool) {
481 let Some(existing) = self
482 .artifacts
483 .iter_mut()
484 .find(|known| known.artifact_id == artifact.artifact_id)
485 else {
486 self.artifacts.push(artifact);
487 return;
488 };
489 if !append {
490 *existing = artifact;
491 return;
492 }
493 for part in artifact.parts {
494 match (existing.parts.last_mut(), &part.content) {
495 (Some(last), PartContent::Text(more)) => match &mut last.content {
496 PartContent::Text(text) => text.push_str(more),
497 _ => existing.parts.push(part),
498 },
499 _ => existing.parts.push(part),
500 }
501 }
502 }
503
504 fn current(&self) -> Reply {
506 if let Some(message) = &self.message {
507 return reply_from_parts(message.parts.iter(), self.context_id.clone(), None);
508 }
509 let (context_id, state) = (self.context_id.clone(), self.state.clone());
510 let artifact_parts = self.artifacts.iter().flat_map(|artifact| &artifact.parts);
511 let finished = self.state == Some(TaskState::Completed);
515 if (finished || self.status_message.is_none()) && artifact_parts.clone().next().is_some() {
516 return reply_from_parts(artifact_parts, context_id, state);
517 }
518 if let Some(message) = &self.status_message {
519 return reply_from_parts(message.parts.iter(), context_id, state);
520 }
521 Reply {
522 text: self.progress.clone(),
523 context_id,
524 state,
525 ..Reply::default()
526 }
527 }
528
529 fn settled(&self) -> bool {
532 self.message.is_some()
533 || self.state.as_ref().is_some_and(|state| {
534 state.is_terminal()
535 || matches!(state, TaskState::InputRequired | TaskState::AuthRequired)
536 })
537 }
538
539 fn finish(self) -> Reply {
540 self.current()
541 }
542}
543
544fn reply_from_parts<'a>(
545 parts: impl Iterator<Item = &'a Part>,
546 context_id: Option<String>,
547 state: Option<TaskState>,
548) -> Reply {
549 let mut reply = Reply {
550 context_id,
551 state,
552 ..Reply::default()
553 };
554 let mut lines = Vec::new();
555 for part in parts {
556 let file = |content| RemoteFile {
557 name: part.filename.clone(),
558 media_type: part.media_type.clone(),
559 content,
560 };
561 match &part.content {
562 PartContent::Text(text) => lines.push(text.as_str()),
563 PartContent::Data(data) => reply.data.push(data.clone()),
564 PartContent::Raw(bytes) => reply.files.push(file(FileContent::Bytes(bytes.clone()))),
565 PartContent::Url(url) => reply.files.push(file(FileContent::Url(url.clone()))),
566 }
567 }
568 reply.text = lines.join("\n");
569 reply
570}
571
572fn tool_output(reply: &Reply) -> Result<ToolOutput, ToolExecutionError> {
574 let mut images = Vec::new();
575 let files: Vec<Value> = reply
576 .files
577 .iter()
578 .map(|file| describe_file(file, &mut images))
579 .collect();
580 let mut summary = Map::new();
581 summary.insert("reply".into(), json!(reply.text));
582 summary.insert("context_id".into(), json!(reply.context_id));
583 summary.insert(
584 "state".into(),
585 json!(reply.state.as_ref().map(v03::state_name)),
586 );
587 if !reply.data.is_empty() {
588 summary.insert("data".into(), json!(reply.data));
589 }
590 if !files.is_empty() {
591 summary.insert("files".into(), json!(files));
592 }
593 let mut content = vec![ToolResultContent::json(Value::Object(summary))];
594 content.extend(images);
595 ToolOutput::content(content)
596}
597
598fn describe_file(file: &RemoteFile, images: &mut Vec<ToolResultContent>) -> Value {
602 let mut described = Map::new();
603 described.insert("name".into(), json!(file.name));
604 described.insert("media_type".into(), json!(file.media_type));
605 let image_kind = |bytes: Option<&[u8]>| {
606 file.media_type
607 .as_deref()
608 .and_then(ImageMediaType::from_mime_type)
609 .or_else(|| bytes.and_then(ImageMediaType::sniff))
610 };
611 let image = |data, kind| {
612 ToolResultContent::Image(Image {
613 data,
614 media_type: Some(kind),
615 ..Default::default()
616 })
617 };
618 match &file.content {
619 FileContent::Url(url) => {
620 described.insert("url".into(), json!(url));
621 if let Some(kind) = image_kind(None) {
622 images.push(image(DocumentSourceKind::url(url), kind));
623 described.insert("shown".into(), json!("as an image below"));
624 }
625 }
626 FileContent::Bytes(bytes) => {
627 described.insert("size_bytes".into(), json!(bytes.len()));
628 let texty = file
629 .media_type
630 .as_deref()
631 .is_none_or(|media| media.starts_with("text/") || media == "application/json");
632 match (image_kind(Some(bytes)), std::str::from_utf8(bytes)) {
633 (Some(kind), _) if bytes.len() <= MAX_IMAGE_BYTES => {
634 images.push(image(
635 DocumentSourceKind::base64(BASE64.encode(bytes)),
636 kind,
637 ));
638 described.insert("shown".into(), json!("as an image below"));
639 }
640 (None, Ok(text)) if texty && bytes.len() <= MAX_INLINE_TEXT => {
641 described.insert("text".into(), json!(text));
642 }
643 _ => {
644 described.insert("shown".into(), json!("not shown: binary or too large"));
645 }
646 }
647 }
648 }
649 Value::Object(described)
650}
651
652fn v1_card_from_v03(mut card: Value, url: &str) -> Result<AgentCard, RemoteError> {
656 if let Some(fields) = card.as_object_mut() {
657 fields.remove("securitySchemes");
658 fields.remove("security");
659 fields.insert(
660 "supportedInterfaces".into(),
661 json!([{"url": url, "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}]),
662 );
663 }
664 serde_json::from_value(card).map_err(|e| RemoteError::Card(format!("not a v0.3 card: {e}")))
665}
666
667fn user_message(text: &str, context_id: Option<&str>) -> Message {
668 let mut message = Message::new(Role::User, vec![Part::text(text)]);
669 message.context_id = context_id.map(str::to_owned);
670 message
671}
672
673fn request(message: Message) -> SendMessageRequest {
674 SendMessageRequest {
675 message,
676 configuration: None,
677 metadata: None,
678 tenant: None,
679 }
680}
681
682#[derive(Deserialize)]
683struct Args {
684 message: String,
685 context_id: Option<String>,
686}
687
688fn tool_name(agent_name: &str) -> String {
691 let mut name: String = agent_name
692 .trim()
693 .chars()
694 .map(|c| {
695 if c.is_ascii_alphanumeric() {
696 c.to_ascii_lowercase()
697 } else {
698 '_'
699 }
700 })
701 .collect();
702 name.truncate(MAX_TOOL_NAME);
703 let name = name.trim_matches('_');
704 if name.is_empty() {
705 "remote_agent".to_owned()
706 } else {
707 name.to_owned()
708 }
709}
710
711fn tool_description(card: &AgentCard) -> String {
712 let skills: Vec<String> = card
713 .skills
714 .iter()
715 .map(|skill| format!("- {}: {}", skill.name, skill.description))
716 .collect();
717 format!(
718 "Delegate to the remote agent \"{}\" (A2A). {}\nSkills:\n{}\n\
719 Pass the context_id of an earlier reply to continue the same conversation.",
720 card.name,
721 card.description,
722 skills.join("\n")
723 )
724}
725
726#[cfg(test)]
727mod tests;