use std::time::Duration;
use async_trait::async_trait;
use serde_json::{json, Value};
use crate::error::{Result, RustyError};
use crate::journal::{Journal, PARENT_EVENT_KEY};
use crate::llm::backoff_delay;
use crate::node::{Node, NodeContext, NodeOutput};
use crate::record::{Effect, EventStatus, RunEventKind};
use crate::replay::ReplaySource;
pub const A2A_PROTOCOL_VERSION: &str = "0.3.0";
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_MAX_RETRIES: u32 = 2;
pub const DEFAULT_BASE_BACKOFF: Duration = Duration::from_millis(100);
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
#[derive(Clone)]
pub struct A2aNode {
name: String,
rpc_url: String,
client: Option<reqwest::Client>,
timeout: Duration,
max_retries: u32,
base_backoff: Duration,
poll_interval: Duration,
channel: String,
api_key: Option<String>,
journal: Option<Journal>,
cancellation: Option<tokio_util::sync::CancellationToken>,
replay: Option<ReplaySource>,
}
#[derive(Debug)]
enum AttemptError {
Retryable {
error: RustyError,
retry_after: Option<Duration>,
},
Fatal(RustyError),
}
impl A2aNode {
pub fn new(name: impl Into<String>, base_url: impl Into<String>) -> Self {
let base = base_url.into();
let base = base.trim_end_matches('/');
let rpc_url = if base.ends_with("/a2a") {
base.to_owned()
} else {
format!("{base}/a2a")
};
Self {
name: name.into(),
rpc_url,
client: Some(Self::build_client(DEFAULT_TIMEOUT)),
timeout: DEFAULT_TIMEOUT,
max_retries: DEFAULT_MAX_RETRIES,
base_backoff: DEFAULT_BASE_BACKOFF,
poll_interval: DEFAULT_POLL_INTERVAL,
channel: "a2a_outcome".to_string(),
api_key: None,
journal: None,
cancellation: None,
replay: None,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
if self.replay.is_none() {
self.client = Some(Self::build_client(timeout));
}
self
}
pub fn with_retries(mut self, max_retries: u32) -> Self {
self.max_retries = max_retries;
self
}
pub fn with_backoff(mut self, base_backoff: Duration) -> Self {
self.base_backoff = base_backoff;
self
}
pub fn with_poll_interval(mut self, poll_interval: Duration) -> Self {
self.poll_interval = poll_interval;
self
}
pub fn with_channel(mut self, channel: impl Into<String>) -> Self {
self.channel = channel.into();
self
}
pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn with_journal(mut self, journal: Journal) -> Self {
self.journal = Some(journal);
self
}
pub fn with_cancellation(mut self, token: tokio_util::sync::CancellationToken) -> Self {
self.cancellation = Some(token);
self
}
pub fn replaying(mut self, source: ReplaySource, journal: Journal) -> Self {
self.client = None;
self.replay = Some(source);
self.journal = Some(journal);
self
}
pub fn message_id(&self, thread_id: &str, step: usize) -> String {
format!("a2a-{thread_id}-{step}-{}", self.name)
}
pub fn rpc_url(&self) -> &str {
&self.rpc_url
}
fn build_client(timeout: Duration) -> reqwest::Client {
reqwest::Client::builder()
.timeout(timeout)
.build()
.expect("reqwest client builder with rustls must succeed")
}
fn node_err(&self, msg: impl Into<String>) -> RustyError {
RustyError::Node(format!("a2a node `{}`: {}", self.name, msg.into()))
}
async fn try_rpc(
&self,
method: &str,
params: &Value,
) -> std::result::Result<Value, AttemptError> {
let Some(client) = &self.client else {
return Err(AttemptError::Fatal(self.node_err(
"replay-mode node attempted a live RPC (construction bug)",
)));
};
let request = json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params,
});
let mut builder = client.post(&self.rpc_url).json(&request);
if let Some(key) = &self.api_key {
builder = builder.header("x-api-key", key);
}
let response = builder.send().await.map_err(|e| {
let err = self.node_err(format!("POST {} failed: {e}", self.rpc_url));
if e.is_timeout() || e.is_connect() {
AttemptError::Retryable {
error: err,
retry_after: None,
}
} else {
AttemptError::Fatal(err)
}
})?;
let status = response.status();
if !status.is_success() {
let retry_after = response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok())
.map(Duration::from_secs);
let body = response.text().await.unwrap_or_default();
let err = self.node_err(format!(
"agent at {} returned {status}: {}",
self.rpc_url,
crate::llm::truncate_body(&body)
));
let retryable = status.is_server_error()
|| status == reqwest::StatusCode::REQUEST_TIMEOUT
|| status == reqwest::StatusCode::TOO_MANY_REQUESTS;
return Err(if retryable {
AttemptError::Retryable {
error: err,
retry_after,
}
} else {
AttemptError::Fatal(err)
});
}
let body: Value = response.json().await.map_err(|e| {
AttemptError::Fatal(self.node_err(format!("could not decode JSON-RPC response: {e}")))
})?;
if let Some(error) = body.get("error") {
return Err(AttemptError::Fatal(self.node_err(format!(
"JSON-RPC error from {}: {error}",
self.rpc_url
))));
}
body.get("result").cloned().ok_or_else(|| {
AttemptError::Fatal(
self.node_err("JSON-RPC response carries neither `result` nor `error`"),
)
})
}
async fn rpc(&self, method: &str, params: &Value) -> Result<Value> {
let mut attempt: u32 = 0;
loop {
match self.try_rpc(method, params).await {
Ok(result) => return Ok(result),
Err(AttemptError::Fatal(e)) => return Err(e),
Err(AttemptError::Retryable { error, retry_after })
if attempt < self.max_retries =>
{
let mut delay = backoff_delay(self.base_backoff, attempt);
if let Some(floor) = retry_after {
delay = delay.max(floor);
}
tracing::warn!(
node = %self.name,
url = %self.rpc_url,
method,
attempt = attempt + 1,
max_retries = self.max_retries,
backoff_ms = delay.as_millis() as u64,
error = %error,
"a2a attempt failed; retrying"
);
tokio::time::sleep(delay).await;
attempt += 1;
}
Err(AttemptError::Retryable { error, .. }) => return Err(error),
}
}
}
fn journal_outcome(&self, parent: Option<String>, params: &Value, task: &Value, error: bool) {
let Some(journal) = &self.journal else {
return;
};
let mut draft = crate::journal::EventDraft::new(RunEventKind::RemoteCall, self.effect())
.node(self.name.clone())
.input(params.clone())
.output(task.clone());
if let Some(parent) = parent {
draft = draft.parent(parent);
}
if error {
draft = draft.status(EventStatus::Error);
}
journal.record(draft);
}
fn outcome_update(&self, task: &Value) -> NodeOutput {
NodeOutput::update(
self.channel.clone(),
json!({
"task_id": task.get("id").cloned().unwrap_or(Value::Null),
"context_id": task.get("contextId").cloned().unwrap_or(Value::Null),
"artifacts": task.get("artifacts").cloned().unwrap_or(Value::Null),
}),
)
}
}
#[async_trait]
impl Node for A2aNode {
fn name(&self) -> &str {
&self.name
}
fn effect(&self) -> Effect {
Effect::NonIdempotent
}
async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
let parent = ctx
.config()
.extra
.get(PARENT_EVENT_KEY)
.and_then(Value::as_str)
.map(str::to_string);
let message = json!({
"role": "user",
"messageId": self.message_id(ctx.thread_id(), ctx.step()),
"contextId": ctx.thread_id(),
"parts": [{ "kind": "data", "data": ctx.state().to_value() }],
});
let params = json!({ "message": message });
if let Some(source) = &self.replay {
let served = source.serve(RunEventKind::RemoteCall, ¶ms)?;
if let Some(journal) = &self.journal {
served.rejournal(journal, parent.unwrap_or_default());
}
if served.event.status == EventStatus::Error {
return Err(self.node_err(format!(
"recorded delegation failed (served from journal): {}",
served.output.unwrap_or(Value::Null)
)));
}
let task = served.output.unwrap_or(Value::Null);
return Ok(self.outcome_update(&task));
}
let task = self.rpc("message/send", ¶ms).await?;
let task_id = task
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| self.node_err("`message/send` result carries no task `id`"))?
.to_string();
let get_params = json!({ "id": task_id });
loop {
let sleep = tokio::time::sleep(self.poll_interval);
if let Some(token) = &self.cancellation {
tokio::select! {
() = sleep => {}
() = token.cancelled() => {
let cancel_params = json!({ "id": task_id });
let _ = self.try_rpc("tasks/cancel", &cancel_params).await;
let canceled = json!({
"id": task_id,
"status": { "state": "canceled" },
});
self.journal_outcome(parent, ¶ms, &canceled, true);
return Err(RustyError::Cancelled(format!(
"a2a node `{}`: run cancelled; remote task `{task_id}` was sent tasks/cancel",
self.name
)));
}
}
} else {
sleep.await;
}
let task = self.rpc("tasks/get", &get_params).await?;
let state = task
.pointer("/status/state")
.and_then(Value::as_str)
.unwrap_or("");
match state {
"submitted" | "working" => continue,
"completed" => {
self.journal_outcome(parent, ¶ms, &task, false);
return Ok(self.outcome_update(&task));
}
"failed" | "rejected" => {
self.journal_outcome(parent, ¶ms, &task, true);
let message = task
.pointer("/status/message/parts")
.and_then(Value::as_array)
.and_then(|parts| parts.first())
.and_then(|part| part.get("text"))
.and_then(Value::as_str)
.unwrap_or("the remote agent reported failure");
return Err(
self.node_err(format!("remote task `{task_id}` {state}: {message}"))
);
}
"canceled" => {
self.journal_outcome(parent, ¶ms, &task, true);
return Err(self.node_err(format!(
"remote task `{task_id}` was canceled outside this run"
)));
}
other => {
return Err(self.node_err(format!(
"remote task `{task_id}` reports unknown state `{other}`"
)));
}
}
}
}
}