Skip to main content

rig_a2a/
client.rs

1//! Remote A2A agents as Rig tools.
2//!
3//! [`RemoteAgent::connect`] reads an agent's card and talks to it in the
4//! protocol version the card declares: v1.0 through the official client, or
5//! v0.3 JSON-RPC for agents that have not upgraded (see [`crate::v03`]).
6//! [`RemoteAgent::stream`] follows an answer as it is written;
7//! [`RemoteAgent::send`] waits for the whole of it. [`RemoteAgent::into_tool`]
8//! turns the agent into a [`DynamicTool`] a Rig agent can call, so a local
9//! agent can delegate to any A2A agent, whatever framework it is written in.
10
11use 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
34/// How long a remote agent may stay silent before a call gives up, unless
35/// told otherwise: the whole wait without streaming, the gap between two
36/// events with it.
37pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
38
39/// Longest tool name most providers accept.
40const MAX_TOOL_NAME: usize = 64;
41/// Largest image a tool result hands the model.
42const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;
43/// Largest text file a tool result inlines.
44const MAX_INLINE_TEXT: usize = 20_000;
45/// Largest agent card read from a remote agent.
46const MAX_CARD_BYTES: usize = 1024 * 1024;
47
48/// Why a remote agent could not be reached or did not answer.
49#[derive(Debug, thiserror::Error)]
50pub enum RemoteError {
51    /// The agent answered with an A2A error.
52    #[error("A2A error {}: {}", .0.code, .0.message)]
53    A2a(#[from] A2AError),
54    /// The HTTP request itself failed.
55    #[error("HTTP: {0}")]
56    Http(#[from] reqwest::Error),
57    /// The agent card is missing or in neither v1.0 nor v0.3 shape.
58    #[error("agent card: {0}")]
59    Card(String),
60    /// The agent stayed silent for longer than the timeout.
61    #[error("no answer within {0:?}")]
62    Timeout(Duration),
63}
64
65/// An A2A agent reached over the network.
66#[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/// Options for [`RemoteAgent`]: a bearer token, extensions to activate, and a timeout.
85#[derive(Debug, Clone)]
86pub struct RemoteAgentBuilder {
87    base_url: String,
88    bearer: Option<String>,
89    extensions: Vec<String>,
90    timeout: Duration,
91}
92
93/// One answer from a remote agent.
94#[derive(Debug, Clone, PartialEq, Default)]
95pub struct Reply {
96    /// The answer's text parts, one per line. A finished task answers in its
97    /// artifacts; a task in any other state, in its status message.
98    pub text: String,
99    /// The answer's structured data parts.
100    pub data: Vec<Value>,
101    /// The answer's file parts.
102    pub files: Vec<RemoteFile>,
103    /// The conversation to send follow-ups in, when the agent gave one.
104    pub context_id: Option<String>,
105    /// The task's state, when the agent answered with a task.
106    pub state: Option<TaskState>,
107}
108
109/// A file in an answer.
110#[derive(Debug, Clone, PartialEq)]
111pub struct RemoteFile {
112    /// The file's name, when the agent gave one.
113    pub name: Option<String>,
114    /// The file's media type, when the agent gave one.
115    pub media_type: Option<String>,
116    /// The file itself, or where to fetch it.
117    pub content: FileContent,
118}
119
120/// Where a [`RemoteFile`]'s bytes are.
121#[derive(Debug, Clone, PartialEq)]
122pub enum FileContent {
123    /// Sent inline.
124    Bytes(Vec<u8>),
125    /// To be fetched from this URL.
126    Url(String),
127}
128
129/// What [`RemoteAgent::stream`] reports while an answer is written.
130#[derive(Debug, Clone, PartialEq)]
131pub enum ReplyEvent {
132    /// The task moved to this state (working, input required, ...).
133    Status(TaskState),
134    /// More answer text, to append to what came before.
135    Text(String),
136    /// The agent rewrote its answer so far; this replaces all text before it.
137    Rewrite(String),
138    /// The whole answer. Always the last event of a stream that did not fail.
139    Done(Reply),
140}
141
142impl RemoteAgent {
143    /// Connect to the agent whose card is under `base_url`, with no
144    /// credentials and the [`DEFAULT_TIMEOUT`]. The card is read up to 1 MiB;
145    /// a larger one is a [`RemoteError::Card`].
146    pub async fn connect(base_url: &str) -> Result<Self, RemoteError> {
147        Self::builder(base_url).connect().await
148    }
149
150    /// Options for connecting to the agent whose card is under `base_url`.
151    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    /// The agent card, in v1.0 shape whatever version the agent speaks.
161    pub fn card(&self) -> &AgentCard {
162        &self.card
163    }
164
165    /// Whether the agent's card says it streams its answers.
166    pub fn streams(&self) -> bool {
167        self.card.capabilities.streaming == Some(true)
168    }
169
170    /// Send `text`, continuing `context_id`'s conversation when given, and
171    /// wait for the whole answer. An agent that streams is followed event by
172    /// event, so a long task that keeps reporting is not cut short; one that
173    /// does not must answer within the timeout.
174    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    /// One request, one response, within the timeout: for agents that do not stream.
192    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    /// Send `text` and follow the answer as it is written: state changes,
218    /// text as it grows, then [`ReplyEvent::Done`] with the whole answer.
219    /// Each event must arrive within the timeout of the one before. An agent
220    /// that does not stream yields its whole answer as one `Done`.
221    ///
222    /// Over A2A v0.3, one event may be 16 MiB before its blank line; a longer
223    /// one ends the stream with an error. A v0.3 `message/send` reply, which
224    /// an agent that does not stream sends instead, is capped at 16 MiB too.
225    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    /// The span one call runs in, from the request until the answer is
262    /// whole. With the `otel` feature, the call carries its trace context.
263    fn call_span(&self) -> tracing::Span {
264        tracing::info_span!("a2a.call", otel.kind = "client", a2a.agent = %self.card.name)
265    }
266
267    /// This agent as a tool named after its card, taking a `message` and an
268    /// optional `context_id` to continue a conversation the tool started.
269    ///
270    /// The model gets the answer as JSON (`reply`, `context_id`, `state`,
271    /// and any `data` and `files`), followed by any image the agent sent.
272    ///
273    /// Returns [`EmptyToolName`] when the tool name is empty, as
274    /// [`Agent::into_tool`](rig_agent::Agent::into_tool) does; a card whose
275    /// name has no usable characters is named `remote_agent` instead.
276    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    /// Send `Authorization: Bearer <token>` with every call.
316    #[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    /// Activate the extension `uri` on every call. Repeat it for more.
323    ///
324    /// A URI already added is ignored, so each one is sent once. The order of
325    /// the first additions is kept.
326    ///
327    /// A v1.0 agent gets the `A2A-Extensions` header and a v0.3 agent the
328    /// `X-A2A-Extensions` header, as the protocol version it declares
329    /// requires. An agent that marks the extension `required` refuses calls
330    /// without it. The card is fetched without it.
331    #[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    /// How long the agent may stay silent; see [`DEFAULT_TIMEOUT`].
341    #[must_use]
342    pub fn timeout(mut self, timeout: Duration) -> Self {
343        self.timeout = timeout;
344        self
345    }
346
347    /// Read the agent card and connect in the version it declares.
348    pub async fn connect(self) -> Result<RemoteAgent, RemoteError> {
349        // No overall request timeout: a stream may rightly last longer. The
350        // agent's silence is bounded per event instead.
351        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                // One header value, comma-separated, on every call.
378                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
414/// Assemble `events` into reply events, giving up when one takes longer than
415/// `timeout`. The call's `span` lasts as long as the stream.
416fn 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        // A stream that stops before the answer is settled is a failure, not
434        // an empty answer: a refused call (401) or a dropped connection ends
435        // the official client's stream the same way.
436        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/// An answer put together from the events that describe it.
447#[derive(Default)]
448struct Assembly {
449    context_id: Option<String>,
450    state: Option<TaskState>,
451    /// The status message of a task that is not working: why it failed, what
452    /// input it needs.
453    status_message: Option<Message>,
454    /// The text of status messages sent while working, in order. Some agents
455    /// (Strands, for one) stream their answer this way before sending it
456    /// whole as an artifact.
457    progress: String,
458    artifacts: Vec<Artifact>,
459    message: Option<Message>,
460    /// The text reported so far, to report only what changed.
461    shown: String,
462}
463
464impl Assembly {
465    /// Take in one event; returns what it changed.
466    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    /// Keep a status message: as progress while the task works, as the
509    /// task's explanation otherwise.
510    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    /// Append `artifact`'s parts to the artifact with its id, or replace it.
521    /// Appended text continues the text part before it.
522    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    /// The answer as the events so far describe it.
547    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        // A finished task answers in its artifacts; a task that failed or
554        // waits on its caller explains itself in its status message; a task
555        // still working shows its artifacts so far, or else its progress.
556        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    /// Whether the events so far hold an answer: a direct message, or a task
572    /// that finished or is waiting on its caller.
573    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
614/// What the model sees of a reply: one JSON block, then the images.
615fn 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
640/// A file as the model reads it: its name and type, its text when it is a
641/// small text file, its URL when it has one. Images also go into `images`,
642/// for the model to look at.
643fn 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
694/// The body of a response, read chunk by chunk; `None` once it passes
695/// `limit` bytes, so a long body is never held whole.
696pub(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
711/// A v0.3 card read as a v1.0 one, for [`RemoteAgent::card`]: one JSON-RPC
712/// interface at its `url`, and its security fields (shaped differently in
713/// v1.0) left out.
714fn 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
747/// A provider-safe tool name from an agent's name: ASCII letters, digits and
748/// `_`, at most 64 characters, never empty.
749fn 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;