Skip to main content

rusty_agent_runtime/
a2a.rs

1//! A2A (Agent2Agent) client support: [`A2aNode`], the durable half of the
2//! A2A bridge (R0.9 Rusty Capsules, wave 4).
3//!
4//! An [`A2aNode`] is registered in a graph exactly like any local node —
5//! the [`RemoteNode`](crate::remote::RemoteNode) precedent: *one `Node`
6//! trait, remote agents behind the same trait*. When the executor runs it,
7//! the node's state snapshot is sent to the remote agent's `POST {base}/a2a`
8//! JSON-RPC endpoint as a `message/send`, the resulting A2A **task** is
9//! polled (`tasks/get`) to a terminal state, and the task's artifacts become
10//! the node's output. `tasks/cancel` propagates run cancellation to the
11//! remote task.
12//!
13//! ## Evidence and the trust posture
14//!
15//! Every delegation is journaled as one [`RunEventKind::RemoteCall`]
16//! event — the canonical replay-servable kind — carrying the exact request
17//! params as input and the terminal task as output. The boundary is the
18//! honest one: **what we sent and what came back is our evidence; the
19//! remote agent's conduct is its own receipt's problem.** A2A gives the
20//! caller no window into the callee's internals, and this module pretends
21//! otherwise nowhere. Replaying ([`A2aNode::replaying`]) serves the
22//! journaled outcome from the recorded journal and holds no HTTP client —
23//! a replayed run issues no outbound calls by construction.
24//!
25//! ## Idempotency
26//!
27//! The A2A `messageId` is the delegation's idempotency handle: derived as
28//! `a2a-{thread_id}-{step}-{node_name}`, it is stable across executor-level
29//! re-execution of the same super-step, so a server that dedupes on
30//! `messageId` (rusty-agent-server's bridge does, mapping it onto the durable
31//! task queue's idempotency key) turns a resubmission into the same task
32//! rather than a second one. The assigned task id then names the remote
33//! work for polling and cancellation.
34//!
35//! ## Spec pin
36//!
37//! [`A2A_PROTOCOL_VERSION`] pins the A2A revision this client speaks
38//! (recorded in requests, not negotiated — the same discipline as
39//! [`MCP_PROTOCOL_VERSION`](crate::mcp::MCP_PROTOCOL_VERSION)): `0.3.0`
40//! renamed the well-known Agent Card path and settled the task/artifact
41//! shapes this module relies on. A second revision lands as additive
42//! evolution, never a rewrite of the pinned shapes.
43
44use std::time::Duration;
45
46use async_trait::async_trait;
47use serde_json::{json, Value};
48
49use crate::error::{Result, RustyError};
50use crate::journal::{Journal, PARENT_EVENT_KEY};
51use crate::llm::backoff_delay;
52use crate::node::{Node, NodeContext, NodeOutput};
53use crate::record::{Effect, EventStatus, RunEventKind};
54use crate::replay::ReplaySource;
55
56/// The A2A spec revision this client speaks (see the module docs). Sent as
57/// the request's `protocolVersion`; the server's revision is recorded in
58/// the journaled task, not validated.
59pub const A2A_PROTOCOL_VERSION: &str = "0.3.0";
60
61/// Default per-request HTTP timeout.
62pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
63
64/// Default number of retries *after* the initial attempt (transport-class
65/// failures only — a JSON-RPC error is the server's definitive answer).
66pub const DEFAULT_MAX_RETRIES: u32 = 2;
67
68/// Default base delay for exponential backoff between retries.
69pub const DEFAULT_BASE_BACKOFF: Duration = Duration::from_millis(100);
70
71/// Default interval between `tasks/get` polls while the remote task runs.
72pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
73
74/// A node's delegation to a remote A2A agent, behind the same [`Node`]
75/// trait as a local node.
76///
77/// **Error semantics across the wire.** A task the remote agent settles
78/// `failed` flattens to [`RustyError::Node`] — a hard, non-retryable
79/// failure, the [`RemoteNode`](crate::remote::RemoteNode) rule: the callee
80/// already made a definitive decision, and retry classification does not
81/// survive a process boundary. This client's own retries cover
82/// transport-class failures only (connect errors, timeouts, HTTP 5xx / 408
83/// / 429 — see the module docs). A task found `canceled` on poll (someone
84/// else cancelled it) is likewise definitive.
85///
86/// ```no_run
87/// use std::time::Duration;
88/// use rusty_agent_runtime::a2a::A2aNode;
89/// use rusty_agent_runtime::graph::GraphBuilder;
90///
91/// let node = A2aNode::new("researcher", "http://127.0.0.1:8300")
92///     .with_timeout(Duration::from_secs(10))
93///     .with_poll_interval(Duration::from_millis(250));
94/// let mut builder = GraphBuilder::new();
95/// builder.add_node("research", node);
96/// ```
97#[derive(Clone)]
98pub struct A2aNode {
99    /// The graph node name, also sent as the message's skill hint.
100    name: String,
101    /// Full URL of the agent's JSON-RPC endpoint (`{base}/a2a`).
102    rpc_url: String,
103    /// HTTP client (carries the per-request timeout); `None` in replay
104    /// mode — a replayed run cannot issue outbound calls by construction.
105    client: Option<reqwest::Client>,
106    timeout: Duration,
107    max_retries: u32,
108    base_backoff: Duration,
109    poll_interval: Duration,
110    /// The state channel the terminal outcome is written to.
111    channel: String,
112    /// Optional `X-Api-Key` credential (rusty-agent-server's tenant auth).
113    api_key: Option<String>,
114    /// The run's journal; attached per run the way
115    /// [`crate::replay::RecordingTool`] attaches.
116    journal: Option<Journal>,
117    /// Run cancellation: firing it cancels the remote task, then errors.
118    cancellation: Option<tokio_util::sync::CancellationToken>,
119    /// The recorded journal's serving cursor; `Some` in replay mode.
120    replay: Option<ReplaySource>,
121}
122
123/// Internal classification of a failed HTTP attempt (the
124/// [`crate::remote::RemoteNode`] taxonomy).
125#[derive(Debug)]
126enum AttemptError {
127    /// Transport-class failure eligible for retry (connect, timeout, 5xx,
128    /// 408, 429), with an optional server-provided `Retry-After` floor.
129    Retryable {
130        error: RustyError,
131        retry_after: Option<Duration>,
132    },
133    /// Definitive failure; never retried (other 4xx, JSON-RPC errors,
134    /// decode errors).
135    Fatal(RustyError),
136}
137
138impl A2aNode {
139    /// A node delegating to the remote agent served at `base_url` (e.g.
140    /// `"http://127.0.0.1:8300"`). A trailing `/` is trimmed and `/a2a`
141    /// appended; a `base_url` already ending in `/a2a` is used verbatim.
142    /// The terminal outcome is written to the `a2a_outcome` channel unless
143    /// [`A2aNode::with_channel`] says otherwise.
144    pub fn new(name: impl Into<String>, base_url: impl Into<String>) -> Self {
145        let base = base_url.into();
146        let base = base.trim_end_matches('/');
147        let rpc_url = if base.ends_with("/a2a") {
148            base.to_owned()
149        } else {
150            format!("{base}/a2a")
151        };
152        Self {
153            name: name.into(),
154            rpc_url,
155            client: Some(Self::build_client(DEFAULT_TIMEOUT)),
156            timeout: DEFAULT_TIMEOUT,
157            max_retries: DEFAULT_MAX_RETRIES,
158            base_backoff: DEFAULT_BASE_BACKOFF,
159            poll_interval: DEFAULT_POLL_INTERVAL,
160            channel: "a2a_outcome".to_string(),
161            api_key: None,
162            journal: None,
163            cancellation: None,
164            replay: None,
165        }
166    }
167
168    /// Override the per-request timeout.
169    pub fn with_timeout(mut self, timeout: Duration) -> Self {
170        self.timeout = timeout;
171        if self.replay.is_none() {
172            self.client = Some(Self::build_client(timeout));
173        }
174        self
175    }
176
177    /// Override the number of retries after the initial attempt (`0` =
178    /// single attempt).
179    pub fn with_retries(mut self, max_retries: u32) -> Self {
180        self.max_retries = max_retries;
181        self
182    }
183
184    /// Override the base backoff delay between retries.
185    pub fn with_backoff(mut self, base_backoff: Duration) -> Self {
186        self.base_backoff = base_backoff;
187        self
188    }
189
190    /// Override the `tasks/get` poll interval.
191    pub fn with_poll_interval(mut self, poll_interval: Duration) -> Self {
192        self.poll_interval = poll_interval;
193        self
194    }
195
196    /// Override the state channel the terminal outcome is written to.
197    pub fn with_channel(mut self, channel: impl Into<String>) -> Self {
198        self.channel = channel.into();
199        self
200    }
201
202    /// Present `key` as the `X-Api-Key` header on every request
203    /// (rusty-agent-server's tenant authentication; other agents ignore or map
204    /// it per their own auth model).
205    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
206        self.api_key = Some(key.into());
207        self
208    }
209
210    /// Attach the run's journal: the delegation is recorded as one
211    /// `RemoteCall` event, parented on the invoking node-input event
212    /// delivered via [`PARENT_EVENT_KEY`]. Without a journal the node
213    /// still works — it just leaves no evidence, the same posture as an
214    /// unwrapped [`crate::remote::RemoteNode`].
215    pub fn with_journal(mut self, journal: Journal) -> Self {
216        self.journal = Some(journal);
217        self
218    }
219
220    /// Attach the run's cancellation token: when it fires mid-delegation
221    /// the node sends `tasks/cancel` for the in-flight remote task (best
222    /// effort — the cancel itself is not retried), journals the canceled
223    /// outcome, and returns [`RustyError::Cancelled`].
224    pub fn with_cancellation(mut self, token: tokio_util::sync::CancellationToken) -> Self {
225        self.cancellation = Some(token);
226        self
227    }
228
229    /// The replaying half (R0.9 wave 4): serve the delegation's outcome
230    /// from the recorded run's [`ReplaySource`] instead of the network.
231    /// No HTTP client is kept — a replayed run cannot reach the remote
232    /// agent by construction, the
233    /// [`JournaledMcpTool::replaying`](crate::mcp::JournaledMcpTool::replaying)
234    /// discipline. The replay run's journal is still required: the served
235    /// event is re-journaled into it.
236    pub fn replaying(mut self, source: ReplaySource, journal: Journal) -> Self {
237        self.client = None;
238        self.replay = Some(source);
239        self.journal = Some(journal);
240        self
241    }
242
243    /// The derived `messageId` for one invocation: the delegation's
244    /// idempotency handle (see the module docs).
245    pub fn message_id(&self, thread_id: &str, step: usize) -> String {
246        format!("a2a-{thread_id}-{step}-{}", self.name)
247    }
248
249    /// The full JSON-RPC endpoint URL.
250    pub fn rpc_url(&self) -> &str {
251        &self.rpc_url
252    }
253
254    fn build_client(timeout: Duration) -> reqwest::Client {
255        // Same invariant as RemoteNode: the builder only sets a timeout on
256        // the rustls backend, so construction cannot realistically fail.
257        reqwest::Client::builder()
258            .timeout(timeout)
259            .build()
260            .expect("reqwest client builder with rustls must succeed")
261    }
262
263    fn node_err(&self, msg: impl Into<String>) -> RustyError {
264        RustyError::Node(format!("a2a node `{}`: {}", self.name, msg.into()))
265    }
266
267    /// One JSON-RPC call. `Ok` carries the response's `result` value;
268    /// `Err` is classified for retry.
269    async fn try_rpc(
270        &self,
271        method: &str,
272        params: &Value,
273    ) -> std::result::Result<Value, AttemptError> {
274        let Some(client) = &self.client else {
275            return Err(AttemptError::Fatal(self.node_err(
276                "replay-mode node attempted a live RPC (construction bug)",
277            )));
278        };
279        let request = json!({
280            "jsonrpc": "2.0",
281            "id": 1,
282            "method": method,
283            "params": params,
284        });
285        let mut builder = client.post(&self.rpc_url).json(&request);
286        if let Some(key) = &self.api_key {
287            builder = builder.header("x-api-key", key);
288        }
289        let response = builder.send().await.map_err(|e| {
290            let err = self.node_err(format!("POST {} failed: {e}", self.rpc_url));
291            if e.is_timeout() || e.is_connect() {
292                AttemptError::Retryable {
293                    error: err,
294                    retry_after: None,
295                }
296            } else {
297                AttemptError::Fatal(err)
298            }
299        })?;
300
301        let status = response.status();
302        if !status.is_success() {
303            let retry_after = response
304                .headers()
305                .get(reqwest::header::RETRY_AFTER)
306                .and_then(|v| v.to_str().ok())
307                .and_then(|s| s.trim().parse::<u64>().ok())
308                .map(Duration::from_secs);
309            let body = response.text().await.unwrap_or_default();
310            let err = self.node_err(format!(
311                "agent at {} returned {status}: {}",
312                self.rpc_url,
313                crate::llm::truncate_body(&body)
314            ));
315            let retryable = status.is_server_error()
316                || status == reqwest::StatusCode::REQUEST_TIMEOUT
317                || status == reqwest::StatusCode::TOO_MANY_REQUESTS;
318            return Err(if retryable {
319                AttemptError::Retryable {
320                    error: err,
321                    retry_after,
322                }
323            } else {
324                AttemptError::Fatal(err)
325            });
326        }
327
328        let body: Value = response.json().await.map_err(|e| {
329            AttemptError::Fatal(self.node_err(format!("could not decode JSON-RPC response: {e}")))
330        })?;
331        if let Some(error) = body.get("error") {
332            // A JSON-RPC error is the server's definitive answer (unknown
333            // method, invalid params, task not found): never retried.
334            return Err(AttemptError::Fatal(self.node_err(format!(
335                "JSON-RPC error from {}: {error}",
336                self.rpc_url
337            ))));
338        }
339        body.get("result").cloned().ok_or_else(|| {
340            AttemptError::Fatal(
341                self.node_err("JSON-RPC response carries neither `result` nor `error`"),
342            )
343        })
344    }
345
346    /// `try_rpc` with the retry policy applied (transport-class only).
347    async fn rpc(&self, method: &str, params: &Value) -> Result<Value> {
348        let mut attempt: u32 = 0;
349        loop {
350            match self.try_rpc(method, params).await {
351                Ok(result) => return Ok(result),
352                Err(AttemptError::Fatal(e)) => return Err(e),
353                Err(AttemptError::Retryable { error, retry_after })
354                    if attempt < self.max_retries =>
355                {
356                    let mut delay = backoff_delay(self.base_backoff, attempt);
357                    if let Some(floor) = retry_after {
358                        delay = delay.max(floor);
359                    }
360                    tracing::warn!(
361                        node = %self.name,
362                        url = %self.rpc_url,
363                        method,
364                        attempt = attempt + 1,
365                        max_retries = self.max_retries,
366                        backoff_ms = delay.as_millis() as u64,
367                        error = %error,
368                        "a2a attempt failed; retrying"
369                    );
370                    tokio::time::sleep(delay).await;
371                    attempt += 1;
372                }
373                Err(AttemptError::Retryable { error, .. }) => return Err(error),
374            }
375        }
376    }
377
378    /// Journal the delegation as one `RemoteCall` event (no-op when the
379    /// node carries no journal). The input is the exact `message/send`
380    /// params; the output is the terminal task (or the canceled task's
381    /// last known state); failures record `EventStatus::Error`.
382    fn journal_outcome(&self, parent: Option<String>, params: &Value, task: &Value, error: bool) {
383        let Some(journal) = &self.journal else {
384            return;
385        };
386        let mut draft = crate::journal::EventDraft::new(RunEventKind::RemoteCall, self.effect())
387            .node(self.name.clone())
388            .input(params.clone())
389            .output(task.clone());
390        if let Some(parent) = parent {
391            draft = draft.parent(parent);
392        }
393        if error {
394            draft = draft.status(EventStatus::Error);
395        }
396        journal.record(draft);
397    }
398
399    /// The channel update for a completed task: the task id plus its
400    /// artifacts, verbatim — the caller's graph decides what to read.
401    fn outcome_update(&self, task: &Value) -> NodeOutput {
402        NodeOutput::update(
403            self.channel.clone(),
404            json!({
405                "task_id": task.get("id").cloned().unwrap_or(Value::Null),
406                "context_id": task.get("contextId").cloned().unwrap_or(Value::Null),
407                "artifacts": task.get("artifacts").cloned().unwrap_or(Value::Null),
408            }),
409        )
410    }
411}
412
413#[async_trait]
414impl Node for A2aNode {
415    fn name(&self) -> &str {
416        &self.name
417    }
418
419    fn effect(&self) -> Effect {
420        // A delegation crosses a process boundary into work the runtime
421        // cannot inspect; the restrictive class applies, exactly as
422        // RemoteNode declares.
423        Effect::NonIdempotent
424    }
425
426    async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
427        let parent = ctx
428            .config()
429            .extra
430            .get(PARENT_EVENT_KEY)
431            .and_then(Value::as_str)
432            .map(str::to_string);
433        let message = json!({
434            "role": "user",
435            "messageId": self.message_id(ctx.thread_id(), ctx.step()),
436            // The run's thread groups its delegations into one A2A context:
437            // server-side, that context maps onto one durable run journal.
438            "contextId": ctx.thread_id(),
439            "parts": [{ "kind": "data", "data": ctx.state().to_value() }],
440        });
441        let params = json!({ "message": message });
442
443        // Replay: serve the journaled outcome; no HTTP, by construction.
444        if let Some(source) = &self.replay {
445            let served = source.serve(RunEventKind::RemoteCall, &params)?;
446            if let Some(journal) = &self.journal {
447                served.rejournal(journal, parent.unwrap_or_default());
448            }
449            if served.event.status == EventStatus::Error {
450                return Err(self.node_err(format!(
451                    "recorded delegation failed (served from journal): {}",
452                    served.output.unwrap_or(Value::Null)
453                )));
454            }
455            let task = served.output.unwrap_or(Value::Null);
456            return Ok(self.outcome_update(&task));
457        }
458
459        // Live: submit, then poll to terminal.
460        let task = self.rpc("message/send", &params).await?;
461        let task_id = task
462            .get("id")
463            .and_then(Value::as_str)
464            .ok_or_else(|| self.node_err("`message/send` result carries no task `id`"))?
465            .to_string();
466
467        let get_params = json!({ "id": task_id });
468        loop {
469            let sleep = tokio::time::sleep(self.poll_interval);
470            if let Some(token) = &self.cancellation {
471                tokio::select! {
472                    () = sleep => {}
473                    () = token.cancelled() => {
474                        // Best effort: the cancel is not retried — the
475                        // server's own lease expiry is the backstop for a
476                        // cancel that never lands.
477                        let cancel_params = json!({ "id": task_id });
478                        let _ = self.try_rpc("tasks/cancel", &cancel_params).await;
479                        let canceled = json!({
480                            "id": task_id,
481                            "status": { "state": "canceled" },
482                        });
483                        self.journal_outcome(parent, &params, &canceled, true);
484                        return Err(RustyError::Cancelled(format!(
485                            "a2a node `{}`: run cancelled; remote task `{task_id}` was sent tasks/cancel",
486                            self.name
487                        )));
488                    }
489                }
490            } else {
491                sleep.await;
492            }
493
494            let task = self.rpc("tasks/get", &get_params).await?;
495            let state = task
496                .pointer("/status/state")
497                .and_then(Value::as_str)
498                .unwrap_or("");
499            match state {
500                "submitted" | "working" => continue,
501                "completed" => {
502                    self.journal_outcome(parent, &params, &task, false);
503                    return Ok(self.outcome_update(&task));
504                }
505                "failed" | "rejected" => {
506                    self.journal_outcome(parent, &params, &task, true);
507                    let message = task
508                        .pointer("/status/message/parts")
509                        .and_then(Value::as_array)
510                        .and_then(|parts| parts.first())
511                        .and_then(|part| part.get("text"))
512                        .and_then(Value::as_str)
513                        .unwrap_or("the remote agent reported failure");
514                    return Err(
515                        self.node_err(format!("remote task `{task_id}` {state}: {message}"))
516                    );
517                }
518                "canceled" => {
519                    self.journal_outcome(parent, &params, &task, true);
520                    return Err(self.node_err(format!(
521                        "remote task `{task_id}` was canceled outside this run"
522                    )));
523                }
524                other => {
525                    return Err(self.node_err(format!(
526                        "remote task `{task_id}` reports unknown state `{other}`"
527                    )));
528                }
529            }
530        }
531    }
532}