1use std::{
13 collections::{HashSet, VecDeque},
14 fmt,
15 net::IpAddr,
16 pin::Pin,
17 sync::{
18 Arc,
19 atomic::{AtomicBool, AtomicU64, Ordering},
20 },
21 time::Duration,
22};
23
24use a2a as wire;
25use bytes::Bytes;
26use futures_core::Stream;
27use futures_util::{StreamExt, stream};
28use http::{HeaderMap, HeaderValue, Method, StatusCode, header};
29use reqwest::Url;
30use serde::{Serialize, de::DeserializeOwned};
31use serde_json::Value;
32use stateknot_core::{
33 AttemptId, BoundedJson, BoxFuture, Digest, InvocationId, JsonLimits, RunId, TenantId,
34};
35use thiserror::Error;
36
37use crate::{
38 A2A_AGENT_CARD_PATH, A2A_PROTOCOL_VERSION_1_0, A2aAgentCard, A2aAgentInterface, A2aBinding,
39 A2aCancelTaskRequest, A2aContractError, A2aDeletePushConfigRequest, A2aGetPushConfigRequest,
40 A2aGetTaskRequest, A2aListPushConfigsRequest, A2aListTasksRequest, A2aMessage, A2aMessageRole,
41 A2aPushConfig, A2aPushConfigPage, A2aSendMessageRequest, A2aSendMessageResponse,
42 A2aStreamEvent, A2aSubscribeTaskRequest, A2aTask, A2aTaskPage, A2aTaskState, ApiKey,
43 ProviderHttpOptions,
44 http::build_client,
45 sse::{SseDecoder, SseEvent},
46};
47
48const A2A_JSON: &str = "application/a2a+json";
49const JSON: &str = "application/json";
50const A2A_JSON_ACCEPT: &str = "application/a2a+json, application/json";
51const EVENT_STREAM: &str = "text/event-stream";
52const A2A_VERSION_HEADER: &str = "a2a-version";
53const A2A_EXTENSIONS_HEADER: &str = "a2a-extensions";
54const MAX_EXTENSION_HEADER_BYTES: usize = 8 * 1024;
55const MAX_EXTENSION_COUNT: usize = 64;
56const MAX_SECURITY_SCHEME_BYTES: usize = 512;
57const MAX_TENANT_BYTES: usize = 512;
58const MAX_REMOTE_ERROR_MESSAGE_BYTES: usize = 16 * 1024;
59
60#[derive(Clone, Eq, PartialEq)]
62pub struct A2aAgentCardEndpoint {
63 url: Url,
64 transport: A2aEndpointTransport,
65}
66
67#[derive(Clone, Eq, PartialEq)]
69pub struct A2aClientInterfacePin {
70 url: Url,
71 binding: A2aBinding,
72 tenant: Option<Box<str>>,
73 transport: A2aEndpointTransport,
74}
75
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77enum A2aEndpointTransport {
78 Https,
79 LoopbackHttp,
80}
81
82impl A2aAgentCardEndpoint {
83 pub fn https(value: &str) -> Result<Self, A2aClientEndpointError> {
85 Self::parse(value, A2aEndpointTransport::Https)
86 }
87
88 pub fn loopback_http(value: &str) -> Result<Self, A2aClientEndpointError> {
90 Self::parse(value, A2aEndpointTransport::LoopbackHttp)
91 }
92
93 fn parse(value: &str, transport: A2aEndpointTransport) -> Result<Self, A2aClientEndpointError> {
94 let url = parse_a2a_url(value, transport)?;
95 if url.path() != A2A_AGENT_CARD_PATH {
96 return Err(A2aClientEndpointError::AgentCardPathRequired);
97 }
98 Ok(Self { url, transport })
99 }
100}
101
102impl A2aClientInterfacePin {
103 pub fn https(value: &str, binding: A2aBinding) -> Result<Self, A2aClientEndpointError> {
105 Self::parse(value, binding, A2aEndpointTransport::Https)
106 }
107
108 pub fn loopback_http(value: &str, binding: A2aBinding) -> Result<Self, A2aClientEndpointError> {
110 Self::parse(value, binding, A2aEndpointTransport::LoopbackHttp)
111 }
112
113 fn parse(
114 value: &str,
115 binding: A2aBinding,
116 transport: A2aEndpointTransport,
117 ) -> Result<Self, A2aClientEndpointError> {
118 let url = parse_a2a_url(value, transport)?;
119 Ok(Self {
120 url,
121 binding,
122 tenant: None,
123 transport,
124 })
125 }
126
127 pub fn with_tenant(
129 mut self,
130 tenant: impl Into<String>,
131 ) -> Result<Self, A2aClientEndpointError> {
132 let tenant = tenant.into();
133 if tenant.is_empty()
134 || tenant.len() > MAX_TENANT_BYTES
135 || tenant.trim() != tenant
136 || tenant.chars().any(char::is_control)
137 {
138 return Err(A2aClientEndpointError::InvalidTenant);
139 }
140 self.tenant = Some(tenant.into_boxed_str());
141 Ok(self)
142 }
143
144 #[must_use]
146 pub const fn binding(&self) -> A2aBinding {
147 self.binding
148 }
149
150 #[must_use]
152 pub fn tenant(&self) -> Option<&str> {
153 self.tenant.as_deref()
154 }
155}
156
157fn parse_a2a_url(
158 value: &str,
159 transport: A2aEndpointTransport,
160) -> Result<Url, A2aClientEndpointError> {
161 let url = Url::parse(value).map_err(|_| A2aClientEndpointError::InvalidUrl)?;
162 if !url.username().is_empty() || url.password().is_some() {
163 return Err(A2aClientEndpointError::EmbeddedCredentials);
164 }
165 if url.query().is_some() || url.fragment().is_some() {
166 return Err(A2aClientEndpointError::QueryOrFragment);
167 }
168 let host = url.host_str().ok_or(A2aClientEndpointError::MissingHost)?;
169 match transport {
170 A2aEndpointTransport::Https if url.scheme() != "https" => {
171 return Err(A2aClientEndpointError::HttpsRequired);
172 }
173 A2aEndpointTransport::LoopbackHttp => {
174 if url.scheme() != "http" {
175 return Err(A2aClientEndpointError::LoopbackHttpRequired);
176 }
177 let address = host
178 .parse::<IpAddr>()
179 .map_err(|_| A2aClientEndpointError::LiteralLoopbackRequired)?;
180 if !address.is_loopback() {
181 return Err(A2aClientEndpointError::LiteralLoopbackRequired);
182 }
183 }
184 A2aEndpointTransport::Https => {}
185 }
186 Ok(url)
187}
188
189impl fmt::Debug for A2aAgentCardEndpoint {
190 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
191 formatter
192 .debug_struct("A2aAgentCardEndpoint")
193 .field("transport", &self.transport)
194 .field("url", &"[REDACTED]")
195 .finish()
196 }
197}
198
199impl fmt::Debug for A2aClientInterfacePin {
200 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
201 formatter
202 .debug_struct("A2aClientInterfacePin")
203 .field("binding", &self.binding)
204 .field("transport", &self.transport)
205 .field("url", &"[REDACTED]")
206 .field("tenant", &self.tenant.as_ref().map(|_| "[PINNED]"))
207 .finish()
208 }
209}
210
211#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
213#[non_exhaustive]
214pub enum A2aClientEndpointError {
215 #[error("A2A endpoint is not an absolute URL")]
217 InvalidUrl,
218 #[error("A2A endpoint must use HTTPS")]
220 HttpsRequired,
221 #[error("loopback A2A endpoint must use HTTP")]
223 LoopbackHttpRequired,
224 #[error("loopback A2A endpoint must use a literal loopback IP address")]
226 LiteralLoopbackRequired,
227 #[error("A2A endpoint must include a host")]
229 MissingHost,
230 #[error("A2A endpoint must not contain embedded credentials")]
232 EmbeddedCredentials,
233 #[error("A2A endpoint must not contain a query or fragment")]
235 QueryOrFragment,
236 #[error("A2A Agent Card endpoint must use /.well-known/agent-card.json")]
238 AgentCardPathRequired,
239 #[error("A2A interface cannot be used as an HTTP+JSON base URL")]
241 InvalidInterfaceBase,
242 #[error("A2A interface tenant pin is invalid")]
244 InvalidTenant,
245}
246
247#[derive(Clone, Copy, Debug, Eq, PartialEq)]
249#[non_exhaustive]
250pub enum A2aAgentCardTrust {
251 TlsServerIdentity,
253 CanonicalSha256(Digest),
255}
256
257pub fn a2a_agent_card_digest(value: &Value) -> Result<Digest, A2aContractError> {
259 let bytes =
260 serde_json_canonicalizer::to_vec(value).map_err(|_| A2aContractError::InvalidJson {
261 field: "Agent Card canonical form",
262 })?;
263 Ok(Digest::sha256(bytes))
264}
265
266#[derive(Clone, Copy, Debug, Eq, PartialEq)]
268pub struct A2aClientOptions {
269 transport: ProviderHttpOptions,
270 discovery_timeout: Duration,
271 request_timeout: Duration,
272 stream_idle_timeout: Duration,
273 maximum_stream_events: u32,
274}
275
276impl A2aClientOptions {
277 pub const HARD_MAXIMUM_STREAM_EVENTS: u32 = 65_536;
279 pub const HARD_MAXIMUM_TIMEOUT: Duration = Duration::from_secs(15 * 60);
281
282 pub const fn new(
284 transport: ProviderHttpOptions,
285 discovery_timeout: Duration,
286 request_timeout: Duration,
287 stream_idle_timeout: Duration,
288 maximum_stream_events: u32,
289 ) -> Result<Self, A2aClientOptionsError> {
290 if discovery_timeout.is_zero() || request_timeout.is_zero() || stream_idle_timeout.is_zero()
291 {
292 return Err(A2aClientOptionsError::ZeroTimeout);
293 }
294 if discovery_timeout.as_nanos() > Self::HARD_MAXIMUM_TIMEOUT.as_nanos()
295 || request_timeout.as_nanos() > Self::HARD_MAXIMUM_TIMEOUT.as_nanos()
296 || stream_idle_timeout.as_nanos() > Self::HARD_MAXIMUM_TIMEOUT.as_nanos()
297 {
298 return Err(A2aClientOptionsError::TimeoutAboveHardMaximum);
299 }
300 if maximum_stream_events == 0 || maximum_stream_events > Self::HARD_MAXIMUM_STREAM_EVENTS {
301 return Err(A2aClientOptionsError::InvalidStreamEventLimit);
302 }
303 Ok(Self {
304 transport,
305 discovery_timeout,
306 request_timeout,
307 stream_idle_timeout,
308 maximum_stream_events,
309 })
310 }
311
312 #[must_use]
314 pub const fn transport(self) -> ProviderHttpOptions {
315 self.transport
316 }
317}
318
319impl Default for A2aClientOptions {
320 fn default() -> Self {
321 Self {
322 transport: ProviderHttpOptions::default(),
323 discovery_timeout: Duration::from_secs(15),
324 request_timeout: Duration::from_secs(60),
325 stream_idle_timeout: Duration::from_secs(60),
326 maximum_stream_events: 4096,
327 }
328 }
329}
330
331#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
333#[non_exhaustive]
334pub enum A2aClientOptionsError {
335 #[error("A2A client timeouts must be positive")]
337 ZeroTimeout,
338 #[error("A2A client timeout exceeds the hard maximum")]
340 TimeoutAboveHardMaximum,
341 #[error("A2A stream event limit is invalid")]
343 InvalidStreamEventLimit,
344}
345
346#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
348#[non_exhaustive]
349pub enum A2aClientOperation {
350 SendMessage,
352 SendStreamingMessage,
354 GetTask,
356 ListTasks,
358 CancelTask,
360 SubscribeToTask,
362 CreatePushConfig,
364 GetPushConfig,
366 ListPushConfigs,
368 DeletePushConfig,
370 GetExtendedAgentCard,
372}
373
374#[derive(Clone, Debug, Eq, PartialEq)]
376#[allow(clippy::struct_field_names)]
377pub struct A2aClientAttemptIdentity {
378 tenant_id: TenantId,
379 run_id: RunId,
380 invocation_id: InvocationId,
381 attempt_id: AttemptId,
382}
383
384impl A2aClientAttemptIdentity {
385 pub(crate) fn new(
386 tenant_id: TenantId,
387 run_id: RunId,
388 invocation_id: InvocationId,
389 attempt_id: AttemptId,
390 ) -> Self {
391 Self {
392 tenant_id,
393 run_id,
394 invocation_id,
395 attempt_id,
396 }
397 }
398
399 #[must_use]
401 pub const fn tenant_id(&self) -> &TenantId {
402 &self.tenant_id
403 }
404
405 #[must_use]
407 pub const fn run_id(&self) -> RunId {
408 self.run_id
409 }
410
411 #[must_use]
413 pub const fn invocation_id(&self) -> InvocationId {
414 self.invocation_id
415 }
416
417 #[must_use]
419 pub const fn attempt_id(&self) -> AttemptId {
420 self.attempt_id
421 }
422}
423
424#[derive(Clone, Debug)]
426pub struct A2aClientAuthorizationRequest {
427 operation: A2aClientOperation,
428 card_digest: Digest,
429 binding: A2aBinding,
430 remote_tenant: Option<Box<str>>,
431 task_id: Option<Box<str>>,
432 required_scopes: Arc<[Box<str>]>,
433 attempt: Option<A2aClientAttemptIdentity>,
434}
435
436impl A2aClientAuthorizationRequest {
437 #[must_use]
439 pub const fn operation(&self) -> A2aClientOperation {
440 self.operation
441 }
442
443 #[must_use]
445 pub const fn card_digest(&self) -> Digest {
446 self.card_digest
447 }
448
449 #[must_use]
451 pub const fn binding(&self) -> A2aBinding {
452 self.binding
453 }
454
455 #[must_use]
457 pub fn remote_tenant(&self) -> Option<&str> {
458 self.remote_tenant.as_deref()
459 }
460
461 #[must_use]
463 pub fn task_id(&self) -> Option<&str> {
464 self.task_id.as_deref()
465 }
466
467 pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
469 self.required_scopes.iter().map(AsRef::as_ref)
470 }
471
472 #[must_use]
474 pub const fn attempt(&self) -> Option<&A2aClientAttemptIdentity> {
475 self.attempt.as_ref()
476 }
477}
478
479#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
481#[non_exhaustive]
482pub enum A2aClientAuthorizationError {
483 #[error("A2A authorization source is unavailable")]
485 Unavailable,
486 #[error("A2A authorization access was denied")]
488 PermissionDenied,
489}
490
491pub trait A2aBearerTokenProvider: Send + Sync + 'static {
493 fn resolve(
495 &self,
496 request: &A2aClientAuthorizationRequest,
497 ) -> BoxFuture<'_, Result<ApiKey, A2aClientAuthorizationError>>;
498}
499
500#[derive(Clone)]
502pub struct StaticA2aBearerToken {
503 token: Arc<ApiKey>,
504}
505
506impl StaticA2aBearerToken {
507 #[must_use]
509 pub fn new(token: ApiKey) -> Self {
510 Self {
511 token: Arc::new(token),
512 }
513 }
514}
515
516impl A2aBearerTokenProvider for StaticA2aBearerToken {
517 fn resolve(
518 &self,
519 _request: &A2aClientAuthorizationRequest,
520 ) -> BoxFuture<'_, Result<ApiKey, A2aClientAuthorizationError>> {
521 let token = self.token.as_ref().clone();
522 Box::pin(async move { Ok(token) })
523 }
524}
525
526impl fmt::Debug for StaticA2aBearerToken {
527 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
528 formatter.write_str("StaticA2aBearerToken([REDACTED])")
529 }
530}
531
532#[derive(Clone)]
534#[non_exhaustive]
535pub enum A2aClientSecurity {
536 Anonymous,
538 Bearer {
540 scheme: Box<str>,
542 provider: Arc<dyn A2aBearerTokenProvider>,
544 },
545}
546
547impl A2aClientSecurity {
548 pub fn bearer(
550 scheme: impl Into<String>,
551 provider: Arc<dyn A2aBearerTokenProvider>,
552 ) -> Result<Self, A2aClientSecurityError> {
553 let scheme = scheme.into();
554 if scheme.is_empty()
555 || scheme.len() > MAX_SECURITY_SCHEME_BYTES
556 || scheme.trim() != scheme
557 || scheme.chars().any(char::is_control)
558 {
559 return Err(A2aClientSecurityError::InvalidSchemeName);
560 }
561 Ok(Self::Bearer {
562 scheme: scheme.into_boxed_str(),
563 provider,
564 })
565 }
566
567 pub(crate) fn requires_credentials(&self) -> bool {
568 matches!(self, Self::Bearer { .. })
569 }
570}
571
572impl fmt::Debug for A2aClientSecurity {
573 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
574 match self {
575 Self::Anonymous => formatter.write_str("A2aClientSecurity::Anonymous"),
576 Self::Bearer { scheme, .. } => formatter
577 .debug_struct("A2aClientSecurity::Bearer")
578 .field("scheme", scheme)
579 .field("provider", &"[REDACTED]")
580 .finish(),
581 }
582 }
583}
584
585#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
587#[non_exhaustive]
588pub enum A2aClientSecurityError {
589 #[error("A2A security scheme name is invalid")]
591 InvalidSchemeName,
592 #[error("A2A Agent Card requires authentication")]
594 AnonymousNotAllowed,
595 #[error("A2A bearer scheme is unavailable or unsupported")]
597 BearerSchemeUnsupported,
598 #[error("A2A bearer scheme does not satisfy a complete security requirement")]
600 RequirementNotSatisfied,
601}
602
603#[derive(Clone, Copy, Debug, Eq, PartialEq)]
605#[non_exhaustive]
606pub enum A2aClientErrorKind {
607 Authorization,
609 Request,
611 Transport,
613 HttpProtocol,
615 Remote,
617 InvalidResponse,
619 Capability,
621}
622
623#[derive(Clone, Debug, Error)]
626#[error("A2A client operation failed: {kind:?}")]
627pub struct A2aClientError {
628 kind: A2aClientErrorKind,
629 dispatched: bool,
630 remote_code: Option<i32>,
631 http_status: Option<u16>,
632 authorization_error: Option<A2aClientAuthorizationError>,
633}
634
635impl A2aClientError {
636 const fn before(kind: A2aClientErrorKind) -> Self {
637 Self {
638 kind,
639 dispatched: false,
640 remote_code: None,
641 http_status: None,
642 authorization_error: None,
643 }
644 }
645
646 const fn after(kind: A2aClientErrorKind) -> Self {
647 Self {
648 kind,
649 dispatched: true,
650 remote_code: None,
651 http_status: None,
652 authorization_error: None,
653 }
654 }
655
656 const fn after_http(kind: A2aClientErrorKind, status: StatusCode) -> Self {
657 Self {
658 kind,
659 dispatched: true,
660 remote_code: None,
661 http_status: Some(status.as_u16()),
662 authorization_error: None,
663 }
664 }
665
666 const fn remote(code: Option<i32>, status: Option<StatusCode>) -> Self {
667 Self {
668 kind: A2aClientErrorKind::Remote,
669 dispatched: true,
670 remote_code: code,
671 http_status: match status {
672 Some(status) => Some(status.as_u16()),
673 None => None,
674 },
675 authorization_error: None,
676 }
677 }
678
679 const fn authorization(error: A2aClientAuthorizationError) -> Self {
680 Self {
681 kind: A2aClientErrorKind::Authorization,
682 dispatched: false,
683 remote_code: None,
684 http_status: None,
685 authorization_error: Some(error),
686 }
687 }
688
689 #[must_use]
691 pub const fn kind(&self) -> A2aClientErrorKind {
692 self.kind
693 }
694
695 #[must_use]
697 pub const fn was_dispatched(&self) -> bool {
698 self.dispatched
699 }
700
701 #[must_use]
703 pub const fn remote_code(&self) -> Option<i32> {
704 self.remote_code
705 }
706
707 #[must_use]
709 pub const fn http_status(&self) -> Option<u16> {
710 self.http_status
711 }
712
713 #[must_use]
715 pub const fn authorization_error(&self) -> Option<A2aClientAuthorizationError> {
716 self.authorization_error
717 }
718}
719
720#[derive(Debug, Error)]
722#[non_exhaustive]
723pub enum A2aClientBuildError {
724 #[error("A2A client requires at least one interface pin")]
726 MissingInterfacePin,
727 #[error("A2A client interface pin limit exceeded")]
729 TooManyInterfacePins,
730 #[error("A2A client contains a duplicate interface pin")]
732 DuplicateInterfacePin,
733 #[error("A2A client extension selection is invalid")]
735 InvalidExtensions,
736 #[error("A2A HTTP client construction failed")]
738 HttpClient,
739 #[error("A2A Agent Card discovery failed")]
741 Discovery,
742 #[error("A2A Agent Card response is invalid")]
744 InvalidAgentCard,
745 #[error("A2A TLS server-identity trust requires HTTPS discovery")]
747 TlsTrustRequiresHttps,
748 #[error("A2A Agent Card digest does not match the configured trust anchor")]
750 AgentCardDigestMismatch,
751 #[error("A2A Agent Card has no supported 1.0 HTTP interface")]
753 NoSupportedInterface,
754 #[error("A2A preferred interface does not match an egress pin")]
756 InterfacePinMismatch,
757 #[error("A2A extension negotiation failed")]
759 ExtensionMismatch,
760 #[error(transparent)]
762 Security(#[from] A2aClientSecurityError),
763}
764
765pub type A2aClientEventStream =
767 Pin<Box<dyn Stream<Item = Result<A2aStreamEvent, A2aClientError>> + Send + 'static>>;
768
769#[derive(Clone)]
770struct A2aSendExpectation {
771 task_id: Option<Box<str>>,
772 context_id: Option<Box<str>>,
773 history_length: Option<u32>,
774 return_immediately: bool,
775}
776
777impl A2aSendExpectation {
778 fn from_request(request: &A2aSendMessageRequest) -> Self {
779 Self {
780 task_id: request.message().task_id().map(Into::into),
781 context_id: request.message().context_id().map(Into::into),
782 history_length: request
783 .configuration()
784 .and_then(crate::A2aSendConfiguration::history_length),
785 return_immediately: request
786 .configuration()
787 .is_some_and(crate::A2aSendConfiguration::should_return_immediately),
788 }
789 }
790}
791
792struct A2aListTasksExpectation {
793 context_id: Option<Box<str>>,
794 status: Option<A2aTaskState>,
795 status_timestamp_after: Option<chrono::DateTime<chrono::Utc>>,
796 page_size: u16,
797 history_length: Option<u32>,
798 include_artifacts: bool,
799}
800
801impl A2aListTasksExpectation {
802 fn from_request(request: &A2aListTasksRequest) -> Self {
803 Self {
804 context_id: request.context_id().map(Into::into),
805 status: request.status(),
806 status_timestamp_after: request.status_timestamp_after(),
807 page_size: request.page_size(),
808 history_length: request.history_length(),
809 include_artifacts: request.should_include_artifacts(),
810 }
811 }
812}
813
814#[derive(Clone)]
815struct A2aCallScope {
816 task_id: Option<Box<str>>,
817 attempt: Option<A2aClientAttemptIdentity>,
818 required_scopes: Option<Arc<[Box<str>]>>,
819 dispatch_observer: Option<Arc<AtomicBool>>,
820}
821
822impl A2aCallScope {
823 fn new(task_id: Option<&str>) -> Self {
824 Self {
825 task_id: task_id.map(Into::into),
826 attempt: None,
827 required_scopes: None,
828 dispatch_observer: None,
829 }
830 }
831
832 fn with_attempt(mut self, attempt: A2aClientAttemptIdentity) -> Self {
833 self.attempt = Some(attempt);
834 self
835 }
836
837 fn with_required_scopes(mut self, required_scopes: Arc<[Box<str>]>) -> Self {
838 self.required_scopes = Some(required_scopes);
839 self
840 }
841
842 fn with_dispatch_observer(mut self, observer: Arc<AtomicBool>) -> Self {
843 self.dispatch_observer = Some(observer);
844 self
845 }
846
847 fn mark_dispatched(&self) {
848 if let Some(observer) = &self.dispatch_observer {
849 observer.store(true, Ordering::Release);
850 }
851 }
852}
853
854#[derive(Clone)]
856pub struct A2aClient {
857 card: A2aAgentCard,
858 card_digest: Digest,
859 interface: A2aAgentInterface,
860 interface_url: Url,
861 security: A2aClientSecurity,
862 required_scopes: Arc<[Box<str>]>,
863 extensions: Arc<[Box<str>]>,
864 options: A2aClientOptions,
865 http: reqwest::Client,
866 next_request_id: Arc<AtomicU64>,
867}
868
869impl fmt::Debug for A2aClient {
870 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
871 formatter
872 .debug_struct("A2aClient")
873 .field("agent", &self.card.name())
874 .field("agent_version", &self.card.agent_version())
875 .field("card_digest", &self.card_digest)
876 .field("binding", &self.interface.binding())
877 .field("interface_url", &"[REDACTED]")
878 .field("security", &self.security)
879 .field("extensions", &self.extensions.len())
880 .finish_non_exhaustive()
881 }
882}
883
884impl A2aClient {
885 #[allow(clippy::too_many_lines)]
887 #[allow(clippy::too_many_arguments)]
888 pub async fn discover(
889 card_endpoint: A2aAgentCardEndpoint,
890 interface_pins: Vec<A2aClientInterfacePin>,
891 trust: A2aAgentCardTrust,
892 security: A2aClientSecurity,
893 extensions: Vec<String>,
894 options: A2aClientOptions,
895 ) -> Result<Self, A2aClientBuildError> {
896 validate_interface_pins(&interface_pins)?;
897 validate_extension_selection(&extensions)?;
898 if matches!(trust, A2aAgentCardTrust::TlsServerIdentity)
899 && card_endpoint.transport != A2aEndpointTransport::Https
900 {
901 return Err(A2aClientBuildError::TlsTrustRequiresHttps);
902 }
903
904 let http =
905 build_client(options.transport()).map_err(|_| A2aClientBuildError::HttpClient)?;
906 let deadline = tokio::time::Instant::now() + options.discovery_timeout;
907 let response = wait_until(deadline, async {
908 http.get(card_endpoint.url.clone())
909 .header(header::ACCEPT, format!("{JSON}, {A2A_JSON}"))
910 .send()
911 .await
912 })
913 .await
914 .map_err(|()| A2aClientBuildError::Discovery)?
915 .map_err(|_| A2aClientBuildError::Discovery)?;
916 if !response.status().is_success() || !is_json_content_type(response.headers()) {
917 return Err(A2aClientBuildError::Discovery);
918 }
919 let bytes = wait_until(
920 deadline,
921 bounded_body(response, options.transport().maximum_response_bytes()),
922 )
923 .await
924 .map_err(|()| A2aClientBuildError::Discovery)?
925 .map_err(|error| match error {
926 BoundedBodyError::Transport => A2aClientBuildError::Discovery,
927 BoundedBodyError::TooLarge => A2aClientBuildError::InvalidAgentCard,
928 })?;
929 let value = BoundedJson::from_slice_with_limits(&bytes, JsonLimits::MAXIMUM)
930 .map_err(|_| A2aClientBuildError::InvalidAgentCard)?
931 .into_value();
932 let card_digest =
933 a2a_agent_card_digest(&value).map_err(|_| A2aClientBuildError::InvalidAgentCard)?;
934 if let A2aAgentCardTrust::CanonicalSha256(expected) = trust {
935 if card_digest != expected {
936 return Err(A2aClientBuildError::AgentCardDigestMismatch);
937 }
938 }
939 let card =
940 A2aAgentCard::from_json(value).map_err(|_| A2aClientBuildError::InvalidAgentCard)?;
941 let selected = card
942 .wire()
943 .supported_interfaces
944 .iter()
945 .find(|candidate| {
946 candidate.protocol_version == A2A_PROTOCOL_VERSION_1_0
947 && A2aBinding::try_from(candidate.protocol_binding.as_str()).is_ok()
948 })
949 .cloned()
950 .ok_or(A2aClientBuildError::NoSupportedInterface)?;
951 let interface = A2aAgentInterface::try_from_wire(selected)
952 .map_err(|_| A2aClientBuildError::NoSupportedInterface)?;
953 let interface_url =
954 Url::parse(interface.url()).map_err(|_| A2aClientBuildError::NoSupportedInterface)?;
955 let pin = interface_pins
956 .iter()
957 .find(|pin| {
958 pin.binding == interface.binding()
959 && pin.url == interface_url
960 && pin.tenant.as_deref() == interface.tenant()
961 })
962 .ok_or(A2aClientBuildError::InterfacePinMismatch)?;
963 match pin.transport {
964 A2aEndpointTransport::Https if interface_url.scheme() != "https" => {
965 return Err(A2aClientBuildError::InterfacePinMismatch);
966 }
967 A2aEndpointTransport::LoopbackHttp if interface_url.scheme() != "http" => {
968 return Err(A2aClientBuildError::InterfacePinMismatch);
969 }
970 A2aEndpointTransport::Https | A2aEndpointTransport::LoopbackHttp => {}
971 }
972
973 let capabilities = card.capabilities();
974 let declared_extensions = capabilities.extensions();
975 for extension in &extensions {
976 if !declared_extensions
977 .iter()
978 .any(|candidate| candidate.uri() == extension)
979 {
980 return Err(A2aClientBuildError::ExtensionMismatch);
981 }
982 }
983 if declared_extensions.iter().any(|required| {
984 required.is_required() && !extensions.iter().any(|value| value == required.uri())
985 }) {
986 return Err(A2aClientBuildError::ExtensionMismatch);
987 }
988
989 let required_scopes = select_security_requirements(
990 card.wire().security_requirements.as_deref(),
991 card.wire().security_schemes.as_ref(),
992 &security,
993 )?;
994 Ok(Self {
995 card,
996 card_digest,
997 interface,
998 interface_url,
999 security,
1000 required_scopes,
1001 extensions: extensions
1002 .into_iter()
1003 .map(String::into_boxed_str)
1004 .collect::<Vec<_>>()
1005 .into(),
1006 options,
1007 http,
1008 next_request_id: Arc::new(AtomicU64::new(1)),
1009 })
1010 }
1011
1012 #[must_use]
1014 pub const fn agent_card(&self) -> &A2aAgentCard {
1015 &self.card
1016 }
1017
1018 #[must_use]
1020 pub const fn agent_card_digest(&self) -> Digest {
1021 self.card_digest
1022 }
1023
1024 #[must_use]
1026 pub const fn interface(&self) -> &A2aAgentInterface {
1027 &self.interface
1028 }
1029
1030 pub fn negotiated_extensions(&self) -> impl ExactSizeIterator<Item = &str> {
1032 self.extensions.iter().map(AsRef::as_ref)
1033 }
1034
1035 pub(crate) fn requires_credentials(&self) -> bool {
1036 self.security.requires_credentials()
1037 }
1038
1039 pub async fn send_message(
1041 &self,
1042 request: A2aSendMessageRequest,
1043 ) -> Result<A2aSendMessageResponse, A2aClientError> {
1044 self.send_message_scoped(request, A2aCallScope::new(None))
1045 .await
1046 }
1047
1048 pub(crate) async fn send_message_with_attempt(
1049 &self,
1050 request: A2aSendMessageRequest,
1051 attempt: A2aClientAttemptIdentity,
1052 required_scopes: Arc<[Box<str>]>,
1053 dispatch_observer: Arc<AtomicBool>,
1054 ) -> Result<A2aSendMessageResponse, A2aClientError> {
1055 self.send_message_scoped(
1056 request,
1057 A2aCallScope::new(None)
1058 .with_attempt(attempt)
1059 .with_required_scopes(required_scopes)
1060 .with_dispatch_observer(dispatch_observer),
1061 )
1062 .await
1063 }
1064
1065 async fn send_message_scoped(
1066 &self,
1067 request: A2aSendMessageRequest,
1068 mut scope: A2aCallScope,
1069 ) -> Result<A2aSendMessageResponse, A2aClientError> {
1070 if request
1071 .configuration()
1072 .and_then(|configuration| configuration.push_config())
1073 .is_some()
1074 && !self.card.capabilities().supports_push_notifications()
1075 {
1076 return Err(A2aClientError::before(A2aClientErrorKind::Capability));
1077 }
1078 let expectation = A2aSendExpectation::from_request(&request);
1079 scope.task_id.clone_from(&expectation.task_id);
1080 let wire = request
1081 .into_wire(self.tenant())
1082 .map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))?;
1083 let params = encode_value(&wire)?;
1084 let rest = RestRequest::json(
1085 Method::POST,
1086 self.rest_url(&["message:send"])?,
1087 params.clone(),
1088 );
1089 let value = self
1090 .call_unary(
1091 A2aClientOperation::SendMessage,
1092 wire::methods::SEND_MESSAGE,
1093 params,
1094 rest,
1095 scope,
1096 )
1097 .await?;
1098 require_exact_variant(&value, &["task", "message"])?;
1099 let response = decode_value::<wire::SendMessageResponse>(value).and_then(|value| {
1100 A2aSendMessageResponse::try_from_wire(value)
1101 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1102 })?;
1103 validate_send_response(&response, &expectation)?;
1104 Ok(response)
1105 }
1106
1107 pub async fn send_streaming_message(
1109 &self,
1110 request: A2aSendMessageRequest,
1111 ) -> Result<A2aClientEventStream, A2aClientError> {
1112 if !self.card.capabilities().supports_streaming() {
1113 return Err(A2aClientError::before(A2aClientErrorKind::Capability));
1114 }
1115 if request
1116 .configuration()
1117 .and_then(|configuration| configuration.push_config())
1118 .is_some()
1119 && !self.card.capabilities().supports_push_notifications()
1120 {
1121 return Err(A2aClientError::before(A2aClientErrorKind::Capability));
1122 }
1123 let expectation = A2aSendExpectation::from_request(&request);
1124 let scope = A2aCallScope::new(expectation.task_id.as_deref());
1125 let wire = request
1126 .into_wire(self.tenant())
1127 .map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))?;
1128 let params = encode_value(&wire)?;
1129 let rest = RestRequest::json(
1130 Method::POST,
1131 self.rest_url(&["message:stream"])?,
1132 params.clone(),
1133 );
1134 self.call_stream(
1135 A2aClientOperation::SendStreamingMessage,
1136 wire::methods::SEND_STREAMING_MESSAGE,
1137 params,
1138 rest,
1139 scope,
1140 A2aStreamContract::SendMessage(expectation),
1141 )
1142 .await
1143 }
1144
1145 pub async fn get_task(&self, request: A2aGetTaskRequest) -> Result<A2aTask, A2aClientError> {
1147 self.get_task_scoped(request, A2aCallScope::new(None)).await
1148 }
1149
1150 pub(crate) async fn get_task_with_attempt(
1151 &self,
1152 request: A2aGetTaskRequest,
1153 attempt: A2aClientAttemptIdentity,
1154 required_scopes: Arc<[Box<str>]>,
1155 ) -> Result<A2aTask, A2aClientError> {
1156 self.get_task_scoped(
1157 request,
1158 A2aCallScope::new(None)
1159 .with_attempt(attempt)
1160 .with_required_scopes(required_scopes),
1161 )
1162 .await
1163 }
1164
1165 async fn get_task_scoped(
1166 &self,
1167 request: A2aGetTaskRequest,
1168 mut scope: A2aCallScope,
1169 ) -> Result<A2aTask, A2aClientError> {
1170 let task_id = request.id().to_owned();
1171 let history_length = request.history_length();
1172 scope.task_id = Some(task_id.clone().into_boxed_str());
1173 let wire = request
1174 .into_wire(self.tenant())
1175 .map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))?;
1176 let mut url = self.rest_url(&["tasks", &task_id])?;
1177 if let Some(length) = wire.history_length {
1178 url.query_pairs_mut()
1179 .append_pair("historyLength", &length.to_string());
1180 }
1181 let params = encode_value(&wire)?;
1182 let value = self
1183 .call_unary(
1184 A2aClientOperation::GetTask,
1185 wire::methods::GET_TASK,
1186 params,
1187 RestRequest::empty(Method::GET, url),
1188 scope,
1189 )
1190 .await?;
1191 let task = decode_value::<wire::Task>(value).and_then(|value| {
1192 A2aTask::try_from_wire(value)
1193 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1194 })?;
1195 validate_task_response(&task, Some(&task_id), None, history_length)?;
1196 Ok(task)
1197 }
1198
1199 pub async fn list_tasks(
1201 &self,
1202 request: A2aListTasksRequest,
1203 ) -> Result<A2aTaskPage, A2aClientError> {
1204 self.list_tasks_scoped(request, A2aCallScope::new(None))
1205 .await
1206 }
1207
1208 pub(crate) async fn list_tasks_with_attempt(
1209 &self,
1210 request: A2aListTasksRequest,
1211 attempt: A2aClientAttemptIdentity,
1212 required_scopes: Arc<[Box<str>]>,
1213 ) -> Result<A2aTaskPage, A2aClientError> {
1214 self.list_tasks_scoped(
1215 request,
1216 A2aCallScope::new(None)
1217 .with_attempt(attempt)
1218 .with_required_scopes(required_scopes),
1219 )
1220 .await
1221 }
1222
1223 async fn list_tasks_scoped(
1224 &self,
1225 request: A2aListTasksRequest,
1226 scope: A2aCallScope,
1227 ) -> Result<A2aTaskPage, A2aClientError> {
1228 let expectation = A2aListTasksExpectation::from_request(&request);
1229 let wire = request.into_wire(self.tenant());
1230 let mut url = self.rest_url(&["tasks"])?;
1231 {
1232 let mut query = url.query_pairs_mut();
1233 if let Some(value) = wire.context_id.as_deref() {
1234 query.append_pair("contextId", value);
1235 }
1236 if let Some(value) = wire.status.as_ref() {
1237 let value = serde_json::to_value(value)
1238 .ok()
1239 .and_then(|value| value.as_str().map(ToOwned::to_owned))
1240 .ok_or_else(|| A2aClientError::before(A2aClientErrorKind::Request))?;
1241 query.append_pair("status", &value);
1242 }
1243 if let Some(value) = wire.page_size {
1244 query.append_pair("pageSize", &value.to_string());
1245 }
1246 if let Some(value) = wire.page_token.as_deref() {
1247 query.append_pair("pageToken", value);
1248 }
1249 if let Some(value) = wire.history_length {
1250 query.append_pair("historyLength", &value.to_string());
1251 }
1252 if let Some(value) = wire.status_timestamp_after {
1253 query.append_pair(
1254 "statusTimestampAfter",
1255 &value.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true),
1256 );
1257 }
1258 if let Some(value) = wire.include_artifacts {
1259 query.append_pair("includeArtifacts", if value { "true" } else { "false" });
1260 }
1261 }
1262 let params = encode_value(&wire)?;
1263 let value = self
1264 .call_unary(
1265 A2aClientOperation::ListTasks,
1266 wire::methods::LIST_TASKS,
1267 params,
1268 RestRequest::empty(Method::GET, url),
1269 scope,
1270 )
1271 .await?;
1272 let page = decode_value::<wire::ListTasksResponse>(value).and_then(|value| {
1273 A2aTaskPage::try_from_wire(value)
1274 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1275 })?;
1276 validate_task_page(&page, &expectation)?;
1277 Ok(page)
1278 }
1279
1280 pub async fn cancel_task(
1282 &self,
1283 request: A2aCancelTaskRequest,
1284 ) -> Result<A2aTask, A2aClientError> {
1285 let task_id = request.id().to_owned();
1286 let wire = request.into_wire(self.tenant());
1287 let params = encode_value(&wire)?;
1288 let action = format!("{task_id}:cancel");
1289 let value = self
1290 .call_unary(
1291 A2aClientOperation::CancelTask,
1292 wire::methods::CANCEL_TASK,
1293 params.clone(),
1294 RestRequest::json(Method::POST, self.rest_url(&["tasks", &action])?, params),
1295 A2aCallScope::new(Some(&task_id)),
1296 )
1297 .await?;
1298 let task = decode_value::<wire::Task>(value).and_then(|value| {
1299 A2aTask::try_from_wire(value)
1300 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1301 })?;
1302 validate_task_response(&task, Some(&task_id), None, None)?;
1303 Ok(task)
1304 }
1305
1306 pub async fn subscribe_to_task(
1308 &self,
1309 request: A2aSubscribeTaskRequest,
1310 ) -> Result<A2aClientEventStream, A2aClientError> {
1311 if !self.card.capabilities().supports_streaming() {
1312 return Err(A2aClientError::before(A2aClientErrorKind::Capability));
1313 }
1314 let task_id = request.id().to_owned();
1315 let wire = request.into_wire(self.tenant());
1316 let params = encode_value(&wire)?;
1317 let action = format!("{task_id}:subscribe");
1318 self.call_stream(
1319 A2aClientOperation::SubscribeToTask,
1320 wire::methods::SUBSCRIBE_TO_TASK,
1321 params,
1322 RestRequest::empty(Method::POST, self.rest_url(&["tasks", &action])?),
1323 A2aCallScope::new(Some(&task_id)),
1324 A2aStreamContract::SubscribeToTask(task_id.into_boxed_str()),
1325 )
1326 .await
1327 }
1328
1329 pub async fn create_push_config(
1331 &self,
1332 config: A2aPushConfig,
1333 ) -> Result<A2aPushConfig, A2aClientError> {
1334 self.require_push_capability()?;
1335 let task_id = config
1336 .task_id()
1337 .ok_or_else(|| A2aClientError::before(A2aClientErrorKind::Request))?
1338 .to_owned();
1339 let wire = config.into_wire_for_tenant(self.tenant());
1340 let params = encode_value(&wire)?;
1341 let value = self
1342 .call_unary(
1343 A2aClientOperation::CreatePushConfig,
1344 wire::methods::CREATE_PUSH_CONFIG,
1345 params.clone(),
1346 RestRequest::json(
1347 Method::POST,
1348 self.rest_url(&["tasks", &task_id, "pushNotificationConfigs"])?,
1349 params,
1350 ),
1351 A2aCallScope::new(Some(&task_id)),
1352 )
1353 .await?;
1354 let value = decode_value::<wire::TaskPushNotificationConfig>(value)?;
1355 let config = decode_push_config(value, self.interface.tenant())?;
1356 validate_push_config_identity(&config, &task_id, None, true)?;
1357 Ok(config)
1358 }
1359
1360 pub async fn get_push_config(
1362 &self,
1363 request: A2aGetPushConfigRequest,
1364 ) -> Result<A2aPushConfig, A2aClientError> {
1365 self.require_push_capability()?;
1366 let task_id = request.task_id().to_owned();
1367 let config_id = request.config_id().to_owned();
1368 let wire = request.into_get_wire(self.tenant());
1369 let params = encode_value(&wire)?;
1370 let value = self
1371 .call_unary(
1372 A2aClientOperation::GetPushConfig,
1373 wire::methods::GET_PUSH_CONFIG,
1374 params,
1375 RestRequest::empty(
1376 Method::GET,
1377 self.rest_url(&["tasks", &task_id, "pushNotificationConfigs", &config_id])?,
1378 ),
1379 A2aCallScope::new(Some(&task_id)),
1380 )
1381 .await?;
1382 let value = decode_value::<wire::TaskPushNotificationConfig>(value)?;
1383 let config = decode_push_config(value, self.interface.tenant())?;
1384 validate_push_config_identity(&config, &task_id, Some(&config_id), true)?;
1385 Ok(config)
1386 }
1387
1388 pub async fn list_push_configs(
1390 &self,
1391 request: A2aListPushConfigsRequest,
1392 ) -> Result<A2aPushConfigPage, A2aClientError> {
1393 self.require_push_capability()?;
1394 let task_id = request.task_id().to_owned();
1395 let page_size = request.page_size();
1396 let wire = request.into_wire(self.tenant());
1397 let mut url = self.rest_url(&["tasks", &task_id, "pushNotificationConfigs"])?;
1398 {
1399 let mut query = url.query_pairs_mut();
1400 if let Some(value) = wire.page_size {
1401 query.append_pair("pageSize", &value.to_string());
1402 }
1403 if let Some(value) = wire.page_token.as_deref() {
1404 query.append_pair("pageToken", value);
1405 }
1406 }
1407 let params = encode_value(&wire)?;
1408 let value = self
1409 .call_unary(
1410 A2aClientOperation::ListPushConfigs,
1411 wire::methods::LIST_PUSH_CONFIGS,
1412 params,
1413 RestRequest::empty(Method::GET, url),
1414 A2aCallScope::new(Some(&task_id)),
1415 )
1416 .await?;
1417 let mut value = decode_value::<wire::ListTaskPushNotificationConfigsResponse>(value)?;
1418 for config in &mut value.configs {
1419 strip_response_tenant(config, self.interface.tenant())?;
1420 }
1421 let page = A2aPushConfigPage::try_from_wire(value)
1422 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))?;
1423 validate_push_config_page(&page, &task_id, page_size)?;
1424 Ok(page)
1425 }
1426
1427 pub async fn delete_push_config(
1429 &self,
1430 request: A2aDeletePushConfigRequest,
1431 ) -> Result<(), A2aClientError> {
1432 self.require_push_capability()?;
1433 let task_id = request.task_id().to_owned();
1434 let config_id = request.config_id().to_owned();
1435 let wire = request.into_delete_wire(self.tenant());
1436 let params = encode_value(&wire)?;
1437 let value = self
1438 .call_unary(
1439 A2aClientOperation::DeletePushConfig,
1440 wire::methods::DELETE_PUSH_CONFIG,
1441 params,
1442 RestRequest::empty_response(
1443 Method::DELETE,
1444 self.rest_url(&["tasks", &task_id, "pushNotificationConfigs", &config_id])?,
1445 ),
1446 A2aCallScope::new(Some(&task_id)),
1447 )
1448 .await?;
1449 if value.is_null() {
1450 Ok(())
1451 } else {
1452 Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1453 }
1454 }
1455
1456 pub async fn get_extended_agent_card(&self) -> Result<A2aAgentCard, A2aClientError> {
1458 if !self.card.capabilities().supports_extended_agent_card() {
1459 return Err(A2aClientError::before(A2aClientErrorKind::Capability));
1460 }
1461 if !self.requires_credentials() {
1462 return Err(A2aClientError::before(A2aClientErrorKind::Authorization));
1463 }
1464 let wire = wire::GetExtendedAgentCardRequest {
1465 tenant: self.tenant(),
1466 };
1467 let params = encode_value(&wire)?;
1468 let value = self
1469 .call_unary(
1470 A2aClientOperation::GetExtendedAgentCard,
1471 wire::methods::GET_EXTENDED_AGENT_CARD,
1472 params,
1473 RestRequest::empty(Method::GET, self.rest_url(&["extendedAgentCard"])?),
1474 A2aCallScope::new(None),
1475 )
1476 .await?;
1477 decode_value::<wire::AgentCard>(value).and_then(|value| {
1478 A2aAgentCard::try_from_wire(value)
1479 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
1480 })
1481 }
1482
1483 pub(crate) fn skill_required_scopes(
1484 &self,
1485 skill_id: &str,
1486 ) -> Option<Result<Arc<[Box<str>]>, A2aClientSecurityError>> {
1487 let skill = self
1488 .card
1489 .skills()
1490 .into_iter()
1491 .find(|skill| skill.id() == skill_id)?;
1492 Some(match skill.security_requirements() {
1493 Some(requirements) => select_security_requirements(
1494 Some(requirements),
1495 self.card.wire().security_schemes.as_ref(),
1496 &self.security,
1497 ),
1498 None => Ok(self.required_scopes.clone()),
1499 })
1500 }
1501
1502 fn tenant(&self) -> Option<String> {
1503 self.interface.tenant().map(ToOwned::to_owned)
1504 }
1505
1506 fn require_push_capability(&self) -> Result<(), A2aClientError> {
1507 if self.card.capabilities().supports_push_notifications() {
1508 Ok(())
1509 } else {
1510 Err(A2aClientError::before(A2aClientErrorKind::Capability))
1511 }
1512 }
1513
1514 fn rest_url(&self, suffix: &[&str]) -> Result<Url, A2aClientError> {
1515 let mut url = self.interface_url.clone();
1516 {
1517 let mut segments = url
1518 .path_segments_mut()
1519 .map_err(|()| A2aClientError::before(A2aClientErrorKind::Request))?;
1520 segments.pop_if_empty();
1521 if let Some(tenant) = self.interface.tenant() {
1522 segments.push(tenant);
1523 }
1524 for segment in suffix {
1525 segments.push(segment);
1526 }
1527 }
1528 Ok(url)
1529 }
1530}
1531
1532impl A2aClient {
1533 async fn call_unary(
1534 &self,
1535 operation: A2aClientOperation,
1536 rpc_method: &'static str,
1537 params: Value,
1538 rest: RestRequest,
1539 scope: A2aCallScope,
1540 ) -> Result<Value, A2aClientError> {
1541 let deadline = tokio::time::Instant::now() + self.options.request_timeout;
1542 let (method, url, body, response_kind, allow_empty) = match self.interface.binding() {
1543 A2aBinding::HttpJson => (
1544 rest.method,
1545 rest.url,
1546 rest.body
1547 .map(|value| serialize_request(&value, self.options.transport())),
1548 UnaryResponseKind::HttpJson,
1549 rest.allow_empty,
1550 ),
1551 A2aBinding::JsonRpc => {
1552 let id = allocate_request_id(&self.next_request_id)
1553 .ok_or_else(|| A2aClientError::before(A2aClientErrorKind::Request))?;
1554 let envelope = wire::JsonRpcRequest::new(
1555 wire::JsonRpcId::Number(id),
1556 rpc_method,
1557 Some(params),
1558 );
1559 (
1560 Method::POST,
1561 self.interface_url.clone(),
1562 Some(serialize_request(&envelope, self.options.transport())),
1563 UnaryResponseKind::JsonRpc(id),
1564 rest.allow_empty,
1565 )
1566 }
1567 };
1568 let body = body.transpose()?;
1569 let authorization = self
1570 .resolve_authorization(deadline, operation, &scope)
1571 .await?;
1572 let request = self.request_builder(method, url, false, body, authorization.as_ref())?;
1573 scope.mark_dispatched();
1574 let response = wait_until(deadline, request.send())
1575 .await
1576 .map_err(|()| A2aClientError::after(A2aClientErrorKind::Transport))?
1577 .map_err(|_| A2aClientError::after(A2aClientErrorKind::Transport))?;
1578 self.consume_unary(deadline, response, response_kind, allow_empty)
1579 .await
1580 }
1581
1582 async fn call_stream(
1583 &self,
1584 operation: A2aClientOperation,
1585 rpc_method: &'static str,
1586 params: Value,
1587 rest: RestRequest,
1588 scope: A2aCallScope,
1589 contract: A2aStreamContract,
1590 ) -> Result<A2aClientEventStream, A2aClientError> {
1591 let deadline = tokio::time::Instant::now() + self.options.request_timeout;
1592 let (method, url, body, response_kind) = match self.interface.binding() {
1593 A2aBinding::HttpJson => (
1594 rest.method,
1595 rest.url,
1596 rest.body
1597 .map(|value| serialize_request(&value, self.options.transport())),
1598 StreamResponseKind::HttpJson,
1599 ),
1600 A2aBinding::JsonRpc => {
1601 let id = allocate_request_id(&self.next_request_id)
1602 .ok_or_else(|| A2aClientError::before(A2aClientErrorKind::Request))?;
1603 let envelope = wire::JsonRpcRequest::new(
1604 wire::JsonRpcId::Number(id),
1605 rpc_method,
1606 Some(params),
1607 );
1608 (
1609 Method::POST,
1610 self.interface_url.clone(),
1611 Some(serialize_request(&envelope, self.options.transport())),
1612 StreamResponseKind::JsonRpc(id),
1613 )
1614 }
1615 };
1616 let body = body.transpose()?;
1617 let authorization = self
1618 .resolve_authorization(deadline, operation, &scope)
1619 .await?;
1620 let request = self.request_builder(method, url, true, body, authorization.as_ref())?;
1621 scope.mark_dispatched();
1622 let response = wait_until(deadline, request.send())
1623 .await
1624 .map_err(|()| A2aClientError::after(A2aClientErrorKind::Transport))?
1625 .map_err(|_| A2aClientError::after(A2aClientErrorKind::Transport))?;
1626 let status = response.status();
1627 if !status.is_success() {
1628 return Err(self
1629 .consume_failed_response(deadline, response, response_kind.into())
1630 .await);
1631 }
1632 if !is_event_stream_content_type(response.headers()) {
1633 if matches!(response_kind, StreamResponseKind::JsonRpc(_))
1634 && is_json_content_type(response.headers())
1635 {
1636 let bytes = self.read_response(deadline, response).await?;
1637 let value = BoundedJson::from_slice_with_limits(&bytes, JsonLimits::MAXIMUM)
1638 .map_err(|_| {
1639 A2aClientError::after_http(A2aClientErrorKind::InvalidResponse, status)
1640 })?
1641 .into_value();
1642 return match response_kind {
1643 StreamResponseKind::JsonRpc(id) => {
1644 match parse_rpc_response(&value, id, Some(status)) {
1645 Err(error) => Err(error),
1646 Ok(_) => Err(A2aClientError::after_http(
1647 A2aClientErrorKind::HttpProtocol,
1648 status,
1649 )),
1650 }
1651 }
1652 StreamResponseKind::HttpJson => unreachable!(),
1653 };
1654 }
1655 return Err(A2aClientError::after_http(
1656 A2aClientErrorKind::HttpProtocol,
1657 status,
1658 ));
1659 }
1660 let state = A2aStreamState {
1661 body: Box::pin(response.bytes_stream()),
1662 decoder: Some(SseDecoder::new(self.options.transport())),
1663 pending: VecDeque::new(),
1664 kind: response_kind,
1665 idle_timeout: self.options.stream_idle_timeout,
1666 maximum_events: self.options.maximum_stream_events,
1667 events_seen: 0,
1668 terminated: false,
1669 validator: A2aStreamValidator::new(contract),
1670 };
1671 Ok(Box::pin(stream::unfold(state, next_a2a_stream_item)))
1672 }
1673
1674 async fn resolve_authorization(
1675 &self,
1676 deadline: tokio::time::Instant,
1677 operation: A2aClientOperation,
1678 scope: &A2aCallScope,
1679 ) -> Result<Option<ApiKey>, A2aClientError> {
1680 let A2aClientSecurity::Bearer { provider, .. } = &self.security else {
1681 return Ok(None);
1682 };
1683 let request = A2aClientAuthorizationRequest {
1684 operation,
1685 card_digest: self.card_digest,
1686 binding: self.interface.binding(),
1687 remote_tenant: self.interface.tenant().map(Into::into),
1688 task_id: scope.task_id.clone(),
1689 required_scopes: scope
1690 .required_scopes
1691 .clone()
1692 .unwrap_or_else(|| self.required_scopes.clone()),
1693 attempt: scope.attempt.clone(),
1694 };
1695 wait_until(deadline, provider.resolve(&request))
1696 .await
1697 .map_err(|()| A2aClientError::authorization(A2aClientAuthorizationError::Unavailable))?
1698 .map(Some)
1699 .map_err(A2aClientError::authorization)
1700 }
1701
1702 fn request_builder(
1703 &self,
1704 method: Method,
1705 url: Url,
1706 streaming: bool,
1707 body: Option<Vec<u8>>,
1708 authorization: Option<&ApiKey>,
1709 ) -> Result<reqwest::RequestBuilder, A2aClientError> {
1710 let carries_json = body.is_some() || method == Method::POST;
1711 let mut request = self
1712 .http
1713 .request(method, url)
1714 .header(A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION_1_0)
1715 .header(
1716 header::ACCEPT,
1717 if streaming {
1718 EVENT_STREAM
1719 } else {
1720 A2A_JSON_ACCEPT
1721 },
1722 );
1723 if !self.extensions.is_empty() {
1724 let extensions = self
1725 .extensions
1726 .iter()
1727 .map(AsRef::as_ref)
1728 .collect::<Vec<_>>()
1729 .join(",");
1730 let value = HeaderValue::from_str(&extensions)
1731 .map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))?;
1732 request = request.header(A2A_EXTENSIONS_HEADER, value);
1733 }
1734 if let Some(key) = authorization {
1735 request = request.bearer_auth(key.expose_secret());
1736 }
1737 if carries_json {
1738 request = request.header(
1739 header::CONTENT_TYPE,
1740 match self.interface.binding() {
1741 A2aBinding::HttpJson => A2A_JSON,
1742 A2aBinding::JsonRpc => JSON,
1743 },
1744 );
1745 }
1746 if let Some(body) = body {
1747 request = request.body(body);
1748 }
1749 Ok(request)
1750 }
1751
1752 async fn consume_unary(
1753 &self,
1754 deadline: tokio::time::Instant,
1755 response: reqwest::Response,
1756 kind: UnaryResponseKind,
1757 allow_empty: bool,
1758 ) -> Result<Value, A2aClientError> {
1759 let status = response.status();
1760 if status == StatusCode::NO_CONTENT
1761 && allow_empty
1762 && matches!(kind, UnaryResponseKind::HttpJson)
1763 {
1764 return Ok(Value::Null);
1765 }
1766 if !is_json_content_type(response.headers()) {
1767 if status.is_success() && allow_empty && matches!(kind, UnaryResponseKind::HttpJson) {
1768 let bytes = self.read_response(deadline, response).await?;
1769 return if bytes.is_empty() {
1770 Ok(Value::Null)
1771 } else {
1772 Err(A2aClientError::after_http(
1773 A2aClientErrorKind::HttpProtocol,
1774 status,
1775 ))
1776 };
1777 }
1778 return Err(A2aClientError::after_http(
1779 A2aClientErrorKind::HttpProtocol,
1780 status,
1781 ));
1782 }
1783 let bytes = self.read_response(deadline, response).await?;
1784 let value = BoundedJson::from_slice_with_limits(&bytes, JsonLimits::MAXIMUM)
1785 .map_err(|_| A2aClientError::after_http(A2aClientErrorKind::InvalidResponse, status))?
1786 .into_value();
1787 match kind {
1788 UnaryResponseKind::HttpJson if status.is_success() => {
1789 if allow_empty
1790 && (value.is_null() || value.as_object().is_some_and(serde_json::Map::is_empty))
1791 {
1792 Ok(Value::Null)
1793 } else {
1794 Ok(value)
1795 }
1796 }
1797 UnaryResponseKind::HttpJson => match parse_rest_error(&value, Some(status)) {
1798 Some(error) => Err(A2aClientError::remote(error.code, Some(status))),
1799 None => Err(A2aClientError::after_http(
1800 A2aClientErrorKind::HttpProtocol,
1801 status,
1802 )),
1803 },
1804 UnaryResponseKind::JsonRpc(id) => {
1805 let result = parse_rpc_response(&value, id, Some(status))?;
1806 if !status.is_success() {
1807 return Err(A2aClientError::after_http(
1808 A2aClientErrorKind::HttpProtocol,
1809 status,
1810 ));
1811 }
1812 if allow_empty
1813 && (result.is_null()
1814 || result.as_object().is_some_and(serde_json::Map::is_empty))
1815 {
1816 Ok(Value::Null)
1817 } else {
1818 Ok(result)
1819 }
1820 }
1821 }
1822 }
1823
1824 async fn consume_failed_response(
1825 &self,
1826 deadline: tokio::time::Instant,
1827 response: reqwest::Response,
1828 kind: UnaryResponseKind,
1829 ) -> A2aClientError {
1830 let status = response.status();
1831 if !is_json_content_type(response.headers()) {
1832 return A2aClientError::after_http(A2aClientErrorKind::HttpProtocol, status);
1833 }
1834 let bytes = match self.read_response(deadline, response).await {
1835 Ok(bytes) => bytes,
1836 Err(error) => return error,
1837 };
1838 let Ok(value) = BoundedJson::from_slice_with_limits(&bytes, JsonLimits::MAXIMUM) else {
1839 return A2aClientError::after_http(A2aClientErrorKind::InvalidResponse, status);
1840 };
1841 let value = value.into_value();
1842 match kind {
1843 UnaryResponseKind::HttpJson => parse_rest_error(&value, Some(status)).map_or_else(
1844 || A2aClientError::after_http(A2aClientErrorKind::HttpProtocol, status),
1845 |error| A2aClientError::remote(error.code, Some(status)),
1846 ),
1847 UnaryResponseKind::JsonRpc(id) => match parse_rpc_response(&value, id, Some(status)) {
1848 Err(error) if error.kind() == A2aClientErrorKind::Remote => error,
1849 Ok(_) | Err(_) => {
1850 A2aClientError::after_http(A2aClientErrorKind::HttpProtocol, status)
1851 }
1852 },
1853 }
1854 }
1855
1856 async fn read_response(
1857 &self,
1858 deadline: tokio::time::Instant,
1859 response: reqwest::Response,
1860 ) -> Result<Vec<u8>, A2aClientError> {
1861 wait_until(
1862 deadline,
1863 bounded_body(response, self.options.transport().maximum_response_bytes()),
1864 )
1865 .await
1866 .map_err(|()| A2aClientError::after(A2aClientErrorKind::Transport))?
1867 .map_err(|error| match error {
1868 BoundedBodyError::Transport => A2aClientError::after(A2aClientErrorKind::Transport),
1869 BoundedBodyError::TooLarge => {
1870 A2aClientError::after(A2aClientErrorKind::InvalidResponse)
1871 }
1872 })
1873 }
1874}
1875
1876struct RestRequest {
1877 method: Method,
1878 url: Url,
1879 body: Option<Value>,
1880 allow_empty: bool,
1881}
1882
1883impl RestRequest {
1884 fn empty(method: Method, url: Url) -> Self {
1885 Self {
1886 method,
1887 url,
1888 body: None,
1889 allow_empty: false,
1890 }
1891 }
1892
1893 fn empty_response(method: Method, url: Url) -> Self {
1894 Self {
1895 method,
1896 url,
1897 body: None,
1898 allow_empty: true,
1899 }
1900 }
1901
1902 fn json(method: Method, url: Url, body: Value) -> Self {
1903 Self {
1904 method,
1905 url,
1906 body: Some(body),
1907 allow_empty: false,
1908 }
1909 }
1910}
1911
1912#[derive(Clone, Copy)]
1913enum UnaryResponseKind {
1914 HttpJson,
1915 JsonRpc(i64),
1916}
1917
1918#[derive(Clone, Copy)]
1919enum StreamResponseKind {
1920 HttpJson,
1921 JsonRpc(i64),
1922}
1923
1924impl From<StreamResponseKind> for UnaryResponseKind {
1925 fn from(value: StreamResponseKind) -> Self {
1926 match value {
1927 StreamResponseKind::HttpJson => Self::HttpJson,
1928 StreamResponseKind::JsonRpc(id) => Self::JsonRpc(id),
1929 }
1930 }
1931}
1932
1933enum A2aStreamContract {
1934 SendMessage(A2aSendExpectation),
1935 SubscribeToTask(Box<str>),
1936}
1937
1938#[derive(Clone)]
1939struct A2aStreamArtifacts {
1940 ids: HashSet<Box<str>>,
1941 sealed_ids: HashSet<Box<str>>,
1942}
1943
1944impl A2aStreamArtifacts {
1945 fn from_task(task: &A2aTask) -> Self {
1946 Self {
1947 ids: task.artifact_ids().map(Into::into).collect(),
1948 sealed_ids: HashSet::new(),
1949 }
1950 }
1951}
1952
1953enum A2aStreamProgress {
1954 AwaitingFirst,
1955 MessageComplete,
1956 Task {
1957 task_id: Box<str>,
1958 context_id: Box<str>,
1959 completion_seen: bool,
1960 artifacts: A2aStreamArtifacts,
1961 },
1962}
1963
1964struct A2aStreamValidator {
1965 contract: A2aStreamContract,
1966 progress: A2aStreamProgress,
1967}
1968
1969impl A2aStreamValidator {
1970 const fn new(contract: A2aStreamContract) -> Self {
1971 Self {
1972 contract,
1973 progress: A2aStreamProgress::AwaitingFirst,
1974 }
1975 }
1976
1977 fn observe(&mut self, event: &A2aStreamEvent) -> Result<(), A2aClientError> {
1978 let progress = match (&self.progress, event) {
1979 (A2aStreamProgress::AwaitingFirst, A2aStreamEvent::Message(message)) => {
1980 let A2aStreamContract::SendMessage(expectation) = &self.contract else {
1981 return Err(invalid_response());
1982 };
1983 validate_agent_message(message, expectation)?;
1984 A2aStreamProgress::MessageComplete
1985 }
1986 (A2aStreamProgress::AwaitingFirst, A2aStreamEvent::Task(task)) => {
1987 let (task_id, context_id, history_length) = match &self.contract {
1988 A2aStreamContract::SendMessage(expectation) => (
1989 expectation.task_id.as_deref(),
1990 expectation.context_id.as_deref(),
1991 expectation.history_length,
1992 ),
1993 A2aStreamContract::SubscribeToTask(task_id) => {
1994 (Some(task_id.as_ref()), None, None)
1995 }
1996 };
1997 validate_task_response(task, task_id, context_id, history_length)?;
1998 A2aStreamProgress::Task {
1999 task_id: task.id().into(),
2000 context_id: task.context_id().into(),
2001 completion_seen: stream_state_closes(task.state()),
2002 artifacts: A2aStreamArtifacts::from_task(task),
2003 }
2004 }
2005 (
2006 A2aStreamProgress::Task {
2007 task_id,
2008 context_id,
2009 completion_seen: false,
2010 artifacts,
2011 },
2012 A2aStreamEvent::StatusUpdate(update),
2013 ) => {
2014 validate_status_update(update, task_id, context_id)?;
2015 A2aStreamProgress::Task {
2016 task_id: task_id.clone(),
2017 context_id: context_id.clone(),
2018 completion_seen: stream_state_closes(update.status().state()),
2019 artifacts: artifacts.clone(),
2020 }
2021 }
2022 (
2023 A2aStreamProgress::Task {
2024 task_id,
2025 context_id,
2026 completion_seen: false,
2027 artifacts,
2028 },
2029 A2aStreamEvent::ArtifactUpdate(update),
2030 ) => {
2031 let artifacts = validate_artifact_update(update, task_id, context_id, artifacts)?;
2032 A2aStreamProgress::Task {
2033 task_id: task_id.clone(),
2034 context_id: context_id.clone(),
2035 completion_seen: false,
2036 artifacts,
2037 }
2038 }
2039 _ => return Err(invalid_response()),
2040 };
2041 self.progress = progress;
2042 Ok(())
2043 }
2044
2045 const fn can_end(&self) -> bool {
2046 matches!(
2047 self.progress,
2048 A2aStreamProgress::MessageComplete
2049 | A2aStreamProgress::Task {
2050 completion_seen: true,
2051 ..
2052 }
2053 )
2054 }
2055}
2056
2057const fn stream_state_closes(state: A2aTaskState) -> bool {
2058 state.is_terminal()
2059 || matches!(
2060 state,
2061 A2aTaskState::InputRequired | A2aTaskState::AuthRequired
2062 )
2063}
2064
2065struct A2aStreamState {
2066 body: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send + 'static>>,
2067 decoder: Option<SseDecoder>,
2068 pending: VecDeque<SseEvent>,
2069 kind: StreamResponseKind,
2070 idle_timeout: Duration,
2071 maximum_events: u32,
2072 events_seen: u32,
2073 terminated: bool,
2074 validator: A2aStreamValidator,
2075}
2076
2077async fn next_a2a_stream_item(
2078 mut state: A2aStreamState,
2079) -> Option<(Result<A2aStreamEvent, A2aClientError>, A2aStreamState)> {
2080 loop {
2081 if state.terminated {
2082 return None;
2083 }
2084 if let Some(event) = state.pending.pop_front() {
2085 state.events_seen = match state.events_seen.checked_add(1) {
2086 Some(value) if value <= state.maximum_events => value,
2087 Some(_) | None => {
2088 state.terminated = true;
2089 return Some((
2090 Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse)),
2091 state,
2092 ));
2093 }
2094 };
2095 let parsed = parse_sse_event(&event, state.kind).and_then(|event| {
2096 state.validator.observe(&event)?;
2097 Ok(event)
2098 });
2099 if parsed.is_err() {
2100 state.terminated = true;
2101 }
2102 return Some((parsed, state));
2103 }
2104
2105 if state.decoder.is_none() {
2106 state.terminated = true;
2107 return if state.validator.can_end() {
2108 None
2109 } else {
2110 Some((Err(invalid_response()), state))
2111 };
2112 }
2113 match tokio::time::timeout(state.idle_timeout, state.body.next()).await {
2114 Err(_) | Ok(Some(Err(_))) => {
2115 state.terminated = true;
2116 return Some((
2117 Err(A2aClientError::after(A2aClientErrorKind::Transport)),
2118 state,
2119 ));
2120 }
2121 Ok(Some(Ok(chunk))) => {
2122 if let Ok(events) = state
2123 .decoder
2124 .as_mut()
2125 .expect("decoder presence was checked")
2126 .push(&chunk)
2127 {
2128 state.pending.extend(events);
2129 } else {
2130 state.terminated = true;
2131 return Some((
2132 Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse)),
2133 state,
2134 ));
2135 }
2136 }
2137 Ok(None) => {
2138 let decoder = state.decoder.take().expect("decoder was present");
2139 if let Ok(events) = decoder.finish() {
2140 state.pending.extend(events);
2141 } else {
2142 state.terminated = true;
2143 return Some((
2144 Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse)),
2145 state,
2146 ));
2147 }
2148 }
2149 }
2150 }
2151}
2152
2153fn parse_sse_event(
2154 event: &SseEvent,
2155 kind: StreamResponseKind,
2156) -> Result<A2aStreamEvent, A2aClientError> {
2157 if event
2158 .event
2159 .as_deref()
2160 .is_some_and(|event| !matches!(event, "message" | "error"))
2161 {
2162 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2163 }
2164 let value = BoundedJson::from_str_with_limits(&event.data, JsonLimits::MAXIMUM)
2165 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))?
2166 .into_value();
2167 match kind {
2168 StreamResponseKind::JsonRpc(id) => {
2169 let value = match parse_rpc_response(&value, id, None) {
2170 Ok(_) if event.event.as_deref() == Some("error") => {
2171 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2172 }
2173 Ok(value) => value,
2174 Err(error) => return Err(error),
2175 };
2176 require_exact_variant(
2177 &value,
2178 &["task", "message", "statusUpdate", "artifactUpdate"],
2179 )?;
2180 let wire = decode_value::<wire::StreamResponse>(value)?;
2181 A2aStreamEvent::try_from_wire(wire)
2182 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
2183 }
2184 StreamResponseKind::HttpJson => {
2185 if event.event.as_deref() == Some("error") {
2186 if let Some(error) =
2187 parse_rest_error(&value, None).or_else(|| parse_bare_rpc_error(&value))
2188 {
2189 return Err(A2aClientError::remote(error.code, None));
2190 }
2191 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2192 }
2193 require_exact_variant(
2194 &value,
2195 &["task", "message", "statusUpdate", "artifactUpdate"],
2196 )?;
2197 match serde_json::from_value::<wire::StreamResponse>(value.clone()) {
2198 Ok(wire) => A2aStreamEvent::try_from_wire(wire)
2199 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse)),
2200 Err(_) => {
2201 if let Some(error) =
2202 parse_rest_error(&value, None).or_else(|| parse_bare_rpc_error(&value))
2203 {
2204 Err(A2aClientError::remote(error.code, None))
2205 } else {
2206 Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse))
2207 }
2208 }
2209 }
2210 }
2211 }
2212}
2213
2214fn validate_interface_pins(
2215 interface_pins: &[A2aClientInterfacePin],
2216) -> Result<(), A2aClientBuildError> {
2217 const MAX_INTERFACE_PINS: usize = 16;
2218 if interface_pins.is_empty() {
2219 return Err(A2aClientBuildError::MissingInterfacePin);
2220 }
2221 if interface_pins.len() > MAX_INTERFACE_PINS {
2222 return Err(A2aClientBuildError::TooManyInterfacePins);
2223 }
2224 let mut unique = HashSet::with_capacity(interface_pins.len());
2225 for pin in interface_pins {
2226 if !unique.insert((pin.binding, pin.url.as_str(), pin.tenant.as_deref())) {
2227 return Err(A2aClientBuildError::DuplicateInterfacePin);
2228 }
2229 }
2230 Ok(())
2231}
2232
2233fn validate_extension_selection(extensions: &[String]) -> Result<(), A2aClientBuildError> {
2234 if extensions.len() > MAX_EXTENSION_COUNT {
2235 return Err(A2aClientBuildError::InvalidExtensions);
2236 }
2237 let mut unique = HashSet::with_capacity(extensions.len());
2238 let mut total = extensions.len().saturating_sub(1);
2239 for extension in extensions {
2240 if extension.is_empty()
2241 || extension.trim() != extension
2242 || extension.contains(',')
2243 || extension.chars().any(char::is_control)
2244 || extension.len() > 4096
2245 || Url::parse(extension)
2246 .ok()
2247 .and_then(|url| url.host_str().map(ToOwned::to_owned))
2248 .is_none()
2249 || !unique.insert(extension.as_str())
2250 {
2251 return Err(A2aClientBuildError::InvalidExtensions);
2252 }
2253 total = total
2254 .checked_add(extension.len())
2255 .ok_or(A2aClientBuildError::InvalidExtensions)?;
2256 }
2257 if total > MAX_EXTENSION_HEADER_BYTES || HeaderValue::from_str(&extensions.join(",")).is_err() {
2258 return Err(A2aClientBuildError::InvalidExtensions);
2259 }
2260 Ok(())
2261}
2262
2263fn select_security_requirements(
2264 requirements: Option<&[wire::SecurityRequirement]>,
2265 schemes: Option<&std::collections::HashMap<String, wire::SecurityScheme>>,
2266 selection: &A2aClientSecurity,
2267) -> Result<Arc<[Box<str>]>, A2aClientSecurityError> {
2268 match selection {
2269 A2aClientSecurity::Anonymous => {
2270 let allowed = requirements.is_none_or(|requirements| {
2271 requirements.is_empty()
2272 || requirements.iter().any(std::collections::HashMap::is_empty)
2273 });
2274 if allowed {
2275 Ok(Arc::<[Box<str>]>::from([]))
2276 } else {
2277 Err(A2aClientSecurityError::AnonymousNotAllowed)
2278 }
2279 }
2280 A2aClientSecurity::Bearer { scheme, .. } => {
2281 let compatible = schemes
2282 .and_then(|schemes| schemes.get(scheme.as_ref()))
2283 .is_some_and(|scheme| match scheme {
2284 wire::SecurityScheme::HttpAuth(value) => {
2285 value.scheme.eq_ignore_ascii_case("bearer")
2286 }
2287 wire::SecurityScheme::OAuth2(_) | wire::SecurityScheme::OpenIdConnect(_) => {
2288 true
2289 }
2290 wire::SecurityScheme::ApiKey(_) | wire::SecurityScheme::MutualTls(_) => false,
2291 });
2292 if !compatible || !selection.requires_credentials() {
2293 return Err(A2aClientSecurityError::BearerSchemeUnsupported);
2294 }
2295 let scopes = requirements
2296 .unwrap_or_default()
2297 .iter()
2298 .find(|requirement| {
2299 requirement.len() == 1 && requirement.contains_key(scheme.as_ref())
2300 })
2301 .and_then(|requirement| requirement.get(scheme.as_ref()))
2302 .ok_or(A2aClientSecurityError::RequirementNotSatisfied)?;
2303 let mut scopes = scopes
2304 .iter()
2305 .cloned()
2306 .map(String::into_boxed_str)
2307 .collect::<Vec<_>>();
2308 scopes.sort_unstable();
2309 scopes.dedup();
2310 Ok(scopes.into())
2311 }
2312 }
2313}
2314
2315const fn invalid_response() -> A2aClientError {
2316 A2aClientError::after(A2aClientErrorKind::InvalidResponse)
2317}
2318
2319fn validate_send_response(
2320 response: &A2aSendMessageResponse,
2321 expectation: &A2aSendExpectation,
2322) -> Result<(), A2aClientError> {
2323 match response {
2324 A2aSendMessageResponse::Task(task) => {
2325 if !expectation.return_immediately && !stream_state_closes(task.state()) {
2326 return Err(invalid_response());
2327 }
2328 validate_task_response(
2329 task,
2330 expectation.task_id.as_deref(),
2331 expectation.context_id.as_deref(),
2332 expectation.history_length,
2333 )
2334 }
2335 A2aSendMessageResponse::Message(message) => validate_agent_message(message, expectation),
2336 }
2337}
2338
2339fn validate_agent_message(
2340 message: &A2aMessage,
2341 expectation: &A2aSendExpectation,
2342) -> Result<(), A2aClientError> {
2343 if message.role() != A2aMessageRole::Agent || message.context_id().is_none() {
2344 return Err(invalid_response());
2345 }
2346 if expectation
2347 .context_id
2348 .as_deref()
2349 .is_some_and(|expected| message.context_id() != Some(expected))
2350 {
2351 return Err(invalid_response());
2352 }
2353 match (expectation.task_id.as_deref(), message.task_id()) {
2354 (Some(expected), Some(observed)) if expected == observed => {}
2355 (None, None) => {}
2356 _ => return Err(invalid_response()),
2357 }
2358 Ok(())
2359}
2360
2361fn validate_task_response(
2362 task: &A2aTask,
2363 expected_task_id: Option<&str>,
2364 expected_context_id: Option<&str>,
2365 history_length: Option<u32>,
2366) -> Result<(), A2aClientError> {
2367 if expected_task_id.is_some_and(|expected| task.id() != expected)
2368 || expected_context_id.is_some_and(|expected| task.context_id() != expected)
2369 || history_length.is_some_and(|maximum| task.history_len() > maximum as usize)
2370 {
2371 return Err(invalid_response());
2372 }
2373 let task_expectation = A2aSendExpectation {
2374 task_id: Some(task.id().into()),
2375 context_id: Some(task.context_id().into()),
2376 history_length: None,
2377 return_immediately: false,
2378 };
2379 if let Some(message) = task.status().message() {
2380 validate_agent_message(&message, &task_expectation)?;
2381 }
2382 for message in task.history() {
2383 if message
2384 .context_id()
2385 .is_some_and(|context_id| context_id != task.context_id())
2386 || message
2387 .task_id()
2388 .is_some_and(|task_id| task_id != task.id())
2389 {
2390 return Err(invalid_response());
2391 }
2392 if message.role() == A2aMessageRole::Agent {
2393 validate_agent_message(&message, &task_expectation)?;
2394 }
2395 }
2396 Ok(())
2397}
2398
2399fn validate_status_update(
2400 update: &crate::A2aStatusUpdate,
2401 task_id: &str,
2402 context_id: &str,
2403) -> Result<(), A2aClientError> {
2404 if update.task_id() != task_id || update.context_id() != context_id {
2405 return Err(invalid_response());
2406 }
2407 if let Some(message) = update.status().message() {
2408 validate_agent_message(
2409 &message,
2410 &A2aSendExpectation {
2411 task_id: Some(task_id.into()),
2412 context_id: Some(context_id.into()),
2413 history_length: None,
2414 return_immediately: false,
2415 },
2416 )?;
2417 }
2418 Ok(())
2419}
2420
2421fn validate_artifact_update(
2422 update: &crate::A2aArtifactUpdate,
2423 task_id: &str,
2424 context_id: &str,
2425 current: &A2aStreamArtifacts,
2426) -> Result<A2aStreamArtifacts, A2aClientError> {
2427 if update.task_id() != task_id || update.context_id() != context_id {
2428 return Err(invalid_response());
2429 }
2430 let artifact_id = update.artifact().artifact_id();
2431 if update.append()
2432 && (!current.ids.contains(artifact_id) || current.sealed_ids.contains(artifact_id))
2433 {
2434 return Err(invalid_response());
2435 }
2436
2437 let mut next = current.clone();
2438 if !update.append() {
2439 next.ids.insert(artifact_id.into());
2440 next.sealed_ids.remove(artifact_id);
2441 }
2442 if update.last_chunk() {
2443 next.sealed_ids.insert(artifact_id.into());
2444 }
2445 Ok(next)
2446}
2447
2448fn validate_task_page(
2449 page: &A2aTaskPage,
2450 expectation: &A2aListTasksExpectation,
2451) -> Result<(), A2aClientError> {
2452 if page.page_size() > expectation.page_size
2453 || page.tasks().len() > usize::from(expectation.page_size)
2454 {
2455 return Err(invalid_response());
2456 }
2457 for task in page.tasks() {
2458 let timestamp = task.status().timestamp();
2459 if expectation
2460 .context_id
2461 .as_deref()
2462 .is_some_and(|context_id| task.context_id() != context_id)
2463 || expectation
2464 .status
2465 .is_some_and(|status| task.state() != status)
2466 || expectation
2467 .status_timestamp_after
2468 .is_some_and(|after| timestamp.is_none_or(|value| value < after))
2469 || (!expectation.include_artifacts && task.has_artifact_projection())
2470 {
2471 return Err(invalid_response());
2472 }
2473 validate_task_response(task, None, None, expectation.history_length)?;
2474 }
2475 Ok(())
2476}
2477
2478fn validate_push_config_identity(
2479 config: &A2aPushConfig,
2480 task_id: &str,
2481 config_id: Option<&str>,
2482 require_id: bool,
2483) -> Result<(), A2aClientError> {
2484 if config.task_id() != Some(task_id)
2485 || config_id.is_some_and(|expected| config.id() != Some(expected))
2486 || (require_id && config.id().is_none())
2487 {
2488 return Err(invalid_response());
2489 }
2490 Ok(())
2491}
2492
2493fn validate_push_config_page(
2494 page: &A2aPushConfigPage,
2495 task_id: &str,
2496 page_size: u16,
2497) -> Result<(), A2aClientError> {
2498 if page.configs().len() > usize::from(page_size) {
2499 return Err(invalid_response());
2500 }
2501 let mut ids = HashSet::with_capacity(page.configs().len());
2502 for config in page.configs() {
2503 validate_push_config_identity(config, task_id, None, true)?;
2504 if !ids.insert(config.id().expect("configuration ID presence was checked")) {
2505 return Err(invalid_response());
2506 }
2507 }
2508 Ok(())
2509}
2510
2511fn serialize_request<T: Serialize>(
2512 value: &T,
2513 options: ProviderHttpOptions,
2514) -> Result<Vec<u8>, A2aClientError> {
2515 let bytes = serde_json::to_vec(value)
2516 .map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))?;
2517 if bytes.len() > options.maximum_request_bytes() {
2518 return Err(A2aClientError::before(A2aClientErrorKind::Request));
2519 }
2520 Ok(bytes)
2521}
2522
2523fn encode_value<T: Serialize>(value: &T) -> Result<Value, A2aClientError> {
2524 serde_json::to_value(value).map_err(|_| A2aClientError::before(A2aClientErrorKind::Request))
2525}
2526
2527fn decode_value<T: DeserializeOwned>(value: Value) -> Result<T, A2aClientError> {
2528 serde_json::from_value(value)
2529 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
2530}
2531
2532fn require_exact_variant(value: &Value, variants: &[&str]) -> Result<(), A2aClientError> {
2533 let object = value
2534 .as_object()
2535 .ok_or_else(|| A2aClientError::after(A2aClientErrorKind::InvalidResponse))?;
2536 if object.len() != 1 || !variants.iter().any(|variant| object.contains_key(*variant)) {
2537 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2538 }
2539 Ok(())
2540}
2541
2542fn parse_rpc_response(
2543 value: &Value,
2544 expected_id: i64,
2545 status: Option<StatusCode>,
2546) -> Result<Value, A2aClientError> {
2547 let object = value
2548 .as_object()
2549 .ok_or_else(|| A2aClientError::after(A2aClientErrorKind::InvalidResponse))?;
2550 let version = object.get("jsonrpc").and_then(Value::as_str);
2551 let id = object
2552 .get("id")
2553 .cloned()
2554 .and_then(|value| serde_json::from_value::<wire::JsonRpcId>(value).ok());
2555 let has_result = object.contains_key("result");
2556 let has_error = object.contains_key("error");
2557 if version != Some("2.0")
2558 || id != Some(wire::JsonRpcId::Number(expected_id))
2559 || has_result == has_error
2560 {
2561 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2562 }
2563 if let Some(error) = object.get("error") {
2564 let error = serde_json::from_value::<wire::JsonRpcError>(error.clone())
2565 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))?;
2566 if error.message.is_empty() || error.message.len() > MAX_REMOTE_ERROR_MESSAGE_BYTES {
2567 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2568 }
2569 let authoritative_code = status
2570 .is_none_or(|status| status.is_success())
2571 .then_some(error.code);
2572 return Err(A2aClientError::remote(authoritative_code, status));
2573 }
2574 Ok(object
2575 .get("result")
2576 .expect("result presence was checked")
2577 .clone())
2578}
2579
2580#[derive(Clone, Copy)]
2581struct ParsedRemoteError {
2582 code: Option<i32>,
2583}
2584
2585fn parse_rest_error(
2586 value: &Value,
2587 expected_http_status: Option<StatusCode>,
2588) -> Option<ParsedRemoteError> {
2589 let error = value.get("error")?.as_object()?;
2590 let code = error.get("code")?.as_u64()?;
2591 let code = u16::try_from(code).ok()?;
2592 if expected_http_status.is_some_and(|expected| expected.as_u16() != code) {
2593 return None;
2594 }
2595 let status = error.get("status")?.as_str()?;
2596 if status.is_empty() || status.len() > 256 {
2597 return None;
2598 }
2599 let message = error.get("message")?.as_str()?;
2600 if message.is_empty() || message.len() > MAX_REMOTE_ERROR_MESSAGE_BYTES {
2601 return None;
2602 }
2603 let details = error.get("details")?.as_array()?;
2604 let mut remote_codes = details.iter().filter_map(|detail| {
2605 let detail = detail.as_object()?;
2606 if detail.get("@type")?.as_str()? != "type.googleapis.com/google.rpc.ErrorInfo" {
2607 return None;
2608 }
2609 if detail.get("domain")?.as_str()? != "a2a-protocol.org" {
2610 return None;
2611 }
2612 wire::reason_to_error_code(detail.get("reason")?.as_str()?)
2613 });
2614 let remote_code = match (remote_codes.next(), remote_codes.next()) {
2615 (Some(remote_code), None)
2616 if rest_error_identity(remote_code).is_some_and(
2617 |(expected_code, expected_status)| {
2618 code == expected_code && status == expected_status
2619 },
2620 ) =>
2621 {
2622 Some(remote_code)
2623 }
2624 _ => None,
2625 };
2626 Some(ParsedRemoteError { code: remote_code })
2627}
2628
2629fn rest_error_identity(code: i32) -> Option<(u16, &'static str)> {
2630 match code {
2631 wire::error_code::TASK_NOT_FOUND | wire::error_code::METHOD_NOT_FOUND => {
2632 Some((StatusCode::NOT_FOUND.as_u16(), "NOT_FOUND"))
2633 }
2634 wire::error_code::TASK_NOT_CANCELABLE => {
2635 Some((StatusCode::CONFLICT.as_u16(), "FAILED_PRECONDITION"))
2636 }
2637 wire::error_code::PUSH_NOTIFICATION_NOT_SUPPORTED
2638 | wire::error_code::UNSUPPORTED_OPERATION
2639 | wire::error_code::VERSION_NOT_SUPPORTED => {
2640 Some((StatusCode::BAD_REQUEST.as_u16(), "UNIMPLEMENTED"))
2641 }
2642 wire::error_code::CONTENT_TYPE_NOT_SUPPORTED => Some((
2643 StatusCode::UNSUPPORTED_MEDIA_TYPE.as_u16(),
2644 "INVALID_ARGUMENT",
2645 )),
2646 wire::error_code::INVALID_AGENT_RESPONSE => {
2647 Some((StatusCode::BAD_GATEWAY.as_u16(), "INTERNAL"))
2648 }
2649 wire::error_code::EXTENDED_CARD_NOT_CONFIGURED
2650 | wire::error_code::EXTENSION_SUPPORT_REQUIRED => {
2651 Some((StatusCode::BAD_REQUEST.as_u16(), "FAILED_PRECONDITION"))
2652 }
2653 wire::error_code::INVALID_REQUEST
2654 | wire::error_code::INVALID_PARAMS
2655 | wire::error_code::PARSE_ERROR => {
2656 Some((StatusCode::BAD_REQUEST.as_u16(), "INVALID_ARGUMENT"))
2657 }
2658 wire::error_code::INTERNAL_ERROR => {
2659 Some((StatusCode::INTERNAL_SERVER_ERROR.as_u16(), "INTERNAL"))
2660 }
2661 _ => None,
2662 }
2663}
2664
2665fn parse_bare_rpc_error(value: &Value) -> Option<ParsedRemoteError> {
2666 let error = serde_json::from_value::<wire::JsonRpcError>(value.clone()).ok()?;
2667 if error.message.is_empty() || error.message.len() > MAX_REMOTE_ERROR_MESSAGE_BYTES {
2668 return None;
2669 }
2670 Some(ParsedRemoteError {
2671 code: Some(error.code),
2672 })
2673}
2674
2675fn decode_push_config(
2676 mut value: wire::TaskPushNotificationConfig,
2677 expected_tenant: Option<&str>,
2678) -> Result<A2aPushConfig, A2aClientError> {
2679 strip_response_tenant(&mut value, expected_tenant)?;
2680 A2aPushConfig::try_from_wire(value)
2681 .map_err(|_| A2aClientError::after(A2aClientErrorKind::InvalidResponse))
2682}
2683
2684fn strip_response_tenant(
2685 value: &mut wire::TaskPushNotificationConfig,
2686 expected_tenant: Option<&str>,
2687) -> Result<(), A2aClientError> {
2688 if value
2689 .tenant
2690 .as_deref()
2691 .is_some_and(|tenant| Some(tenant) != expected_tenant)
2692 {
2693 return Err(A2aClientError::after(A2aClientErrorKind::InvalidResponse));
2694 }
2695 value.tenant = None;
2696 Ok(())
2697}
2698
2699fn allocate_request_id(counter: &AtomicU64) -> Option<i64> {
2700 counter
2701 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
2702 (value < i64::MAX as u64).then_some(value + 1)
2703 })
2704 .ok()
2705 .and_then(|value| i64::try_from(value).ok())
2706}
2707
2708async fn wait_until<T, F>(deadline: tokio::time::Instant, future: F) -> Result<T, ()>
2709where
2710 F: std::future::Future<Output = T>,
2711{
2712 tokio::time::timeout_at(deadline, future)
2713 .await
2714 .map_err(|_| ())
2715}
2716
2717#[derive(Clone, Copy)]
2718enum BoundedBodyError {
2719 Transport,
2720 TooLarge,
2721}
2722
2723async fn bounded_body(
2724 response: reqwest::Response,
2725 maximum: usize,
2726) -> Result<Vec<u8>, BoundedBodyError> {
2727 if response
2728 .content_length()
2729 .is_some_and(|length| length > maximum as u64)
2730 {
2731 return Err(BoundedBodyError::TooLarge);
2732 }
2733 let mut output = Vec::new();
2734 let mut body = response.bytes_stream();
2735 while let Some(chunk) = body.next().await {
2736 let chunk = chunk.map_err(|_| BoundedBodyError::Transport)?;
2737 if output.len().saturating_add(chunk.len()) > maximum {
2738 return Err(BoundedBodyError::TooLarge);
2739 }
2740 output.extend_from_slice(&chunk);
2741 }
2742 Ok(output)
2743}
2744
2745fn is_json_content_type(headers: &HeaderMap) -> bool {
2746 exactly_one_header(headers, header::CONTENT_TYPE).is_some_and(|value| {
2747 value.parse::<mime::Mime>().is_ok_and(|mime| {
2748 mime.essence_str().eq_ignore_ascii_case(JSON)
2749 || mime.essence_str().eq_ignore_ascii_case(A2A_JSON)
2750 })
2751 })
2752}
2753
2754fn is_event_stream_content_type(headers: &HeaderMap) -> bool {
2755 exactly_one_header(headers, header::CONTENT_TYPE).is_some_and(|value| {
2756 value
2757 .parse::<mime::Mime>()
2758 .is_ok_and(|mime| mime.essence_str().eq_ignore_ascii_case(EVENT_STREAM))
2759 })
2760}
2761
2762fn exactly_one_header(headers: &HeaderMap, name: header::HeaderName) -> Option<&str> {
2763 let mut values = headers.get_all(name).iter();
2764 let first = values.next()?.to_str().ok()?;
2765 values.next().is_none().then_some(first)
2766}
2767
2768#[cfg(test)]
2769mod tests {
2770 use super::*;
2771 use serde_json::json;
2772
2773 #[test]
2774 fn endpoints_fail_closed_outside_exact_https_or_literal_loopback_profiles() {
2775 assert!(
2776 A2aAgentCardEndpoint::https("https://agent.example/.well-known/agent-card.json")
2777 .is_ok()
2778 );
2779 assert_eq!(
2780 A2aAgentCardEndpoint::https("http://agent.example/.well-known/agent-card.json")
2781 .unwrap_err(),
2782 A2aClientEndpointError::HttpsRequired
2783 );
2784 assert_eq!(
2785 A2aAgentCardEndpoint::loopback_http(
2786 "http://localhost:8080/.well-known/agent-card.json"
2787 )
2788 .unwrap_err(),
2789 A2aClientEndpointError::LiteralLoopbackRequired
2790 );
2791 assert_eq!(
2792 A2aAgentCardEndpoint::loopback_http("http://127.0.0.1:8080/card.json").unwrap_err(),
2793 A2aClientEndpointError::AgentCardPathRequired
2794 );
2795 assert_eq!(
2796 A2aClientInterfacePin::https(
2797 "https://agent.example/a2a?tenant=untrusted",
2798 A2aBinding::HttpJson,
2799 )
2800 .unwrap_err(),
2801 A2aClientEndpointError::QueryOrFragment
2802 );
2803 assert_eq!(
2804 A2aClientInterfacePin::https("https://agent.example/a2a", A2aBinding::HttpJson,)
2805 .unwrap()
2806 .with_tenant(" tenant-a")
2807 .unwrap_err(),
2808 A2aClientEndpointError::InvalidTenant
2809 );
2810 }
2811
2812 #[test]
2813 fn options_and_extension_headers_have_hard_finite_bounds() {
2814 assert_eq!(
2815 A2aClientOptions::new(
2816 ProviderHttpOptions::default(),
2817 Duration::ZERO,
2818 Duration::from_secs(1),
2819 Duration::from_secs(1),
2820 1,
2821 ),
2822 Err(A2aClientOptionsError::ZeroTimeout)
2823 );
2824 assert_eq!(
2825 A2aClientOptions::new(
2826 ProviderHttpOptions::default(),
2827 Duration::from_secs(1),
2828 Duration::from_secs(1),
2829 Duration::from_secs(1),
2830 A2aClientOptions::HARD_MAXIMUM_STREAM_EVENTS + 1,
2831 ),
2832 Err(A2aClientOptionsError::InvalidStreamEventLimit)
2833 );
2834 assert!(
2835 validate_extension_selection(&["https://extensions.example/v1".to_string()]).is_ok()
2836 );
2837 assert!(
2838 validate_extension_selection(&["https://extensions.example/v1,other".to_string()])
2839 .is_err()
2840 );
2841 }
2842
2843 #[test]
2844 fn response_unions_require_one_and_only_one_wire_variant() {
2845 assert!(require_exact_variant(&json!({"message": {}}), &["task", "message"]).is_ok());
2846 for invalid in [
2847 json!({}),
2848 json!({"task": {}, "message": {}}),
2849 json!({"message": {}, "unknown": true}),
2850 json!({"unknown": {}}),
2851 json!([]),
2852 ] {
2853 let error = require_exact_variant(&invalid, &["task", "message"]).unwrap_err();
2854 assert_eq!(error.kind(), A2aClientErrorKind::InvalidResponse);
2855 assert!(error.was_dispatched());
2856 }
2857 }
2858
2859 #[test]
2860 fn rest_errors_only_expose_standard_codes_not_remote_text() {
2861 let canonical = json!({
2862 "error": {
2863 "code": 400,
2864 "status": "INVALID_ARGUMENT",
2865 "message": "sensitive remote diagnostic",
2866 "details": [{
2867 "@type": "type.googleapis.com/google.rpc.ErrorInfo",
2868 "reason": "INVALID_PARAMS",
2869 "domain": "a2a-protocol.org"
2870 }]
2871 }
2872 });
2873 let parsed = parse_rest_error(&canonical, Some(StatusCode::BAD_REQUEST)).unwrap();
2874 assert_eq!(parsed.code, Some(wire::error_code::INVALID_PARAMS));
2875 let error = A2aClientError::remote(parsed.code, Some(StatusCode::BAD_REQUEST));
2876 let debug = format!("{error:?}");
2877 assert!(!debug.contains("sensitive remote diagnostic"));
2878 assert_eq!(error.http_status(), Some(400));
2879
2880 assert!(parse_rest_error(&canonical, Some(StatusCode::INTERNAL_SERVER_ERROR)).is_none());
2881 let mut inconsistent = canonical.clone();
2882 inconsistent["error"]["code"] = json!(500);
2883 inconsistent["error"]["status"] = json!("INTERNAL");
2884 assert_eq!(
2885 parse_rest_error(&inconsistent, Some(StatusCode::INTERNAL_SERVER_ERROR))
2886 .unwrap()
2887 .code,
2888 None
2889 );
2890 let mut foreign_domain = canonical;
2891 foreign_domain["error"]["details"][0]["domain"] = json!("example.invalid");
2892 assert_eq!(
2893 parse_rest_error(&foreign_domain, Some(StatusCode::BAD_REQUEST))
2894 .unwrap()
2895 .code,
2896 None
2897 );
2898 let mut ambiguous = inconsistent;
2899 ambiguous["error"]["code"] = json!(400);
2900 ambiguous["error"]["status"] = json!("INVALID_ARGUMENT");
2901 let duplicate = ambiguous["error"]["details"][0].clone();
2902 ambiguous["error"]["details"]
2903 .as_array_mut()
2904 .unwrap()
2905 .push(duplicate);
2906 assert_eq!(
2907 parse_rest_error(&ambiguous, Some(StatusCode::BAD_REQUEST))
2908 .unwrap()
2909 .code,
2910 None
2911 );
2912
2913 let rpc_error = parse_rpc_response(
2914 &json!({
2915 "jsonrpc": "2.0",
2916 "id": 7,
2917 "error": {"code": wire::error_code::INVALID_PARAMS, "message": "invalid"}
2918 }),
2919 7,
2920 Some(StatusCode::INTERNAL_SERVER_ERROR),
2921 )
2922 .unwrap_err();
2923 assert_eq!(rpc_error.kind(), A2aClientErrorKind::Remote);
2924 assert_eq!(rpc_error.remote_code(), None);
2925 }
2926
2927 #[test]
2928 fn stream_artifact_appends_require_an_unsealed_prior_artifact() {
2929 let task = A2aTask::new(
2930 "task-1",
2931 "context-1",
2932 crate::A2aTaskStatus::new(A2aTaskState::Working, None, None).unwrap(),
2933 )
2934 .unwrap();
2935 let artifact =
2936 crate::A2aArtifact::new("artifact-1", vec![crate::A2aPart::text("chunk").unwrap()])
2937 .unwrap();
2938 let append = crate::A2aArtifactUpdate::new("task-1", "context-1", artifact.clone())
2939 .unwrap()
2940 .as_chunk(false);
2941 let initial = crate::A2aArtifactUpdate::new("task-1", "context-1", artifact.clone())
2942 .unwrap()
2943 .as_initial_chunk();
2944 let final_chunk = crate::A2aArtifactUpdate::new("task-1", "context-1", artifact)
2945 .unwrap()
2946 .as_chunk(true);
2947 let mut validator =
2948 A2aStreamValidator::new(A2aStreamContract::SubscribeToTask("task-1".into()));
2949 validator.observe(&A2aStreamEvent::Task(task)).unwrap();
2950
2951 assert!(
2952 validator
2953 .observe(&A2aStreamEvent::ArtifactUpdate(append.clone()))
2954 .is_err()
2955 );
2956 validator
2957 .observe(&A2aStreamEvent::ArtifactUpdate(initial))
2958 .unwrap();
2959 validator
2960 .observe(&A2aStreamEvent::ArtifactUpdate(append.clone()))
2961 .unwrap();
2962 validator
2963 .observe(&A2aStreamEvent::ArtifactUpdate(final_chunk))
2964 .unwrap();
2965 assert!(
2966 validator
2967 .observe(&A2aStreamEvent::ArtifactUpdate(append))
2968 .is_err()
2969 );
2970 }
2971
2972 #[test]
2973 fn task_streams_close_on_interruption_and_reject_repeated_task_snapshots() {
2974 let task = |state| {
2975 A2aTask::new(
2976 "task-1",
2977 "context-1",
2978 crate::A2aTaskStatus::new(state, None, None).unwrap(),
2979 )
2980 .unwrap()
2981 };
2982 let mut validator =
2983 A2aStreamValidator::new(A2aStreamContract::SubscribeToTask("task-1".into()));
2984 validator
2985 .observe(&A2aStreamEvent::Task(task(A2aTaskState::Working)))
2986 .unwrap();
2987 let interrupted = crate::A2aStatusUpdate::new(
2988 "task-1",
2989 "context-1",
2990 crate::A2aTaskStatus::new(A2aTaskState::InputRequired, None, None).unwrap(),
2991 )
2992 .unwrap();
2993 validator
2994 .observe(&A2aStreamEvent::StatusUpdate(interrupted))
2995 .unwrap();
2996 assert!(validator.can_end());
2997
2998 let mut repeated =
2999 A2aStreamValidator::new(A2aStreamContract::SubscribeToTask("task-1".into()));
3000 repeated
3001 .observe(&A2aStreamEvent::Task(task(A2aTaskState::Working)))
3002 .unwrap();
3003 assert!(
3004 repeated
3005 .observe(&A2aStreamEvent::Task(task(A2aTaskState::Completed)))
3006 .is_err()
3007 );
3008 }
3009
3010 #[test]
3011 fn blocking_send_rejects_an_in_progress_task_snapshot() {
3012 let response = |state| {
3013 A2aSendMessageResponse::Task(
3014 A2aTask::new(
3015 "task-1",
3016 "context-1",
3017 crate::A2aTaskStatus::new(state, None, None).unwrap(),
3018 )
3019 .unwrap(),
3020 )
3021 };
3022 let mut expectation = A2aSendExpectation {
3023 task_id: None,
3024 context_id: None,
3025 history_length: None,
3026 return_immediately: false,
3027 };
3028 assert!(validate_send_response(&response(A2aTaskState::Working), &expectation).is_err());
3029 validate_send_response(&response(A2aTaskState::InputRequired), &expectation).unwrap();
3030 expectation.return_immediately = true;
3031 validate_send_response(&response(A2aTaskState::Working), &expectation).unwrap();
3032 }
3033
3034 #[test]
3035 fn task_pages_enforce_timestamp_filters_and_newest_first_ordering() {
3036 let after = "2026-09-03T08:00:00Z"
3037 .parse::<chrono::DateTime<chrono::Utc>>()
3038 .unwrap();
3039 let newer = "2026-09-03T08:00:02Z"
3040 .parse::<chrono::DateTime<chrono::Utc>>()
3041 .unwrap();
3042 let before = "2026-09-03T07:59:59Z"
3043 .parse::<chrono::DateTime<chrono::Utc>>()
3044 .unwrap();
3045 let request = A2aListTasksRequest::new()
3046 .with_page_size(2)
3047 .unwrap()
3048 .with_status_timestamp_after(after);
3049 let expectation = A2aListTasksExpectation::from_request(&request);
3050 let task = |id, timestamp| {
3051 A2aTask::new(
3052 id,
3053 "context-1",
3054 crate::A2aTaskStatus::new(A2aTaskState::Working, None, timestamp).unwrap(),
3055 )
3056 .unwrap()
3057 };
3058
3059 let valid = A2aTaskPage::new(
3060 vec![task("task-new", Some(newer)), task("task-at", Some(after))],
3061 None,
3062 2,
3063 2,
3064 )
3065 .unwrap();
3066 validate_task_page(&valid, &expectation).unwrap();
3067
3068 assert!(
3069 A2aTaskPage::new(
3070 vec![task("task-at", Some(after)), task("task-new", Some(newer))],
3071 None,
3072 2,
3073 2,
3074 )
3075 .is_err()
3076 );
3077
3078 let missing_timestamp =
3079 A2aTaskPage::new(vec![task("task-unknown", None)], None, 2, 1).unwrap();
3080 assert!(validate_task_page(&missing_timestamp, &expectation).is_err());
3081
3082 let before_bound =
3083 A2aTaskPage::new(vec![task("task-before", Some(before))], None, 2, 1).unwrap();
3084 assert!(validate_task_page(&before_bound, &expectation).is_err());
3085 }
3086}