1use std::error::Error as _;
2
3use async_trait::async_trait;
4use reqwest::Url;
5use serde_json::Value;
6use tokio::sync::broadcast;
7
8use crate::triggers::TriggerEvent;
9
10const A2A_AGENT_CARD_PATHS: &[&str] = &[
11 ".well-known/agent-card.json",
12 ".well-known/a2a-agent",
13 ".well-known/agent.json",
14 "agent/card",
15];
16const A2A_PROTOCOL_VERSION: &str = "0.3.0";
17const A2A_JSONRPC_TRANSPORT: &str = "JSONRPC";
18const A2A_PUSH_URL_ENV: &str = "HARN_A2A_PUSH_URL";
19const A2A_PUSH_TOKEN_ENV: &str = "HARN_A2A_PUSH_TOKEN";
20const A2A_ACTOR_CHAIN_METADATA_POINTERS: &[&str] = &[
21 "/actor_chain",
22 "/actorChain",
23 "/metadata/actor_chain",
24 "/metadata/actorChain",
25 "/metadata/harn/actor_chain",
26 "/metadata/harn/actorChain",
27 "/metadata/_harn/actorChain",
28 "/statusUpdate/actor_chain",
29 "/statusUpdate/actorChain",
30 "/statusUpdate/metadata/actor_chain",
31 "/statusUpdate/metadata/actorChain",
32 "/statusUpdate/metadata/harn/actor_chain",
33 "/statusUpdate/metadata/harn/actorChain",
34 "/statusUpdate/metadata/_harn/actorChain",
35 "/task/actor_chain",
36 "/task/actorChain",
37 "/task/metadata/actor_chain",
38 "/task/metadata/actorChain",
39 "/task/metadata/harn/actor_chain",
40 "/task/metadata/harn/actorChain",
41 "/task/metadata/_harn/actorChain",
42 "/message/metadata/actor_chain",
43 "/message/metadata/actorChain",
44 "/message/metadata/harn/actor_chain",
45 "/message/metadata/harn/actorChain",
46 "/message/metadata/_harn/actorChain",
47];
48
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct ResolvedA2aEndpoint {
51 pub card_url: String,
52 pub rpc_url: String,
53 pub agent_id: Option<String>,
54 pub target_agent: String,
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct ResolvedA2aAgent {
59 pub endpoint: ResolvedA2aEndpoint,
60 pub card: Value,
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub enum DispatchAck {
65 InlineResult {
66 task_id: String,
67 result: Value,
68 },
69 PendingTask {
70 task_id: String,
71 state: String,
72 handle: Value,
73 },
74}
75
76#[derive(Debug)]
77pub enum A2aClientError {
78 InvalidTarget(String),
79 Discovery(String),
80 Protocol(String),
81 Denied(String),
82 Timeout(String),
83 Cancelled(String),
84}
85
86impl std::fmt::Display for A2aClientError {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 match self {
89 Self::InvalidTarget(message)
90 | Self::Discovery(message)
91 | Self::Protocol(message)
92 | Self::Denied(message)
93 | Self::Timeout(message)
94 | Self::Cancelled(message) => f.write_str(message),
95 }
96 }
97}
98
99impl std::error::Error for A2aClientError {}
100
101#[async_trait]
103pub trait A2aClient: Send + Sync + 'static {
104 async fn dispatch(
105 &self,
106 target: &str,
107 allow_cleartext: bool,
108 binding_id: &str,
109 binding_key: &str,
110 event: &TriggerEvent,
111 cancel_rx: &mut broadcast::Receiver<()>,
112 ) -> Result<(ResolvedA2aEndpoint, DispatchAck), A2aClientError>;
113}
114
115pub struct RealA2aClient;
117
118#[async_trait]
119impl A2aClient for RealA2aClient {
120 async fn dispatch(
121 &self,
122 target: &str,
123 allow_cleartext: bool,
124 binding_id: &str,
125 binding_key: &str,
126 event: &TriggerEvent,
127 cancel_rx: &mut broadcast::Receiver<()>,
128 ) -> Result<(ResolvedA2aEndpoint, DispatchAck), A2aClientError> {
129 dispatch_trigger_event(
130 target,
131 allow_cleartext,
132 binding_id,
133 binding_key,
134 event,
135 cancel_rx,
136 )
137 .await
138 }
139}
140
141pub fn actor_chain_metadata_candidate(value: &Value) -> Option<(&'static str, &Value)> {
146 for pointer in A2A_ACTOR_CHAIN_METADATA_POINTERS {
147 if let Some(candidate) = value.pointer(pointer) {
148 return Some((pointer, candidate));
149 }
150 }
151 None
152}
153
154pub fn actor_chain_from_metadata(value: &Value) -> Option<crate::actor_chain::ActorChain> {
155 actor_chain_metadata_candidate(value)
156 .and_then(|(_, candidate)| crate::actor_chain::ActorChain::from_json_value(candidate).ok())
157}
158
159#[derive(Debug)]
160enum AgentCardFetchError {
161 Cancelled(String),
162 Discovery(String),
163 ConnectRefused(String),
164 Denied(String),
165 Timeout(String),
166}
167
168pub async fn dispatch_trigger_event(
169 raw_target: &str,
170 allow_cleartext: bool,
171 binding_id: &str,
172 binding_key: &str,
173 event: &TriggerEvent,
174 cancel_rx: &mut broadcast::Receiver<()>,
175) -> Result<(ResolvedA2aEndpoint, DispatchAck), A2aClientError> {
176 let started = std::time::Instant::now();
177 let target = match parse_target(raw_target) {
178 Ok(target) => target,
179 Err(error) => {
180 record_a2a_metric(raw_target, "failed", started.elapsed());
181 return Err(error);
182 }
183 };
184 let endpoint = match resolve_endpoint(&target, allow_cleartext, cancel_rx).await {
185 Ok(endpoint) => endpoint,
186 Err(error) => {
187 record_a2a_metric(raw_target, "failed", started.elapsed());
188 return Err(error);
189 }
190 };
191 let message_id = format!("{}.{}", event.trace_id.0, event.id.0);
192 let actor_chain = crate::agent_sessions::current_actor_chain()
193 .as_ref()
194 .map(crate::actor_chain::ActorChain::to_json_value);
195 let mut envelope = serde_json::json!({
196 "kind": "harn.trigger.dispatch",
197 "message_id": message_id,
198 "trace_id": event.trace_id.0,
199 "event_id": event.id.0,
200 "trigger_id": binding_id,
201 "binding_key": binding_key,
202 "target_agent": endpoint.target_agent,
203 "event": event,
204 });
205 if let Some(chain) = actor_chain.as_ref() {
206 envelope["actor_chain"] = chain.clone();
207 }
208 let text = serde_json::to_string(&envelope)
209 .map_err(|error| A2aClientError::Protocol(format!("serialize A2A envelope: {error}")))?;
210 let push_config = push_notification_config();
211 let mut metadata = serde_json::json!({
212 "kind": "harn.trigger.dispatch",
213 "trace_id": event.trace_id.0,
214 "event_id": event.id.0,
215 "trigger_id": binding_id,
216 "binding_key": binding_key,
217 "target_agent": endpoint.target_agent,
218 });
219 if let Some(chain) = actor_chain.as_ref() {
220 metadata["actor_chain"] = chain.clone();
221 metadata["harn"] = serde_json::json!({"actor_chain": chain});
222 }
223 let mut params = serde_json::json!({
224 "contextId": event.trace_id.0,
225 "message": {
226 "messageId": message_id,
227 "role": "user",
228 "parts": [{
229 "type": "text",
230 "text": text,
231 }],
232 "metadata": metadata,
233 },
234 });
235 if let Some(config) = push_config.clone() {
236 params["configuration"] = serde_json::json!({
237 "blocking": false,
238 "returnImmediately": true,
239 "pushNotificationConfig": config,
240 });
241 }
242 let request = crate::jsonrpc::request(message_id.clone(), "message/send", params);
243
244 let body = match send_jsonrpc(&endpoint.rpc_url, &request, &event.trace_id.0, cancel_rx).await {
245 Ok(body) => body,
246 Err(error) => {
247 record_a2a_metric(raw_target, "failed", started.elapsed());
248 return Err(error);
249 }
250 };
251 let result = match body.get("result").cloned().ok_or_else(|| {
252 if let Some(error) = body.get("error") {
253 let message = error
254 .get("message")
255 .and_then(Value::as_str)
256 .unwrap_or("unknown A2A error");
257 A2aClientError::Protocol(format!("A2A task dispatch failed: {message}"))
258 } else {
259 A2aClientError::Protocol("A2A task dispatch response missing result".to_string())
260 }
261 }) {
262 Ok(result) => result,
263 Err(error) => {
264 record_a2a_metric(raw_target, "failed", started.elapsed());
265 return Err(error);
266 }
267 };
268
269 let task_id = match result
270 .get("id")
271 .and_then(Value::as_str)
272 .filter(|value| !value.is_empty())
273 .ok_or_else(|| A2aClientError::Protocol("A2A task response missing result.id".to_string()))
274 {
275 Ok(task_id) => task_id.to_string(),
276 Err(error) => {
277 record_a2a_metric(raw_target, "failed", started.elapsed());
278 return Err(error);
279 }
280 };
281 let state = match task_state(&result) {
282 Ok(state) => state.to_string(),
283 Err(error) => {
284 record_a2a_metric(raw_target, "failed", started.elapsed());
285 return Err(error);
286 }
287 };
288
289 if state == "completed" {
290 let inline = extract_inline_result(&result);
291 record_a2a_metric(raw_target, "succeeded", started.elapsed());
292 return Ok((
293 endpoint,
294 DispatchAck::InlineResult {
295 task_id,
296 result: inline,
297 },
298 ));
299 }
300
301 if state == "rejected" {
302 record_a2a_metric(raw_target, "failed", started.elapsed());
303 return Err(A2aClientError::Denied(format!(
304 "A2A task rejected by remote agent: {}",
305 task_status_message(&result).unwrap_or("permission rejected")
306 )));
307 }
308
309 if let Some(config) = push_config {
310 register_push_notification_config(
311 &endpoint.rpc_url,
312 &task_id,
313 config,
314 &event.trace_id.0,
315 cancel_rx,
316 )
317 .await
318 .inspect_err(|_| {
319 record_a2a_metric(raw_target, "failed", started.elapsed());
320 })?;
321 }
322 record_a2a_metric(raw_target, "succeeded", started.elapsed());
323 Ok((
324 endpoint.clone(),
325 DispatchAck::PendingTask {
326 task_id: task_id.clone(),
327 state: state.clone(),
328 handle: serde_json::json!({
329 "kind": "a2a_task_handle",
330 "task_id": task_id,
331 "state": state,
332 "target_agent": endpoint.target_agent,
333 "rpc_url": endpoint.rpc_url,
334 "card_url": endpoint.card_url,
335 "agent_id": endpoint.agent_id,
336 }),
337 },
338 ))
339}
340
341pub async fn resolve_agent(
342 raw_target: &str,
343 allow_cleartext: bool,
344 cancel_rx: &mut broadcast::Receiver<()>,
345) -> Result<ResolvedA2aAgent, A2aClientError> {
346 let target = parse_target(raw_target)?;
347 let resolved = resolve_endpoint_with_card(&target, allow_cleartext, cancel_rx).await?;
348 Ok(ResolvedA2aAgent {
349 endpoint: resolved.0,
350 card: resolved.1,
351 })
352}
353
354pub async fn send_jsonrpc_request(
355 rpc_url: &str,
356 request: &Value,
357 trace_id: &str,
358 cancel_rx: &mut broadcast::Receiver<()>,
359) -> Result<Value, A2aClientError> {
360 send_jsonrpc(rpc_url, request, trace_id, cancel_rx).await
361}
362
363fn push_notification_config() -> Option<Value> {
364 let url = std::env::var(A2A_PUSH_URL_ENV)
365 .ok()
366 .map(|value| value.trim().to_string())
367 .filter(|value| !value.is_empty())?;
368 let token = std::env::var(A2A_PUSH_TOKEN_ENV)
369 .ok()
370 .map(|value| value.trim().to_string())
371 .filter(|value| !value.is_empty());
372 let mut config = serde_json::json!({ "url": url });
373 if let Some(token) = token {
374 config["token"] = Value::String(token.clone());
375 config["authentication"] = serde_json::json!({
376 "scheme": "Bearer",
377 "credentials": token,
378 });
379 }
380 Some(config)
381}
382
383async fn register_push_notification_config(
384 rpc_url: &str,
385 task_id: &str,
386 config: Value,
387 trace_id: &str,
388 cancel_rx: &mut broadcast::Receiver<()>,
389) -> Result<(), A2aClientError> {
390 let request = crate::jsonrpc::request(
391 format!("{trace_id}.{task_id}.push-config"),
392 "tasks/pushNotificationConfig/set",
393 serde_json::json!({
394 "taskId": task_id,
395 "pushNotificationConfig": config,
396 }),
397 );
398 let response = send_jsonrpc(rpc_url, &request, trace_id, cancel_rx).await?;
399 if response.get("error").is_some() {
400 return Err(A2aClientError::Protocol(format!(
401 "A2A push notification registration failed: {}",
402 response["error"]
403 )));
404 }
405 Ok(())
406}
407
408fn record_a2a_metric(target: &str, outcome: &str, duration: std::time::Duration) {
409 if let Some(metrics) = crate::active_metrics_registry() {
410 metrics.record_a2a_hop(target, outcome, duration);
411 }
412}
413
414pub fn target_agent_label(raw_target: &str) -> String {
415 parse_target(raw_target)
416 .map(|target| target.target_agent_label())
417 .unwrap_or_else(|_| raw_target.to_string())
418}
419
420#[derive(Clone, Debug)]
421struct ParsedTarget {
422 authority: String,
423 target_agent: String,
424}
425
426impl ParsedTarget {
427 fn target_agent_label(&self) -> String {
428 if self.target_agent.is_empty() {
429 self.authority.clone()
430 } else {
431 self.target_agent.clone()
432 }
433 }
434}
435
436fn parse_target(raw_target: &str) -> Result<ParsedTarget, A2aClientError> {
437 let parsed = Url::parse(&format!("http://{raw_target}")).map_err(|error| {
438 A2aClientError::InvalidTarget(format!(
439 "invalid a2a dispatch target '{raw_target}': {error}"
440 ))
441 })?;
442 let host = parsed.host_str().ok_or_else(|| {
443 A2aClientError::InvalidTarget(format!(
444 "invalid a2a dispatch target '{raw_target}': missing host"
445 ))
446 })?;
447 let authority = if let Some(port) = parsed.port() {
448 format!("{host}:{port}")
449 } else {
450 host.to_string()
451 };
452 Ok(ParsedTarget {
453 authority,
454 target_agent: parsed.path().trim_start_matches('/').to_string(),
455 })
456}
457
458async fn resolve_endpoint(
459 target: &ParsedTarget,
460 allow_cleartext: bool,
461 cancel_rx: &mut broadcast::Receiver<()>,
462) -> Result<ResolvedA2aEndpoint, A2aClientError> {
463 Ok(
464 resolve_endpoint_with_card(target, allow_cleartext, cancel_rx)
465 .await?
466 .0,
467 )
468}
469
470async fn resolve_endpoint_with_card(
471 target: &ParsedTarget,
472 allow_cleartext: bool,
473 cancel_rx: &mut broadcast::Receiver<()>,
474) -> Result<(ResolvedA2aEndpoint, Value), A2aClientError> {
475 let mut last_error = None;
476 for scheme in card_resolution_schemes(allow_cleartext) {
477 let mut last_scheme_error = None;
478 for path in A2A_AGENT_CARD_PATHS {
479 let card_url = format!("{scheme}://{}/{path}", target.authority);
480 match fetch_agent_card(&card_url, cancel_rx).await {
481 Ok(card) => {
482 let endpoint = endpoint_from_card(
483 card_url,
484 allow_cleartext,
485 &target.authority,
486 target.target_agent.clone(),
487 &card,
488 )?;
489 return Ok((endpoint, card));
490 }
491 Err(AgentCardFetchError::Cancelled(message)) => {
492 return Err(A2aClientError::Cancelled(message));
493 }
494 Err(AgentCardFetchError::Timeout(message)) => {
495 return Err(A2aClientError::Timeout(message));
496 }
497 Err(AgentCardFetchError::Denied(message)) => {
498 return Err(A2aClientError::Denied(message));
499 }
500 Err(error) => {
501 last_error = Some(agent_card_fetch_error_message(&error));
502 last_scheme_error = Some(error);
503 }
504 }
505 }
506 if last_scheme_error.as_ref().is_some_and(|error| {
507 should_try_cleartext_fallback(scheme, allow_cleartext, error, &target.authority)
508 }) {
509 continue;
510 }
511 break;
512 }
513 Err(A2aClientError::Discovery(format!(
514 "could not resolve A2A agent card for '{}': {}",
515 target.authority,
516 last_error.unwrap_or_else(|| "unknown discovery error".to_string())
517 )))
518}
519
520async fn fetch_agent_card(
521 card_url: &str,
522 cancel_rx: &mut broadcast::Receiver<()>,
523) -> Result<Value, AgentCardFetchError> {
524 let response = tokio::select! {
525 response = crate::llm::shared_utility_client().get(card_url).send() => {
526 match response {
527 Ok(response) => Ok(response),
528 Err(error) if error.is_timeout() => Err(AgentCardFetchError::Timeout(
529 format!("A2A HTTP request timed out: {error}")
530 )),
531 Err(error) if is_connect_refused(&error) => Err(AgentCardFetchError::ConnectRefused(
532 format!("A2A HTTP request failed: {error}")
533 )),
534 Err(error) => Err(AgentCardFetchError::Discovery(
535 format!("A2A HTTP request failed: {error}")
536 )),
537 }
538 }
539 _ = recv_cancel(cancel_rx) => Err(AgentCardFetchError::Cancelled(
540 "A2A agent-card fetch cancelled".to_string()
541 )),
542 }?;
543 if matches!(
544 response.status(),
545 reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
546 ) {
547 return Err(AgentCardFetchError::Denied(format!(
548 "GET {card_url} returned HTTP {}",
549 response.status()
550 )));
551 }
552 if !response.status().is_success() {
553 return Err(AgentCardFetchError::Discovery(format!(
554 "GET {card_url} returned HTTP {}",
555 response.status()
556 )));
557 }
558 response
559 .json::<Value>()
560 .await
561 .map_err(|error| AgentCardFetchError::Discovery(format!("parse {card_url}: {error}")))
562}
563
564fn endpoint_from_card(
565 card_url: String,
566 allow_cleartext: bool,
567 requested_authority: &str,
568 target_agent: String,
569 card: &Value,
570) -> Result<ResolvedA2aEndpoint, A2aClientError> {
571 let rpc_url = if has_current_transport_fields(card) {
572 endpoint_from_current_card(card, allow_cleartext, requested_authority)?
573 } else if let Some(rpc_url) =
574 endpoint_from_legacy_supported_interfaces(card, allow_cleartext, requested_authority)?
575 {
576 rpc_url
577 } else {
578 return Err(A2aClientError::Discovery(
579 "A2A agent card missing preferredTransport/additionalInterfaces".to_string(),
580 ));
581 };
582
583 Ok(ResolvedA2aEndpoint {
584 card_url,
585 rpc_url: rpc_url.to_string(),
586 agent_id: card.get("id").and_then(Value::as_str).map(str::to_string),
587 target_agent,
588 })
589}
590
591fn has_current_transport_fields(card: &Value) -> bool {
592 card.get("preferredTransport").is_some() || card.get("additionalInterfaces").is_some()
593}
594
595fn endpoint_from_current_card(
596 card: &Value,
597 allow_cleartext: bool,
598 requested_authority: &str,
599) -> Result<Url, A2aClientError> {
600 let protocol_version = card
601 .get("protocolVersion")
602 .and_then(Value::as_str)
603 .ok_or_else(|| {
604 A2aClientError::Discovery("A2A agent card missing protocolVersion".to_string())
605 })?;
606 if protocol_version != A2A_PROTOCOL_VERSION {
607 return Err(A2aClientError::Discovery(format!(
608 "A2A agent card protocolVersion '{protocol_version}' is not supported; expected {A2A_PROTOCOL_VERSION}"
609 )));
610 }
611
612 let base_url = card
613 .get("url")
614 .and_then(Value::as_str)
615 .ok_or_else(|| A2aClientError::Discovery("A2A agent card missing url".to_string()))?;
616 let base_url = resolve_declared_url(
617 base_url,
618 allow_cleartext,
619 requested_authority,
620 "agent card url",
621 )?;
622
623 let preferred_transport = card
624 .get("preferredTransport")
625 .and_then(Value::as_str)
626 .ok_or_else(|| {
627 A2aClientError::Discovery("A2A agent card missing preferredTransport".to_string())
628 })?;
629 if transport_is_jsonrpc(preferred_transport) {
630 return Ok(base_url);
631 }
632
633 if let Some(interface_url) = current_additional_jsonrpc_url(card)? {
634 return resolve_declared_url(
635 interface_url,
636 allow_cleartext,
637 requested_authority,
638 "JSONRPC additionalInterface url",
639 );
640 }
641
642 Err(A2aClientError::Discovery(
643 "A2A agent card does not expose JSONRPC transport".to_string(),
644 ))
645}
646
647fn current_additional_jsonrpc_url(card: &Value) -> Result<Option<&str>, A2aClientError> {
648 let Some(interfaces) = card.get("additionalInterfaces") else {
649 return Ok(None);
650 };
651 let interfaces = interfaces.as_array().ok_or_else(|| {
652 A2aClientError::Discovery("A2A additionalInterfaces must be an array".to_string())
653 })?;
654 for interface in interfaces {
655 if interface
656 .get("transport")
657 .and_then(Value::as_str)
658 .is_some_and(transport_is_jsonrpc)
659 {
660 let interface_url = interface
661 .get("url")
662 .and_then(Value::as_str)
663 .ok_or_else(|| {
664 A2aClientError::Discovery(
665 "A2A JSONRPC additionalInterface missing url".to_string(),
666 )
667 })?;
668 return Ok(Some(interface_url));
669 }
670 }
671 Ok(None)
672}
673
674fn endpoint_from_legacy_supported_interfaces(
675 card: &Value,
676 allow_cleartext: bool,
677 requested_authority: &str,
678) -> Result<Option<Url>, A2aClientError> {
679 let Some(interfaces) = card.get("supportedInterfaces") else {
680 return Ok(None);
681 };
682 let interfaces = interfaces.as_array().ok_or_else(|| {
683 A2aClientError::Discovery("A2A supportedInterfaces must be an array".to_string())
684 })?;
685 let mut saw_jsonrpc = false;
686 for interface in interfaces {
687 if !interface
688 .get("protocolBinding")
689 .and_then(Value::as_str)
690 .is_some_and(transport_is_jsonrpc)
691 {
692 continue;
693 }
694 saw_jsonrpc = true;
695 if interface.get("protocolVersion").and_then(Value::as_str) != Some(A2A_PROTOCOL_VERSION) {
696 continue;
697 }
698 let interface_url = interface
699 .get("url")
700 .and_then(Value::as_str)
701 .ok_or_else(|| {
702 A2aClientError::Discovery("A2A JSONRPC supportedInterface missing url".to_string())
703 })?;
704 return resolve_declared_url(
705 interface_url,
706 allow_cleartext,
707 requested_authority,
708 "JSONRPC supportedInterface url",
709 )
710 .map(Some);
711 }
712 if saw_jsonrpc {
713 return Err(A2aClientError::Discovery(format!(
714 "A2A supportedInterfaces does not expose JSONRPC for protocolVersion {A2A_PROTOCOL_VERSION}"
715 )));
716 }
717 Err(A2aClientError::Discovery(
718 "A2A agent card does not expose a JSONRPC supportedInterface".to_string(),
719 ))
720}
721
722fn transport_is_jsonrpc(transport: &str) -> bool {
723 transport.eq_ignore_ascii_case(A2A_JSONRPC_TRANSPORT)
724}
725
726fn resolve_declared_url(
727 raw_url: &str,
728 allow_cleartext: bool,
729 requested_authority: &str,
730 label: &str,
731) -> Result<Url, A2aClientError> {
732 let url = Url::parse(raw_url).map_err(|error| {
733 A2aClientError::Discovery(format!("invalid A2A {label} '{raw_url}': {error}"))
734 })?;
735 ensure_cleartext_allowed(&url, allow_cleartext, label)?;
736 let declared_authority = url_authority(&url)?;
737 if !authorities_equivalent(&declared_authority, requested_authority) {
738 return Err(A2aClientError::Denied(format!(
739 "A2A {label} authority mismatch: requested '{requested_authority}', card returned '{declared_authority}'"
740 )));
741 }
742 Ok(url)
743}
744
745fn card_resolution_schemes(allow_cleartext: bool) -> &'static [&'static str] {
746 if allow_cleartext {
747 &["https", "http"]
748 } else {
749 &["https"]
750 }
751}
752
753fn should_try_cleartext_fallback(
766 scheme: &str,
767 allow_cleartext: bool,
768 error: &AgentCardFetchError,
769 authority: &str,
770) -> bool {
771 if !allow_cleartext || scheme != "https" {
772 return false;
773 }
774 match error {
775 AgentCardFetchError::Cancelled(_)
776 | AgentCardFetchError::Denied(_)
777 | AgentCardFetchError::Timeout(_) => false,
778 AgentCardFetchError::ConnectRefused(_) => true,
779 AgentCardFetchError::Discovery(_) => is_loopback_authority(authority),
780 }
781}
782
783fn ensure_cleartext_allowed(
784 url: &Url,
785 allow_cleartext: bool,
786 label: &str,
787) -> Result<(), A2aClientError> {
788 if allow_cleartext || url.scheme() != "http" {
789 return Ok(());
790 }
791 Err(A2aClientError::Denied(format!(
792 "cleartext A2A {label} '{url}' requires `allow_cleartext = true` on the trigger binding"
793 )))
794}
795
796fn is_loopback_authority(authority: &str) -> bool {
797 let (host, _) = split_authority(authority);
798 if host.eq_ignore_ascii_case("localhost") {
799 return true;
800 }
801 if let Ok(ip) = host.parse::<std::net::IpAddr>() {
802 return ip.is_loopback();
803 }
804 false
805}
806
807fn authorities_equivalent(card_authority: &str, requested_authority: &str) -> bool {
818 if card_authority == requested_authority {
819 return true;
820 }
821 let (_, card_port) = split_authority(card_authority);
822 let (_, requested_port) = split_authority(requested_authority);
823 if card_port != requested_port {
824 return false;
825 }
826 is_loopback_authority(card_authority) && is_loopback_authority(requested_authority)
827}
828
829fn split_authority(authority: &str) -> (&str, &str) {
832 let (host_raw, port) = if authority.starts_with('[') {
833 if let Some(end) = authority.rfind(']') {
835 let host = &authority[..=end];
836 let rest = &authority[end + 1..];
837 let port = rest.strip_prefix(':').unwrap_or("");
838 (host, port)
839 } else {
840 (authority, "")
841 }
842 } else {
843 match authority.rsplit_once(':') {
844 Some((host, port)) => (host, port),
845 None => (authority, ""),
846 }
847 };
848 let host = host_raw.trim_start_matches('[').trim_end_matches(']');
849 (host, port)
850}
851
852fn agent_card_fetch_error_message(error: &AgentCardFetchError) -> String {
853 match error {
854 AgentCardFetchError::Cancelled(message)
855 | AgentCardFetchError::Discovery(message)
856 | AgentCardFetchError::ConnectRefused(message)
857 | AgentCardFetchError::Denied(message)
858 | AgentCardFetchError::Timeout(message) => message.clone(),
859 }
860}
861
862fn is_connect_refused(error: &reqwest::Error) -> bool {
863 if !error.is_connect() {
864 return false;
865 }
866 let mut source = error.source();
867 while let Some(cause) = source {
868 if let Some(io_error) = cause.downcast_ref::<std::io::Error>() {
869 if io_error.kind() == std::io::ErrorKind::ConnectionRefused {
870 return true;
871 }
872 }
873 source = cause.source();
874 }
875 false
876}
877
878fn url_authority(url: &Url) -> Result<String, A2aClientError> {
879 let host = url
880 .host_str()
881 .ok_or_else(|| A2aClientError::Discovery(format!("A2A card url '{url}' missing host")))?;
882 Ok(if let Some(port) = url.port() {
883 format!("{host}:{port}")
884 } else {
885 host.to_string()
886 })
887}
888
889async fn send_jsonrpc(
890 rpc_url: &str,
891 request: &Value,
892 trace_id: &str,
893 cancel_rx: &mut broadcast::Receiver<()>,
894) -> Result<Value, A2aClientError> {
895 let response = send_http(
896 crate::llm::shared_blocking_client()
897 .post(rpc_url)
898 .header(reqwest::header::CONTENT_TYPE, "application/json")
899 .header("A2A-Version", A2A_PROTOCOL_VERSION)
900 .header("A2A-Trace-Id", trace_id)
901 .json(request),
902 cancel_rx,
903 "A2A task dispatch cancelled",
904 )
905 .await?;
906 if matches!(
907 response.status(),
908 reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
909 ) {
910 return Err(A2aClientError::Denied(format!(
911 "A2A task dispatch returned HTTP {}",
912 response.status()
913 )));
914 }
915 if !response.status().is_success() {
916 return Err(A2aClientError::Protocol(format!(
917 "A2A task dispatch returned HTTP {}",
918 response.status()
919 )));
920 }
921 response
922 .json::<Value>()
923 .await
924 .map_err(|error| A2aClientError::Protocol(format!("parse A2A dispatch response: {error}")))
925}
926
927async fn send_http(
928 request: reqwest::RequestBuilder,
929 cancel_rx: &mut broadcast::Receiver<()>,
930 cancelled_message: &'static str,
931) -> Result<reqwest::Response, A2aClientError> {
932 tokio::select! {
933 response = request.send() => response.map_err(|error| {
934 if error.is_timeout() {
935 A2aClientError::Timeout(format!("A2A HTTP request timed out: {error}"))
936 } else {
937 A2aClientError::Protocol(format!("A2A HTTP request failed: {error}"))
938 }
939 }),
940 _ = recv_cancel(cancel_rx) => Err(A2aClientError::Cancelled(cancelled_message.to_string())),
941 }
942}
943
944fn task_state(task: &Value) -> Result<&str, A2aClientError> {
945 task.pointer("/status/state")
946 .and_then(Value::as_str)
947 .filter(|value| !value.is_empty())
948 .ok_or_else(|| {
949 A2aClientError::Protocol("A2A task response missing result.status.state".to_string())
950 })
951}
952
953fn task_status_message(task: &Value) -> Option<&str> {
954 task.pointer("/status/message/parts")
955 .and_then(Value::as_array)
956 .and_then(|parts| {
957 parts.iter().find_map(|part| {
958 if part.get("type").and_then(Value::as_str) == Some("text") {
959 part.get("text").and_then(Value::as_str).map(str::trim)
960 } else {
961 None
962 }
963 })
964 })
965 .filter(|message| !message.is_empty())
966}
967
968fn extract_inline_result(task: &Value) -> Value {
969 let text = task
970 .get("history")
971 .and_then(Value::as_array)
972 .and_then(|history| {
973 history.iter().rev().find_map(|message| {
974 let role = message.get("role").and_then(Value::as_str)?;
975 if role != "agent" {
976 return None;
977 }
978 message
979 .get("parts")
980 .and_then(Value::as_array)
981 .and_then(|parts| {
982 parts.iter().find_map(|part| {
983 if part.get("type").and_then(Value::as_str) == Some("text") {
984 part.get("text").and_then(Value::as_str).map(str::trim_end)
985 } else {
986 None
987 }
988 })
989 })
990 })
991 });
992 match text {
993 Some(text) if !text.is_empty() => {
994 serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_string()))
995 }
996 _ => task.clone(),
997 }
998}
999
1000async fn recv_cancel(cancel_rx: &mut broadcast::Receiver<()>) {
1001 let _ = cancel_rx.recv().await;
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006 use super::*;
1007
1008 #[test]
1009 fn target_agent_label_prefers_path() {
1010 assert_eq!(target_agent_label("reviewer.prod/triage"), "triage");
1011 assert_eq!(target_agent_label("reviewer.prod"), "reviewer.prod");
1012 }
1013
1014 #[test]
1015 fn extract_inline_result_parses_json_text() {
1016 let task = serde_json::json!({
1017 "history": [
1018 {"role": "user", "parts": [{"type": "text", "text": "ignored"}]},
1019 {"role": "agent", "parts": [{"type": "text", "text": "{\"trace_id\":\"trace_123\"}\n"}]},
1020 ]
1021 });
1022 assert_eq!(
1023 extract_inline_result(&task),
1024 serde_json::json!({"trace_id": "trace_123"})
1025 );
1026 }
1027
1028 #[test]
1029 fn discovery_prefers_https_before_http() {
1030 assert_eq!(card_resolution_schemes(false), ["https"]);
1031 assert_eq!(card_resolution_schemes(true), ["https", "http"]);
1032 }
1033
1034 #[test]
1035 fn endpoint_from_card_accepts_current_preferred_transport() {
1036 let endpoint = endpoint_from_card(
1037 "https://trusted.example/.well-known/agent-card.json".to_string(),
1038 false,
1039 "trusted.example",
1040 "triage".to_string(),
1041 &serde_json::json!({
1042 "name": "trusted",
1043 "protocolVersion": "0.3.0",
1044 "url": "https://trusted.example/rpc",
1045 "preferredTransport": "JSONRPC",
1046 "additionalInterfaces": [{
1047 "url": "https://trusted.example/rpc",
1048 "transport": "JSONRPC"
1049 }]
1050 }),
1051 )
1052 .expect("current A2A card should resolve");
1053 assert_eq!(endpoint.rpc_url, "https://trusted.example/rpc");
1054 assert_eq!(
1055 endpoint.card_url,
1056 "https://trusted.example/.well-known/agent-card.json"
1057 );
1058 assert_eq!(endpoint.target_agent, "triage");
1059 }
1060
1061 #[test]
1062 fn endpoint_from_card_uses_additional_jsonrpc_interface_when_needed() {
1063 let endpoint = endpoint_from_card(
1064 "https://trusted.example/.well-known/agent-card.json".to_string(),
1065 false,
1066 "trusted.example",
1067 "triage".to_string(),
1068 &serde_json::json!({
1069 "name": "trusted",
1070 "protocolVersion": "0.3.0",
1071 "url": "https://trusted.example/rest",
1072 "preferredTransport": "HTTP+JSON",
1073 "additionalInterfaces": [{
1074 "url": "https://trusted.example/rpc",
1075 "transport": "JSONRPC"
1076 }]
1077 }),
1078 )
1079 .expect("current A2A card should resolve through additionalInterfaces");
1080 assert_eq!(endpoint.rpc_url, "https://trusted.example/rpc");
1081 }
1082
1083 #[test]
1084 fn endpoint_from_card_accepts_legacy_supported_interfaces() {
1085 let endpoint = endpoint_from_card(
1086 "https://trusted.example/.well-known/agent-card.json".to_string(),
1087 false,
1088 "trusted.example",
1089 "triage".to_string(),
1090 &serde_json::json!({
1091 "name": "trusted",
1092 "supportedInterfaces": [{
1093 "protocolBinding": "JSONRPC",
1094 "protocolVersion": "0.3.0",
1095 "url": "https://trusted.example/rpc"
1096 }],
1097 }),
1098 )
1099 .expect("legacy A2A card should resolve during the transition");
1100 assert_eq!(endpoint.rpc_url, "https://trusted.example/rpc");
1101 }
1102
1103 #[test]
1104 fn endpoint_from_card_rejects_removed_interfaces_shape() {
1105 let error = endpoint_from_card(
1106 "https://trusted.example/.well-known/agent-card.json".to_string(),
1107 false,
1108 "trusted.example",
1109 "triage".to_string(),
1110 &serde_json::json!({
1111 "url": "https://trusted.example",
1112 "interfaces": [{"protocol": "jsonrpc", "url": "/rpc"}],
1113 }),
1114 )
1115 .expect_err("pre-0.3 Harn discovery shape should be rejected");
1116 assert_eq!(
1117 error.to_string(),
1118 "A2A agent card missing preferredTransport/additionalInterfaces"
1119 );
1120 }
1121
1122 #[test]
1123 fn cleartext_fallback_only_after_https_connect_refused() {
1124 assert!(should_try_cleartext_fallback(
1125 "https",
1126 true,
1127 &AgentCardFetchError::ConnectRefused("connect refused".to_string()),
1128 "reviewer.example:443",
1129 ));
1130 assert!(!should_try_cleartext_fallback(
1131 "http",
1132 true,
1133 &AgentCardFetchError::ConnectRefused("connect refused".to_string()),
1134 "reviewer.example:443",
1135 ));
1136 assert!(!should_try_cleartext_fallback(
1137 "https",
1138 true,
1139 &AgentCardFetchError::Discovery("tls handshake failed".to_string()),
1140 "reviewer.example:443",
1141 ));
1142 }
1143
1144 #[test]
1145 fn cleartext_fallback_requires_opt_in_even_for_loopback_authorities() {
1146 for authority in [
1147 "127.0.0.1:8080",
1148 "localhost:8080",
1149 "[::1]:8080",
1150 "127.1.2.3:9000",
1151 ] {
1152 assert!(
1153 !should_try_cleartext_fallback(
1154 "https",
1155 false,
1156 &AgentCardFetchError::Discovery("tls handshake failed".to_string()),
1157 authority,
1158 ),
1159 "cleartext fallback must stay disabled without opt-in for '{authority}'"
1160 );
1161 }
1162 }
1163
1164 #[test]
1165 fn cleartext_fallback_allows_loopback_after_opt_in() {
1166 for authority in [
1169 "127.0.0.1:8080",
1170 "localhost:8080",
1171 "[::1]:8080",
1172 "127.1.2.3:9000",
1173 ] {
1174 assert!(
1175 should_try_cleartext_fallback(
1176 "https",
1177 true,
1178 &AgentCardFetchError::Discovery("tls handshake failed".to_string()),
1179 authority,
1180 ),
1181 "expected cleartext fallback for loopback authority '{authority}'"
1182 );
1183 }
1184 }
1185
1186 #[test]
1187 fn cleartext_fallback_denies_external_tls_failures() {
1188 for authority in [
1191 "reviewer.example:443",
1192 "8.8.8.8:443",
1193 "192.168.1.10:8080",
1194 "10.0.0.5:8443",
1195 ] {
1196 assert!(
1197 !should_try_cleartext_fallback(
1198 "https",
1199 true,
1200 &AgentCardFetchError::Discovery("tls handshake failed".to_string()),
1201 authority,
1202 ),
1203 "cleartext fallback must be denied for external authority '{authority}'"
1204 );
1205 }
1206 }
1207
1208 #[test]
1209 fn is_loopback_authority_recognises_loopback_forms() {
1210 assert!(is_loopback_authority("127.0.0.1:8080"));
1211 assert!(is_loopback_authority("localhost:8080"));
1212 assert!(is_loopback_authority("LOCALHOST:9000"));
1213 assert!(is_loopback_authority("[::1]:8080"));
1214 assert!(is_loopback_authority("127.5.5.5:1234"));
1215 assert!(!is_loopback_authority("8.8.8.8:443"));
1216 assert!(!is_loopback_authority("192.168.1.10:8080"));
1217 assert!(!is_loopback_authority("example.com:443"));
1218 assert!(!is_loopback_authority("reviewer.prod"));
1219 }
1220
1221 #[test]
1222 fn endpoint_from_card_rejects_card_url_authority_mismatch() {
1223 let error = endpoint_from_card(
1224 "https://trusted.example/.well-known/agent-card.json".to_string(),
1225 false,
1226 "trusted.example",
1227 "triage".to_string(),
1228 &serde_json::json!({
1229 "protocolVersion": "0.3.0",
1230 "url": "https://evil.example",
1231 "preferredTransport": "JSONRPC",
1232 }),
1233 )
1234 .unwrap_err();
1235 assert_eq!(
1236 error.to_string(),
1237 "A2A agent card url authority mismatch: requested 'trusted.example', card returned 'evil.example'"
1238 );
1239 }
1240
1241 #[test]
1242 fn endpoint_from_card_rejects_cleartext_without_opt_in() {
1243 let error = endpoint_from_card(
1244 "https://127.0.0.1:8080/.well-known/agent-card.json".to_string(),
1245 false,
1246 "127.0.0.1:8080",
1247 "triage".to_string(),
1248 &serde_json::json!({
1249 "protocolVersion": "0.3.0",
1250 "url": "http://localhost:8080",
1251 "preferredTransport": "JSONRPC",
1252 }),
1253 )
1254 .expect_err("cleartext card should require explicit opt-in");
1255 assert!(error
1256 .to_string()
1257 .contains("requires `allow_cleartext = true`"));
1258 }
1259
1260 #[test]
1261 fn endpoint_from_card_accepts_loopback_alias_pairs_when_cleartext_opted_in() {
1262 let card = serde_json::json!({
1266 "protocolVersion": "0.3.0",
1267 "url": "http://localhost:8080",
1268 "preferredTransport": "JSONRPC",
1269 });
1270 let endpoint = endpoint_from_card(
1271 "http://127.0.0.1:8080/.well-known/agent-card.json".to_string(),
1272 true,
1273 "127.0.0.1:8080",
1274 "triage".to_string(),
1275 &card,
1276 )
1277 .expect("loopback alias pair should be accepted");
1278 assert_eq!(endpoint.rpc_url, "http://localhost:8080/");
1279
1280 let card_v6 = serde_json::json!({
1282 "protocolVersion": "0.3.0",
1283 "url": "http://[::1]:8080",
1284 "preferredTransport": "JSONRPC",
1285 });
1286 let endpoint_v6 = endpoint_from_card(
1287 "http://localhost:8080/.well-known/agent-card.json".to_string(),
1288 true,
1289 "localhost:8080",
1290 "triage".to_string(),
1291 &card_v6,
1292 )
1293 .expect("IPv6 loopback alias should be accepted");
1294 assert_eq!(endpoint_v6.rpc_url, "http://[::1]:8080/");
1295
1296 let card_wrong_port = serde_json::json!({
1298 "protocolVersion": "0.3.0",
1299 "url": "http://localhost:9000",
1300 "preferredTransport": "JSONRPC",
1301 });
1302 let error = endpoint_from_card(
1303 "http://127.0.0.1:8080/.well-known/agent-card.json".to_string(),
1304 true,
1305 "127.0.0.1:8080",
1306 "triage".to_string(),
1307 &card_wrong_port,
1308 )
1309 .expect_err("mismatched ports must still be rejected even on loopback");
1310 assert!(error
1311 .to_string()
1312 .contains("A2A agent card url authority mismatch"));
1313 }
1314
1315 #[test]
1316 fn authorities_equivalent_rejects_non_loopback_host_mismatch() {
1317 assert!(!authorities_equivalent(
1318 "internal.corp.example:443",
1319 "trusted.example:443",
1320 ));
1321 assert!(!authorities_equivalent("10.0.0.5:8080", "127.0.0.1:8080",));
1322 assert!(authorities_equivalent(
1323 "trusted.example:443",
1324 "trusted.example:443",
1325 ));
1326 }
1327}