1use std::{
15 collections::HashSet,
16 error::Error as StdError,
17 fmt,
18 sync::{
19 Arc,
20 atomic::{AtomicBool, Ordering},
21 },
22 time::Instant,
23};
24
25use stateknot_core::{
26 ArtifactRef, AttemptId, BoundedJson, BoxFuture, ByteCount, CapabilityIdentity, Digest,
27 DurationMillis, ErasedTool, EventId, ExecutionCount, Failure, FailureCategory, FailureCode,
28 FailureId, FailureMessage, FailureOrigin, GraphSchemaValidator, InvocationId,
29 ModelSchemaRegistry, RetryAdvice, RunId, TenantId, ToolArtifacts, ToolCancellationSupport,
30 ToolContext, ToolDescriptor, ToolError, ToolErrorPhase, ToolErrorProvenance,
31 ToolExternalEffect, ToolIdempotency, ToolInput, ToolReconciliationContext,
32 ToolReconciliationObservation, ToolReconciliationObservationError,
33 ToolReconciliationProbeError, ToolRecoveryHandle, ToolResourceAccess, ToolResult,
34 ToolResultProvenance, ToolRisk, ToolStopReason,
35};
36use thiserror::Error;
37
38use crate::{
39 A2aClient, A2aClientAttemptIdentity, A2aClientAuthorizationError, A2aClientError,
40 A2aClientErrorKind, A2aClientSecurityError, A2aContractError, A2aGetTaskRequest,
41 A2aListTasksRequest, A2aMessage, A2aMessageRole, A2aPart, A2aSendConfiguration,
42 A2aSendMessageRequest, A2aSendMessageResponse, A2aTask, A2aTaskState,
43};
44
45const A2A_TASK_RECOVERY_NAMESPACE: &str = "protocol.a2a.task";
46const MAX_A2A_ARTIFACT_SOURCE_ID_BYTES: usize = 512;
47const MAX_A2A_ARTIFACT_NAME_BYTES: usize = 512;
48const MAX_A2A_ARTIFACT_DESCRIPTION_BYTES: usize = 16 * 1024;
49
50#[derive(Clone)]
52#[non_exhaustive]
53pub enum A2aArtifactSource {
54 TaskArtifact {
56 task_id: Box<str>,
58 artifact_id: Box<str>,
60 artifact_index: u16,
62 part_index: u16,
64 },
65}
66
67impl A2aArtifactSource {
68 pub fn task_artifact(
75 task_id: impl Into<String>,
76 artifact_id: impl Into<String>,
77 artifact_index: u16,
78 part_index: u16,
79 ) -> Result<Self, A2aContractError> {
80 let task_id = task_id.into();
81 let artifact_id = artifact_id.into();
82 validate_ingestion_text(
83 "artifact source task id",
84 &task_id,
85 MAX_A2A_ARTIFACT_SOURCE_ID_BYTES,
86 )?;
87 validate_ingestion_text(
88 "artifact source artifact id",
89 &artifact_id,
90 MAX_A2A_ARTIFACT_SOURCE_ID_BYTES,
91 )?;
92 Ok(Self::TaskArtifact {
93 task_id: task_id.into_boxed_str(),
94 artifact_id: artifact_id.into_boxed_str(),
95 artifact_index,
96 part_index,
97 })
98 }
99
100 #[must_use]
102 pub fn task_id(&self) -> &str {
103 match self {
104 Self::TaskArtifact { task_id, .. } => task_id,
105 }
106 }
107
108 #[must_use]
110 pub fn artifact_id(&self) -> &str {
111 match self {
112 Self::TaskArtifact { artifact_id, .. } => artifact_id,
113 }
114 }
115
116 #[must_use]
118 pub const fn artifact_index(&self) -> u16 {
119 match self {
120 Self::TaskArtifact { artifact_index, .. } => *artifact_index,
121 }
122 }
123
124 #[must_use]
126 pub const fn part_index(&self) -> u16 {
127 match self {
128 Self::TaskArtifact { part_index, .. } => *part_index,
129 }
130 }
131}
132
133impl fmt::Debug for A2aArtifactSource {
134 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135 match self {
136 Self::TaskArtifact {
137 task_id,
138 artifact_id,
139 artifact_index,
140 part_index,
141 } => formatter
142 .debug_struct("A2aArtifactSource::TaskArtifact")
143 .field("task_id_bytes", &task_id.len())
144 .field("artifact_id_bytes", &artifact_id.len())
145 .field("artifact_index", artifact_index)
146 .field("part_index", part_index)
147 .finish(),
148 }
149 }
150}
151
152#[derive(Clone)]
154pub struct A2aArtifactIngestionRequest {
155 tenant_id: TenantId,
156 run_id: RunId,
157 invocation_id: InvocationId,
158 attempt_id: AttemptId,
159 origin_event_id: EventId,
160 tool: CapabilityIdentity,
161 source: A2aArtifactSource,
162 artifact_name: Option<Box<str>>,
163 artifact_description: Option<Box<str>>,
164 part: A2aPart,
165 maximum_bytes: ByteCount,
166}
167
168impl A2aArtifactIngestionRequest {
169 #[allow(clippy::too_many_arguments)]
176 pub fn new(
177 tenant_id: TenantId,
178 run_id: RunId,
179 invocation_id: InvocationId,
180 attempt_id: AttemptId,
181 origin_event_id: EventId,
182 tool: CapabilityIdentity,
183 source: A2aArtifactSource,
184 artifact_name: Option<String>,
185 artifact_description: Option<String>,
186 part: A2aPart,
187 maximum_bytes: ByteCount,
188 ) -> Result<Self, A2aContractError> {
189 if let Some(name) = artifact_name.as_deref() {
190 validate_ingestion_text("artifact ingestion name", name, MAX_A2A_ARTIFACT_NAME_BYTES)?;
191 }
192 if let Some(description) = artifact_description.as_deref() {
193 validate_ingestion_text(
194 "artifact ingestion description",
195 description,
196 MAX_A2A_ARTIFACT_DESCRIPTION_BYTES,
197 )?;
198 }
199 Ok(Self {
200 tenant_id,
201 run_id,
202 invocation_id,
203 attempt_id,
204 origin_event_id,
205 tool,
206 source,
207 artifact_name: artifact_name.map(String::into_boxed_str),
208 artifact_description: artifact_description.map(String::into_boxed_str),
209 part,
210 maximum_bytes,
211 })
212 }
213
214 #[must_use]
216 pub const fn tenant_id(&self) -> &TenantId {
217 &self.tenant_id
218 }
219
220 #[must_use]
222 pub const fn run_id(&self) -> RunId {
223 self.run_id
224 }
225
226 #[must_use]
228 pub const fn invocation_id(&self) -> InvocationId {
229 self.invocation_id
230 }
231
232 #[must_use]
234 pub const fn attempt_id(&self) -> AttemptId {
235 self.attempt_id
236 }
237
238 #[must_use]
240 pub const fn origin_event_id(&self) -> EventId {
241 self.origin_event_id
242 }
243
244 #[must_use]
246 pub const fn tool(&self) -> &CapabilityIdentity {
247 &self.tool
248 }
249
250 #[must_use]
252 pub const fn source(&self) -> &A2aArtifactSource {
253 &self.source
254 }
255
256 #[must_use]
258 pub fn artifact_name(&self) -> Option<&str> {
259 self.artifact_name.as_deref()
260 }
261
262 #[must_use]
264 pub fn artifact_description(&self) -> Option<&str> {
265 self.artifact_description.as_deref()
266 }
267
268 #[must_use]
270 pub const fn part(&self) -> &A2aPart {
271 &self.part
272 }
273
274 #[must_use]
276 pub const fn maximum_bytes(&self) -> ByteCount {
277 self.maximum_bytes
278 }
279}
280
281fn validate_ingestion_text(
282 field: &'static str,
283 value: &str,
284 maximum: usize,
285) -> Result<(), A2aContractError> {
286 if value.is_empty() {
287 return Err(A2aContractError::Empty { field });
288 }
289 if value.len() > maximum {
290 return Err(A2aContractError::TooLarge {
291 field,
292 maximum,
293 actual: value.len(),
294 });
295 }
296 if value.trim() != value || value.chars().any(char::is_control) {
297 return Err(A2aContractError::InvalidText { field });
298 }
299 Ok(())
300}
301
302impl fmt::Debug for A2aArtifactIngestionRequest {
303 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304 formatter
305 .debug_struct("A2aArtifactIngestionRequest")
306 .field("tenant_id", &self.tenant_id)
307 .field("run_id", &self.run_id)
308 .field("invocation_id", &self.invocation_id)
309 .field("attempt_id", &self.attempt_id)
310 .field("origin_event_id", &self.origin_event_id)
311 .field("tool", &self.tool)
312 .field("source", &self.source)
313 .field("has_artifact_name", &self.artifact_name.is_some())
314 .field(
315 "has_artifact_description",
316 &self.artifact_description.is_some(),
317 )
318 .field("maximum_bytes", &self.maximum_bytes)
319 .finish_non_exhaustive()
320 }
321}
322
323#[derive(Clone, Copy, Debug, Eq, PartialEq)]
325#[non_exhaustive]
326pub enum A2aArtifactIngestionErrorKind {
327 InvalidContent,
329 PolicyDenied,
331 Integrity,
333 Unavailable,
335}
336
337type PrivateArtifactIngestionSource = dyn StdError + Send + Sync + 'static;
338
339#[derive(Clone)]
341pub struct A2aArtifactIngestionError {
342 kind: A2aArtifactIngestionErrorKind,
343 private_source: Arc<PrivateArtifactIngestionSource>,
344}
345
346impl A2aArtifactIngestionError {
347 #[must_use]
349 pub fn new<E>(kind: A2aArtifactIngestionErrorKind, source: E) -> Self
350 where
351 E: StdError + Send + Sync + 'static,
352 {
353 Self {
354 kind,
355 private_source: Arc::new(source),
356 }
357 }
358
359 #[must_use]
361 pub const fn kind(&self) -> A2aArtifactIngestionErrorKind {
362 self.kind
363 }
364
365 #[must_use]
367 pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
368 self.private_source.as_ref()
369 }
370}
371
372impl fmt::Debug for A2aArtifactIngestionError {
373 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
374 formatter
375 .debug_struct("A2aArtifactIngestionError")
376 .field("kind", &self.kind)
377 .field("has_private_source", &true)
378 .finish_non_exhaustive()
379 }
380}
381
382impl fmt::Display for A2aArtifactIngestionError {
383 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
384 write!(formatter, "A2A artifact ingestion failed: {:?}", self.kind)
385 }
386}
387
388impl StdError for A2aArtifactIngestionError {}
389
390pub trait A2aArtifactIngestor: Send + Sync + 'static {
393 fn ingest(
401 &self,
402 request: A2aArtifactIngestionRequest,
403 ) -> BoxFuture<'_, Result<ArtifactRef, A2aArtifactIngestionError>>;
404}
405
406enum DurableTaskResultError {
407 Invalid,
408 Ingestion(A2aArtifactIngestionError),
409}
410
411pub trait A2aSchemaRegistry: ModelSchemaRegistry + GraphSchemaValidator {}
417
418impl<T> A2aSchemaRegistry for T where T: ModelSchemaRegistry + GraphSchemaValidator {}
419
420#[derive(Clone, Copy, Debug, Eq, PartialEq)]
422#[non_exhaustive]
423pub enum A2aRemoteAgentDelivery {
424 AtMostOnce,
427 MessageIdDeduplicated,
430}
431
432#[derive(Clone, Copy, Debug, Eq, PartialEq)]
434#[non_exhaustive]
435pub enum A2aRemoteAgentRecoveryMode {
436 Disabled,
438 ContextTaskHistory,
441 MessageIdReplay,
444}
445
446#[derive(Clone, Copy, Debug, Eq, PartialEq)]
447enum A2aRemoteAgentRecoveryKind {
448 Disabled,
449 ContextTaskHistory {
450 maximum_pages: u8,
451 history_length: u16,
452 retry_after: DurationMillis,
453 },
454 MessageIdReplay {
455 retry_after: DurationMillis,
456 },
457}
458
459#[derive(Clone, Copy, Debug, Eq, PartialEq)]
465pub struct A2aRemoteAgentRecovery {
466 kind: A2aRemoteAgentRecoveryKind,
467}
468
469impl A2aRemoteAgentRecovery {
470 pub const MAXIMUM_CONTEXT_PAGES: u8 = 16;
472 pub const MAXIMUM_HISTORY_LENGTH: u16 = 256;
474
475 #[must_use]
477 pub const fn disabled() -> Self {
478 Self {
479 kind: A2aRemoteAgentRecoveryKind::Disabled,
480 }
481 }
482
483 pub fn operator_attested_context_task_history(
490 maximum_pages: u8,
491 history_length: u16,
492 retry_after: DurationMillis,
493 ) -> Result<Self, A2aRemoteAgentRecoveryError> {
494 if maximum_pages == 0 || maximum_pages > Self::MAXIMUM_CONTEXT_PAGES {
495 return Err(A2aRemoteAgentRecoveryError::InvalidMaximumPages);
496 }
497 if history_length == 0 || history_length > Self::MAXIMUM_HISTORY_LENGTH {
498 return Err(A2aRemoteAgentRecoveryError::InvalidHistoryLength);
499 }
500 validate_recovery_delay(retry_after)?;
501 Ok(Self {
502 kind: A2aRemoteAgentRecoveryKind::ContextTaskHistory {
503 maximum_pages,
504 history_length,
505 retry_after,
506 },
507 })
508 }
509
510 pub fn operator_attested_message_id_replay(
516 retry_after: DurationMillis,
517 ) -> Result<Self, A2aRemoteAgentRecoveryError> {
518 validate_recovery_delay(retry_after)?;
519 Ok(Self {
520 kind: A2aRemoteAgentRecoveryKind::MessageIdReplay { retry_after },
521 })
522 }
523
524 #[must_use]
526 pub const fn mode(self) -> A2aRemoteAgentRecoveryMode {
527 match self.kind {
528 A2aRemoteAgentRecoveryKind::Disabled => A2aRemoteAgentRecoveryMode::Disabled,
529 A2aRemoteAgentRecoveryKind::ContextTaskHistory { .. } => {
530 A2aRemoteAgentRecoveryMode::ContextTaskHistory
531 }
532 A2aRemoteAgentRecoveryKind::MessageIdReplay { .. } => {
533 A2aRemoteAgentRecoveryMode::MessageIdReplay
534 }
535 }
536 }
537
538 const fn retry_after(self) -> Option<DurationMillis> {
539 match self.kind {
540 A2aRemoteAgentRecoveryKind::Disabled => None,
541 A2aRemoteAgentRecoveryKind::ContextTaskHistory { retry_after, .. }
542 | A2aRemoteAgentRecoveryKind::MessageIdReplay { retry_after } => Some(retry_after),
543 }
544 }
545}
546
547impl Default for A2aRemoteAgentRecovery {
548 fn default() -> Self {
549 Self::disabled()
550 }
551}
552
553fn validate_recovery_delay(retry_after: DurationMillis) -> Result<(), A2aRemoteAgentRecoveryError> {
554 ToolReconciliationObservation::pending(retry_after)
555 .map(|_| ())
556 .map_err(A2aRemoteAgentRecoveryError::invalid_retry_delay)
557}
558
559#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
561#[non_exhaustive]
562pub enum A2aRemoteAgentRecoveryError {
563 #[error("A2A reconciliation maximum pages must be between 1 and 16")]
565 InvalidMaximumPages,
566 #[error("A2A reconciliation history length must be between 1 and 256")]
568 InvalidHistoryLength,
569 #[error("A2A reconciliation retry delay is invalid: {source}")]
571 InvalidRetryDelay {
572 #[source]
574 source: ToolReconciliationObservationError,
575 },
576}
577
578impl A2aRemoteAgentRecoveryError {
579 const fn invalid_retry_delay(source: ToolReconciliationObservationError) -> Self {
580 Self::InvalidRetryDelay { source }
581 }
582}
583
584pub struct A2aRemoteAgent {
586 descriptor: ToolDescriptor,
587 client: A2aClient,
588 skill_id: Box<str>,
589 delivery: A2aRemoteAgentDelivery,
590 recovery: A2aRemoteAgentRecovery,
591 required_scopes: Arc<[Box<str>]>,
592 output_modes: Arc<[Box<str>]>,
593 schemas: Arc<dyn A2aSchemaRegistry>,
594 artifact_ingestor: Option<Arc<dyn A2aArtifactIngestor>>,
595}
596
597impl A2aRemoteAgent {
598 pub fn bind(
608 descriptor: ToolDescriptor,
609 client: A2aClient,
610 skill_id: impl Into<String>,
611 delivery: A2aRemoteAgentDelivery,
612 schemas: Arc<dyn A2aSchemaRegistry>,
613 ) -> Result<Self, A2aRemoteAgentBuildError> {
614 Self::bind_with_recovery(
615 descriptor,
616 client,
617 skill_id,
618 delivery,
619 A2aRemoteAgentRecovery::disabled(),
620 schemas,
621 )
622 }
623
624 pub fn bind_with_recovery(
632 descriptor: ToolDescriptor,
633 client: A2aClient,
634 skill_id: impl Into<String>,
635 delivery: A2aRemoteAgentDelivery,
636 recovery: A2aRemoteAgentRecovery,
637 schemas: Arc<dyn A2aSchemaRegistry>,
638 ) -> Result<Self, A2aRemoteAgentBuildError> {
639 Self::bind_internal(
640 descriptor, client, skill_id, delivery, recovery, schemas, None,
641 )
642 }
643
644 pub fn bind_with_durable_artifacts(
651 descriptor: ToolDescriptor,
652 client: A2aClient,
653 skill_id: impl Into<String>,
654 delivery: A2aRemoteAgentDelivery,
655 recovery: A2aRemoteAgentRecovery,
656 schemas: Arc<dyn A2aSchemaRegistry>,
657 artifact_ingestor: Arc<dyn A2aArtifactIngestor>,
658 ) -> Result<Self, A2aRemoteAgentBuildError> {
659 if recovery.mode() == A2aRemoteAgentRecoveryMode::Disabled {
660 return Err(A2aRemoteAgentBuildError::DurableArtifactsRequireRecovery);
661 }
662 if descriptor.limits().max_artifacts() == ExecutionCount::ZERO {
663 return Err(A2aRemoteAgentBuildError::ArtifactCapacityRequired);
664 }
665 Self::bind_internal(
666 descriptor,
667 client,
668 skill_id,
669 delivery,
670 recovery,
671 schemas,
672 Some(artifact_ingestor),
673 )
674 }
675
676 #[allow(clippy::too_many_arguments)]
677 fn bind_internal(
678 descriptor: ToolDescriptor,
679 client: A2aClient,
680 skill_id: impl Into<String>,
681 delivery: A2aRemoteAgentDelivery,
682 recovery: A2aRemoteAgentRecovery,
683 schemas: Arc<dyn A2aSchemaRegistry>,
684 artifact_ingestor: Option<Arc<dyn A2aArtifactIngestor>>,
685 ) -> Result<Self, A2aRemoteAgentBuildError> {
686 validate_descriptor(&descriptor, &client, delivery, recovery)?;
687 schemas
688 .canonical_schema_bytes(descriptor.input_schema())
689 .ok_or(A2aRemoteAgentBuildError::InputSchemaUnavailable)?;
690 schemas
691 .canonical_schema_bytes(descriptor.output_schema())
692 .ok_or(A2aRemoteAgentBuildError::OutputSchemaUnavailable)?;
693
694 let skill_id = skill_id.into();
695 let skill = client
696 .agent_card()
697 .skills()
698 .into_iter()
699 .find(|skill| skill.id() == skill_id)
700 .ok_or(A2aRemoteAgentBuildError::SkillUnavailable)?;
701 let input_modes = if skill.input_modes().is_empty() {
702 client.agent_card().default_input_modes()
703 } else {
704 skill.input_modes()
705 };
706 if !input_modes.iter().any(|mode| accepts_json(mode)) {
707 return Err(A2aRemoteAgentBuildError::JsonInputModeUnsupported);
708 }
709 let output_modes = if skill.output_modes().is_empty() {
710 client.agent_card().default_output_modes().to_vec()
711 } else {
712 skill.output_modes().to_vec()
713 };
714 if output_modes.is_empty() {
715 return Err(A2aRemoteAgentBuildError::OutputModesUnavailable);
716 }
717 let required_scopes = client
718 .skill_required_scopes(&skill_id)
719 .ok_or(A2aRemoteAgentBuildError::SkillUnavailable)??;
720
721 Ok(Self {
722 descriptor,
723 client,
724 skill_id: skill_id.into_boxed_str(),
725 delivery,
726 recovery,
727 required_scopes,
728 output_modes: output_modes
729 .into_iter()
730 .map(String::into_boxed_str)
731 .collect::<Vec<_>>()
732 .into(),
733 schemas,
734 artifact_ingestor,
735 })
736 }
737
738 #[must_use]
740 pub fn skill_id(&self) -> &str {
741 &self.skill_id
742 }
743
744 #[must_use]
746 pub const fn delivery(&self) -> A2aRemoteAgentDelivery {
747 self.delivery
748 }
749
750 #[must_use]
752 pub const fn recovery(&self) -> A2aRemoteAgentRecovery {
753 self.recovery
754 }
755
756 #[must_use]
759 pub const fn durable_artifacts_enabled(&self) -> bool {
760 self.artifact_ingestor.is_some()
761 }
762
763 fn preparation_error(
764 &self,
765 context: &ToolContext,
766 category: FailureCategory,
767 code: &'static str,
768 message: &'static str,
769 retry: RetryAdvice,
770 ) -> ToolError {
771 self.error(
772 context,
773 ToolErrorPhase::Preparation,
774 category,
775 code,
776 message,
777 retry,
778 ToolExternalEffect::NotStarted,
779 )
780 }
781
782 fn rejected_error(
783 &self,
784 context: &ToolContext,
785 category: FailureCategory,
786 code: &'static str,
787 message: &'static str,
788 ) -> ToolError {
789 self.error(
790 context,
791 ToolErrorPhase::Execution,
792 category,
793 code,
794 message,
795 RetryAdvice::Never,
796 ToolExternalEffect::NotApplied,
797 )
798 }
799
800 fn unknown_outcome(&self, context: &ToolContext) -> ToolError {
801 self.error(
802 context,
803 ToolErrorPhase::Execution,
804 FailureCategory::AmbiguousExternalOutcome,
805 "call.outcome_unknown",
806 "The A2A message may have been accepted; reconcile it before recovery.",
807 RetryAdvice::ReconcileFirst,
808 ToolExternalEffect::Unknown,
809 )
810 }
811
812 fn task_recovery_handle(&self, task_id: &str) -> ToolRecoveryHandle {
813 ToolRecoveryHandle::new(
814 FailureOrigin::new(A2A_TASK_RECOVERY_NAMESPACE)
815 .expect("A2A task recovery namespace is valid"),
816 self.client.agent_card_digest(),
817 task_id,
818 )
819 .expect("validated A2A task identifiers fit the recovery-handle contract")
820 }
821
822 fn unknown_task_outcome(&self, context: &ToolContext, task_id: &str) -> ToolError {
823 self.unknown_outcome(context)
824 .with_recovery_handle(self.task_recovery_handle(task_id))
825 .expect("unknown A2A outcomes accept a recovery handle")
826 }
827
828 fn invalid_result(&self, context: &ToolContext) -> ToolError {
829 self.error(
830 context,
831 ToolErrorPhase::Result,
832 FailureCategory::DataCorruption,
833 "result.invalid",
834 "The A2A agent returned a result outside the pinned local contract.",
835 RetryAdvice::Never,
836 ToolExternalEffect::Applied,
837 )
838 }
839
840 fn terminal_task_error(&self, context: &ToolContext, state: A2aTaskState) -> ToolError {
841 let (category, code, message) = terminal_task_failure(state);
842 self.error(
843 context,
844 ToolErrorPhase::Execution,
845 category,
846 code,
847 message,
848 RetryAdvice::Never,
849 ToolExternalEffect::Applied,
850 )
851 }
852
853 fn artifact_ingestion_error(
854 &self,
855 context: &ToolContext,
856 task_id: &str,
857 error: &A2aArtifactIngestionError,
858 ) -> ToolError {
859 match error.kind() {
860 A2aArtifactIngestionErrorKind::Unavailable => {
861 self.unknown_task_outcome(context, task_id)
862 }
863 A2aArtifactIngestionErrorKind::PolicyDenied => self.error(
864 context,
865 ToolErrorPhase::Result,
866 FailureCategory::PermissionDenied,
867 "artifact.policy_denied",
868 "Local policy denied an A2A artifact.",
869 RetryAdvice::Never,
870 ToolExternalEffect::Applied,
871 ),
872 A2aArtifactIngestionErrorKind::InvalidContent
873 | A2aArtifactIngestionErrorKind::Integrity => self.invalid_result(context),
874 }
875 }
876
877 fn durable_task_projection(
878 &self,
879 task: &A2aTask,
880 artifact_count: usize,
881 maximum_inline_bytes: ByteCount,
882 ) -> Result<BoundedJson, DurableTaskResultError> {
883 let value = serde_json::json!({
884 "kind": "task",
885 "task_id": task.id(),
886 "context_id": task.context_id(),
887 "state": "completed",
888 "artifact_count": artifact_count,
889 });
890 let output =
891 BoundedJson::try_from_value(value).map_err(|_| DurableTaskResultError::Invalid)?;
892 let encoded_bytes = u64::try_from(output.stats().compact_bytes()).unwrap_or(u64::MAX);
893 if encoded_bytes > maximum_inline_bytes.get()
894 || self
895 .schemas
896 .validate(self.descriptor.output_schema(), &output)
897 .is_err()
898 {
899 return Err(DurableTaskResultError::Invalid);
900 }
901 Ok(output)
902 }
903
904 #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
905 async fn durable_task_components(
906 &self,
907 tenant_id: &TenantId,
908 run_id: RunId,
909 invocation_id: InvocationId,
910 attempt_id: AttemptId,
911 origin_event_id: EventId,
912 maximum_inline_bytes: ByteCount,
913 maximum_artifacts: ExecutionCount,
914 maximum_artifact_bytes: ByteCount,
915 task: &A2aTask,
916 ) -> Result<(BoundedJson, ToolArtifacts), DurableTaskResultError> {
917 let ingestor = self
918 .artifact_ingestor
919 .as_ref()
920 .expect("durable task mapping requires an artifact ingestor");
921 let remote_artifacts = task.artifacts();
922 let artifact_count = remote_artifacts
923 .iter()
924 .map(|artifact| artifact.parts().len())
925 .try_fold(0_usize, usize::checked_add)
926 .ok_or(DurableTaskResultError::Invalid)?;
927 let hard_maximum = usize::try_from(maximum_artifacts.get())
928 .unwrap_or(usize::MAX)
929 .min(ToolArtifacts::MAX_LEN);
930 if artifact_count > hard_maximum {
931 return Err(DurableTaskResultError::Invalid);
932 }
933
934 let output = self.durable_task_projection(task, artifact_count, maximum_inline_bytes)?;
936 let mut remaining = maximum_artifact_bytes;
937 let mut local_artifacts = Vec::with_capacity(artifact_count);
938 let mut identities = HashSet::with_capacity(artifact_count);
939 for (artifact_index, artifact) in remote_artifacts.into_iter().enumerate() {
940 for (part_index, part) in artifact.parts().enumerate() {
941 let request = A2aArtifactIngestionRequest {
942 tenant_id: tenant_id.clone(),
943 run_id,
944 invocation_id,
945 attempt_id,
946 origin_event_id,
947 tool: self.descriptor.metadata().identity().clone(),
948 source: A2aArtifactSource::TaskArtifact {
949 task_id: task.id().to_owned().into_boxed_str(),
950 artifact_id: artifact.artifact_id().to_owned().into_boxed_str(),
951 artifact_index: u16::try_from(artifact_index)
952 .map_err(|_| DurableTaskResultError::Invalid)?,
953 part_index: u16::try_from(part_index)
954 .map_err(|_| DurableTaskResultError::Invalid)?,
955 },
956 artifact_name: artifact
957 .name()
958 .map(|value| value.to_owned().into_boxed_str()),
959 artifact_description: artifact
960 .description()
961 .map(|value| value.to_owned().into_boxed_str()),
962 part: part.to_owned(),
963 maximum_bytes: remaining,
964 };
965 let local = ingestor
966 .ingest(request)
967 .await
968 .map_err(DurableTaskResultError::Ingestion)?;
969 if local.identity().tenant_id() != tenant_id
970 || local.provenance().run_id() != run_id
971 || local.provenance().event_id() != origin_event_id
972 || local.provenance().principal()
973 != self.descriptor.metadata().identity().owner()
974 || local.provenance().capability()
975 != Some(self.descriptor.metadata().identity().capability())
976 || local.representation().byte_length() > remaining
977 || !identities.insert(local.identity().clone())
978 {
979 return Err(DurableTaskResultError::Invalid);
980 }
981 remaining = remaining
982 .checked_sub(local.representation().byte_length())
983 .ok_or(DurableTaskResultError::Invalid)?;
984 local_artifacts.push(local);
985 }
986 }
987 let artifacts =
988 ToolArtifacts::try_new(local_artifacts).map_err(|_| DurableTaskResultError::Invalid)?;
989 Ok((output, artifacts))
990 }
991
992 #[allow(clippy::too_many_arguments)]
993 fn error(
994 &self,
995 context: &ToolContext,
996 phase: ToolErrorPhase,
997 category: FailureCategory,
998 code: &'static str,
999 message: &'static str,
1000 retry: RetryAdvice,
1001 effect: ToolExternalEffect,
1002 ) -> ToolError {
1003 let failure = Failure::new(
1004 FailureId::generate(),
1005 category,
1006 FailureCode::new(code).expect("A2A failure codes are valid constants"),
1007 FailureOrigin::new("protocol.a2a").expect("A2A failure origin is valid"),
1008 FailureMessage::new(message).expect("A2A public failure messages are valid"),
1009 retry,
1010 )
1011 .expect("A2A failure category and retry advice are coherent");
1012 ToolError::new(
1013 failure,
1014 phase,
1015 effect,
1016 ToolErrorProvenance::for_invocation(context, &self.descriptor),
1017 )
1018 .expect("A2A phase, risk evidence, and failure category are coherent")
1019 }
1020
1021 #[allow(clippy::too_many_lines)]
1022 async fn call_inner(
1023 &self,
1024 context: ToolContext,
1025 input: ToolInput,
1026 ) -> Result<ToolResult, ToolError> {
1027 input
1028 .validate_for(&context, &self.descriptor)
1029 .map_err(|_| {
1030 self.preparation_error(
1031 &context,
1032 FailureCategory::InvalidInput,
1033 "input.binding_invalid",
1034 "The A2A input does not match this invocation binding.",
1035 RetryAdvice::Never,
1036 )
1037 })?;
1038 self.schemas
1039 .validate(self.descriptor.input_schema(), input.value())
1040 .map_err(|_| {
1041 self.preparation_error(
1042 &context,
1043 FailureCategory::InvalidInput,
1044 "input.schema_rejected",
1045 "The A2A input failed its pinned local schema.",
1046 RetryAdvice::Never,
1047 )
1048 })?;
1049 if self.artifact_ingestor.is_some() && context.origin_event_id().is_none() {
1050 return Err(self.preparation_error(
1051 &context,
1052 FailureCategory::Internal,
1053 "artifact.origin_event_missing",
1054 "The durable A2A artifact origin is unavailable.",
1055 RetryAdvice::Never,
1056 ));
1057 }
1058
1059 if let Some(reason) = context.stop_reason_at(Instant::now()) {
1060 return Err(self.stop_before_dispatch(&context, reason));
1061 }
1062 let message_id = self.message_id(&context).ok_or_else(|| {
1063 self.preparation_error(
1064 &context,
1065 FailureCategory::Internal,
1066 "request.idempotency_key_missing",
1067 "The durable A2A idempotency key is unavailable.",
1068 RetryAdvice::Never,
1069 )
1070 })?;
1071 let context_id = self.context_id(
1072 context.tenant_id().as_str(),
1073 &context.run_id().to_string(),
1074 &context.thread_id().to_string(),
1075 &context.invocation_id().to_string(),
1076 &context.attempt_id().to_string(),
1077 );
1078 let request = self
1079 .request(message_id, context_id, input.value())
1080 .map_err(|_| {
1081 self.preparation_error(
1082 &context,
1083 FailureCategory::Internal,
1084 "request.mapping_failed",
1085 "The bounded A2A request could not be constructed.",
1086 RetryAdvice::Never,
1087 )
1088 })?;
1089 let attempt = A2aClientAttemptIdentity::new(
1090 context.tenant_id().clone(),
1091 context.run_id(),
1092 context.invocation_id(),
1093 context.attempt_id(),
1094 );
1095 let dispatched = Arc::new(AtomicBool::new(false));
1096 let call = self.client.send_message_with_attempt(
1097 request,
1098 attempt,
1099 self.required_scopes.clone(),
1100 dispatched.clone(),
1101 );
1102 let response = wait_for_tool(&context, call)
1103 .await
1104 .map_err(|reason| {
1105 if dispatched.load(Ordering::Acquire) {
1106 self.stop_after_dispatch(&context, reason)
1107 } else {
1108 self.stop_before_dispatch(&context, reason)
1109 }
1110 })?
1111 .map_err(|error| self.client_error(&context, &error))?;
1112
1113 let (output, artifacts) = if self.artifact_ingestor.is_some() {
1114 let A2aSendMessageResponse::Task(task) = response else {
1115 return Err(self.invalid_result(&context));
1116 };
1117 match task.state() {
1118 A2aTaskState::Completed => self
1119 .durable_task_components(
1120 context.tenant_id(),
1121 context.run_id(),
1122 context.invocation_id(),
1123 context.attempt_id(),
1124 context
1125 .origin_event_id()
1126 .expect("durable artifact mode checked the origin event"),
1127 context.max_inline_result_bytes(),
1128 context.max_artifacts(),
1129 context.max_total_artifact_bytes(),
1130 &task,
1131 )
1132 .await
1133 .map_err(|error| match error {
1134 DurableTaskResultError::Invalid => self.invalid_result(&context),
1135 DurableTaskResultError::Ingestion(error) => {
1136 self.artifact_ingestion_error(&context, task.id(), &error)
1137 }
1138 })?,
1139 state if state.is_terminal() => {
1140 return Err(self.terminal_task_error(&context, state));
1141 }
1142 _ => return Err(self.unknown_task_outcome(&context, task.id())),
1143 }
1144 } else {
1145 let value = response
1146 .to_json()
1147 .map_err(|_| self.invalid_result(&context))?;
1148 let output =
1149 BoundedJson::try_from_value(value).map_err(|_| self.invalid_result(&context))?;
1150 self.schemas
1151 .validate(self.descriptor.output_schema(), &output)
1152 .map_err(|_| self.invalid_result(&context))?;
1153 (output, ToolArtifacts::empty())
1154 };
1155 let result = ToolResult::for_invocation(&context, &self.descriptor, output, artifacts);
1156 result
1157 .validate_for(&context, &self.descriptor)
1158 .map_err(|_| self.invalid_result(&context))?;
1159 Ok(result)
1160 }
1161
1162 fn message_id(&self, context: &ToolContext) -> Option<String> {
1163 match self.delivery {
1164 A2aRemoteAgentDelivery::AtMostOnce => {
1165 Some(format!("stateknot-attempt-{}", context.attempt_id()))
1166 }
1167 A2aRemoteAgentDelivery::MessageIdDeduplicated => context
1168 .idempotency_key()
1169 .map(|key| format!("stateknot-invocation-{key}")),
1170 }
1171 }
1172
1173 fn request(
1174 &self,
1175 message_id: String,
1176 context_id: Option<String>,
1177 input: &BoundedJson,
1178 ) -> Result<A2aSendMessageRequest, A2aContractError> {
1179 let part = A2aPart::data(input.as_value().clone())?.with_media_type("application/json")?;
1180 let mut message = A2aMessage::new(message_id, A2aMessageRole::User, vec![part])?;
1181 if let Some(context_id) = context_id {
1182 message = message.with_context_id(context_id)?;
1183 }
1184 let configuration = A2aSendConfiguration::new()
1185 .with_accepted_output_modes(
1186 self.output_modes.iter().map(ToString::to_string).collect(),
1187 )?
1188 .return_immediately(true);
1189 Ok(A2aSendMessageRequest::new(message).with_configuration(configuration))
1190 }
1191
1192 fn reconciliation_message_id(&self, context: &ToolReconciliationContext) -> Option<String> {
1193 match self.delivery {
1194 A2aRemoteAgentDelivery::AtMostOnce => {
1195 Some(format!("stateknot-attempt-{}", context.attempt_id()))
1196 }
1197 A2aRemoteAgentDelivery::MessageIdDeduplicated => context
1198 .idempotency_key()
1199 .map(|key| format!("stateknot-invocation-{key}")),
1200 }
1201 }
1202
1203 fn reconciliation_context_id(&self, context: &ToolReconciliationContext) -> Option<String> {
1204 self.context_id(
1205 context.tenant_id().as_str(),
1206 &context.run_id().to_string(),
1207 &context.thread_id().to_string(),
1208 &context.invocation_id().to_string(),
1209 &context.attempt_id().to_string(),
1210 )
1211 }
1212
1213 fn context_id(
1214 &self,
1215 tenant_id: &str,
1216 run_id: &str,
1217 thread_id: &str,
1218 invocation_id: &str,
1219 attempt_id: &str,
1220 ) -> Option<String> {
1221 if !matches!(
1222 self.recovery.kind,
1223 A2aRemoteAgentRecoveryKind::ContextTaskHistory { .. }
1224 ) {
1225 return None;
1226 }
1227 let mut material = b"stateknot.a2a.reconciliation-context.v1\0".to_vec();
1228 for value in [tenant_id, run_id, thread_id, invocation_id, attempt_id] {
1229 material.extend_from_slice(value.as_bytes());
1230 material.push(0);
1231 }
1232 let identity = serde_json_canonicalizer::to_vec(self.descriptor.metadata().identity())
1233 .expect("validated capability identities have a canonical JSON representation");
1234 material.extend_from_slice(&identity);
1235 material.push(0);
1236 material.extend_from_slice(self.client.agent_card_digest().as_bytes());
1237 Some(format!(
1238 "stateknot-context-{}",
1239 digest_bytes_hex(Digest::sha256(material).as_bytes())
1240 ))
1241 }
1242
1243 fn probe_error(
1244 category: FailureCategory,
1245 code: &'static str,
1246 message: &'static str,
1247 retry: RetryAdvice,
1248 ) -> ToolReconciliationProbeError {
1249 let failure = Failure::new(
1250 FailureId::generate(),
1251 category,
1252 FailureCode::new(code).expect("A2A reconciliation failure code is valid"),
1253 FailureOrigin::new("protocol.a2a.reconciliation")
1254 .expect("A2A reconciliation failure origin is valid"),
1255 FailureMessage::new(message)
1256 .expect("A2A reconciliation public failure message is valid"),
1257 retry,
1258 )
1259 .expect("A2A reconciliation failure semantics are coherent");
1260 ToolReconciliationProbeError::new(failure)
1261 .expect("A2A reconciliation retry advice is bounded and non-recursive")
1262 }
1263
1264 fn invalid_probe_contract(
1265 code: &'static str,
1266 message: &'static str,
1267 ) -> ToolReconciliationProbeError {
1268 Self::probe_error(
1269 FailureCategory::DataCorruption,
1270 code,
1271 message,
1272 RetryAdvice::Never,
1273 )
1274 }
1275
1276 fn probe_client_error(&self, error: &A2aClientError) -> ToolReconciliationProbeError {
1277 if error.authorization_error() == Some(A2aClientAuthorizationError::PermissionDenied) {
1278 return Self::probe_error(
1279 FailureCategory::PermissionDenied,
1280 "authorization.permission_denied",
1281 "A2A reconciliation authorization was denied.",
1282 RetryAdvice::Never,
1283 );
1284 }
1285 if error.kind() == A2aClientErrorKind::Remote
1286 && definitive_rejection(error.remote_code()).is_some()
1287 {
1288 return Self::probe_error(
1289 FailureCategory::Unsupported,
1290 "probe.remote_operation_rejected",
1291 "The A2A agent rejected the configured reconciliation operation.",
1292 RetryAdvice::Never,
1293 );
1294 }
1295 match error.kind() {
1296 A2aClientErrorKind::Authorization | A2aClientErrorKind::Transport => Self::probe_error(
1297 FailureCategory::DependencyUnavailable,
1298 "probe.dependency_unavailable",
1299 "The A2A reconciliation dependency is temporarily unavailable.",
1300 RetryAdvice::SafeAfter {
1301 delay: self
1302 .recovery
1303 .retry_after()
1304 .expect("enabled reconciliation has a retry delay"),
1305 },
1306 ),
1307 A2aClientErrorKind::Remote => Self::probe_error(
1308 FailureCategory::DependencyUnavailable,
1309 "probe.remote_unavailable",
1310 "The A2A agent could not complete reconciliation.",
1311 RetryAdvice::SafeAfter {
1312 delay: self
1313 .recovery
1314 .retry_after()
1315 .expect("enabled reconciliation has a retry delay"),
1316 },
1317 ),
1318 A2aClientErrorKind::Request | A2aClientErrorKind::Capability => Self::probe_error(
1319 FailureCategory::Unsupported,
1320 "probe.operation_unsupported",
1321 "The pinned A2A reconciliation operation is unavailable.",
1322 RetryAdvice::Never,
1323 ),
1324 A2aClientErrorKind::HttpProtocol | A2aClientErrorKind::InvalidResponse => {
1325 Self::invalid_probe_contract(
1326 "probe.invalid_response",
1327 "The A2A reconciliation response violated the pinned protocol contract.",
1328 )
1329 }
1330 }
1331 }
1332
1333 fn validate_reconciliation_input(
1334 &self,
1335 context: &ToolReconciliationContext,
1336 input: &ToolInput,
1337 ) -> Result<(), ToolReconciliationProbeError> {
1338 if context.validate_for(&self.descriptor).is_err()
1339 || input.schema() != self.descriptor.input_schema()
1340 || u64::try_from(input.value().stats().compact_bytes()).unwrap_or(u64::MAX)
1341 > self.descriptor.limits().max_input_bytes().get()
1342 || self
1343 .schemas
1344 .validate(self.descriptor.input_schema(), input.value())
1345 .is_err()
1346 {
1347 return Err(Self::invalid_probe_contract(
1348 "probe.input_binding_invalid",
1349 "The durable A2A reconciliation input violated its pinned contract.",
1350 ));
1351 }
1352 Ok(())
1353 }
1354
1355 fn reconciled_result(
1356 &self,
1357 context: &ToolReconciliationContext,
1358 response: &A2aSendMessageResponse,
1359 ) -> Result<ToolResult, ToolReconciliationProbeError> {
1360 let value = response.to_json().map_err(|_| {
1361 Self::invalid_probe_contract(
1362 "probe.result_encoding_invalid",
1363 "The reconciled A2A result could not be encoded safely.",
1364 )
1365 })?;
1366 let output = BoundedJson::try_from_value(value).map_err(|_| {
1367 Self::invalid_probe_contract(
1368 "probe.result_limit_exceeded",
1369 "The reconciled A2A result exceeded bounded JSON limits.",
1370 )
1371 })?;
1372 self.schemas
1373 .validate(self.descriptor.output_schema(), &output)
1374 .map_err(|_| {
1375 Self::invalid_probe_contract(
1376 "probe.result_schema_invalid",
1377 "The reconciled A2A result violated its pinned output schema.",
1378 )
1379 })?;
1380 Ok(ToolResult::new(
1381 ToolResultProvenance::new(
1382 context.invocation_id(),
1383 context.attempt_id(),
1384 self.descriptor.metadata().identity().clone(),
1385 ),
1386 self.descriptor.output_schema().clone(),
1387 output,
1388 ToolArtifacts::empty(),
1389 ))
1390 }
1391
1392 #[allow(clippy::too_many_arguments)]
1393 fn reconciled_error(
1394 &self,
1395 context: &ToolReconciliationContext,
1396 phase: ToolErrorPhase,
1397 category: FailureCategory,
1398 code: &'static str,
1399 message: &'static str,
1400 ) -> ToolError {
1401 let failure = Failure::new(
1402 FailureId::generate(),
1403 category,
1404 FailureCode::new(code).expect("A2A reconciliation failure code is valid"),
1405 FailureOrigin::new("protocol.a2a").expect("A2A reconciliation failure origin is valid"),
1406 FailureMessage::new(message).expect("A2A reconciliation failure message is bounded"),
1407 RetryAdvice::Never,
1408 )
1409 .expect("A2A terminal reconciliation failure semantics are coherent");
1410 ToolError::new(
1411 failure,
1412 phase,
1413 ToolExternalEffect::Applied,
1414 ToolErrorProvenance::new(
1415 context.invocation_id(),
1416 context.attempt_id(),
1417 self.descriptor.metadata().identity().clone(),
1418 ),
1419 )
1420 .expect("terminal A2A reconciliation evidence has a valid shape")
1421 }
1422
1423 fn reconciled_terminal_task_error(
1424 &self,
1425 context: &ToolReconciliationContext,
1426 state: A2aTaskState,
1427 ) -> ToolError {
1428 let (category, code, message) = terminal_task_failure(state);
1429 self.reconciled_error(context, ToolErrorPhase::Execution, category, code, message)
1430 }
1431
1432 #[allow(clippy::too_many_lines)]
1433 async fn reconciled_observation(
1434 &self,
1435 context: &ToolReconciliationContext,
1436 response: &A2aSendMessageResponse,
1437 ) -> Result<ToolReconciliationObservation, ToolReconciliationProbeError> {
1438 if self.artifact_ingestor.is_none() {
1439 return self
1440 .reconciled_result(context, response)
1441 .map(ToolReconciliationObservation::Result);
1442 }
1443 let A2aSendMessageResponse::Task(task) = response else {
1444 return Ok(ToolReconciliationObservation::Error(self.reconciled_error(
1445 context,
1446 ToolErrorPhase::Result,
1447 FailureCategory::DataCorruption,
1448 "result.task_required",
1449 "The durable A2A binding received a direct message instead of a task.",
1450 )));
1451 };
1452 match task.state() {
1453 A2aTaskState::Completed => {
1454 let origin_event_id = context.origin_event_id().ok_or_else(|| {
1455 Self::invalid_probe_contract(
1456 "probe.origin_event_missing",
1457 "The durable A2A artifact origin is unavailable.",
1458 )
1459 })?;
1460 match self
1461 .durable_task_components(
1462 context.tenant_id(),
1463 context.run_id(),
1464 context.invocation_id(),
1465 context.attempt_id(),
1466 origin_event_id,
1467 context.max_inline_result_bytes(),
1468 context.max_artifacts(),
1469 context.max_total_artifact_bytes(),
1470 task,
1471 )
1472 .await
1473 {
1474 Ok((output, artifacts)) => {
1475 Ok(ToolReconciliationObservation::Result(ToolResult::new(
1476 ToolResultProvenance::new(
1477 context.invocation_id(),
1478 context.attempt_id(),
1479 self.descriptor.metadata().identity().clone(),
1480 ),
1481 self.descriptor.output_schema().clone(),
1482 output,
1483 artifacts,
1484 )))
1485 }
1486 Err(DurableTaskResultError::Invalid) => {
1487 Ok(ToolReconciliationObservation::Error(self.reconciled_error(
1488 context,
1489 ToolErrorPhase::Result,
1490 FailureCategory::DataCorruption,
1491 "result.invalid",
1492 "The A2A agent returned a result outside the pinned local contract.",
1493 )))
1494 }
1495 Err(DurableTaskResultError::Ingestion(error)) => match error.kind() {
1496 A2aArtifactIngestionErrorKind::Unavailable => Err(Self::probe_error(
1497 FailureCategory::DependencyUnavailable,
1498 "probe.artifact_store_unavailable",
1499 "The A2A artifact store is temporarily unavailable.",
1500 RetryAdvice::SafeAfter {
1501 delay: self
1502 .recovery
1503 .retry_after()
1504 .expect("durable artifact mode requires recovery"),
1505 },
1506 )),
1507 A2aArtifactIngestionErrorKind::PolicyDenied => {
1508 Ok(ToolReconciliationObservation::Error(self.reconciled_error(
1509 context,
1510 ToolErrorPhase::Result,
1511 FailureCategory::PermissionDenied,
1512 "artifact.policy_denied",
1513 "Local policy denied an A2A artifact.",
1514 )))
1515 }
1516 A2aArtifactIngestionErrorKind::InvalidContent
1517 | A2aArtifactIngestionErrorKind::Integrity => {
1518 Ok(ToolReconciliationObservation::Error(self.reconciled_error(
1519 context,
1520 ToolErrorPhase::Result,
1521 FailureCategory::DataCorruption,
1522 "artifact.integrity_invalid",
1523 "The A2A artifact failed local integrity validation.",
1524 )))
1525 }
1526 },
1527 }
1528 }
1529 state if state.is_terminal() => Ok(ToolReconciliationObservation::Error(
1530 self.reconciled_terminal_task_error(context, state),
1531 )),
1532 _ => ToolReconciliationObservation::pending(
1533 self.recovery
1534 .retry_after()
1535 .expect("durable artifact mode requires recovery"),
1536 )
1537 .map_err(|_| {
1538 Self::invalid_probe_contract(
1539 "probe.retry_delay_invalid",
1540 "The configured A2A reconciliation delay is invalid.",
1541 )
1542 }),
1543 }
1544 }
1545
1546 fn matching_message_occurrences(
1547 task: &A2aTask,
1548 expected_message: &A2aMessage,
1549 ) -> Result<usize, ToolReconciliationProbeError> {
1550 let task_bound_message = expected_message
1551 .clone()
1552 .with_task_id(task.id().to_owned())
1553 .map_err(|_| {
1554 Self::invalid_probe_contract(
1555 "probe.task_binding_invalid",
1556 "The A2A reconciliation task identity could not be validated.",
1557 )
1558 })?;
1559 let mut occurrences = 0_usize;
1560 for message in task
1561 .history()
1562 .iter()
1563 .filter(|message| message.message_id() == expected_message.message_id())
1564 {
1565 if message != expected_message && message != &task_bound_message {
1566 return Err(Self::invalid_probe_contract(
1567 "probe.message_mismatch",
1568 "The A2A task history changed the original message payload.",
1569 ));
1570 }
1571 occurrences += 1;
1572 }
1573 Ok(occurrences)
1574 }
1575
1576 async fn reconcile_context_task_history(
1577 &self,
1578 context: &ToolReconciliationContext,
1579 expected_message: &A2aMessage,
1580 context_id: String,
1581 maximum_pages: u8,
1582 history_length: u16,
1583 retry_after: DurationMillis,
1584 ) -> Result<ToolReconciliationObservation, ToolReconciliationProbeError> {
1585 let attempt = A2aClientAttemptIdentity::new(
1586 context.tenant_id().clone(),
1587 context.run_id(),
1588 context.invocation_id(),
1589 context.attempt_id(),
1590 );
1591 let mut page_token = None;
1592 let mut seen_tasks = HashSet::new();
1593 let mut matched_task: Option<A2aTask> = None;
1594 for page_index in 0..maximum_pages {
1595 let mut request = A2aListTasksRequest::new()
1596 .with_context_id(context_id.clone())
1597 .and_then(|request| request.with_page_size(A2aListTasksRequest::MAX_PAGE_SIZE))
1598 .and_then(|request| request.with_history_length(u32::from(history_length)))
1599 .map(|request| request.include_artifacts(true))
1600 .map_err(|_| {
1601 Self::invalid_probe_contract(
1602 "probe.request_invalid",
1603 "The bounded A2A reconciliation query could not be constructed.",
1604 )
1605 })?;
1606 if let Some(token) = page_token.take() {
1607 request = request.with_page_token(token).map_err(|_| {
1608 Self::invalid_probe_contract(
1609 "probe.cursor_invalid",
1610 "The A2A reconciliation cursor violated protocol bounds.",
1611 )
1612 })?;
1613 }
1614 let page = self
1615 .client
1616 .list_tasks_with_attempt(request, attempt.clone(), self.required_scopes.clone())
1617 .await
1618 .map_err(|error| self.probe_client_error(&error))?;
1619 for task in page.tasks() {
1620 if !seen_tasks.insert(task.id().to_owned()) {
1621 return Err(Self::invalid_probe_contract(
1622 "probe.duplicate_task",
1623 "The A2A stable task snapshot repeated a task identity.",
1624 ));
1625 }
1626 let occurrences = Self::matching_message_occurrences(task, expected_message)?;
1627 if occurrences > 1 || (occurrences == 1 && matched_task.is_some()) {
1628 return Err(Self::invalid_probe_contract(
1629 "probe.ambiguous_match",
1630 "More than one A2A task history matched the original message.",
1631 ));
1632 }
1633 if occurrences == 1 {
1634 matched_task = Some(task.clone());
1635 }
1636 }
1637 page_token = page.next_page_token().map(ToOwned::to_owned);
1638 if page_token.is_none() {
1639 return match matched_task {
1640 Some(task) => {
1641 let response = A2aSendMessageResponse::Task(task);
1642 self.reconciled_observation(context, &response).await
1643 }
1644 None => ToolReconciliationObservation::pending(retry_after).map_err(|_| {
1645 Self::invalid_probe_contract(
1646 "probe.retry_delay_invalid",
1647 "The configured A2A reconciliation delay is invalid.",
1648 )
1649 }),
1650 };
1651 }
1652 if page_index + 1 == maximum_pages {
1653 return Err(Self::probe_error(
1654 FailureCategory::RateLimited,
1655 "probe.scan_limit_exceeded",
1656 "The A2A task snapshot exceeds the configured reconciliation scan bound.",
1657 RetryAdvice::Never,
1658 ));
1659 }
1660 }
1661 Err(Self::invalid_probe_contract(
1662 "probe.scan_invariant",
1663 "The bounded A2A reconciliation scan ended unexpectedly.",
1664 ))
1665 }
1666
1667 #[allow(clippy::too_many_lines)]
1668 async fn reconcile_inner(
1669 &self,
1670 context: ToolReconciliationContext,
1671 input: ToolInput,
1672 ) -> Result<ToolReconciliationObservation, ToolReconciliationProbeError> {
1673 self.validate_reconciliation_input(&context, &input)?;
1674 if let Some(handle) = context.recovery_handle() {
1675 if self.artifact_ingestor.is_none()
1676 || handle.namespace().as_str() != A2A_TASK_RECOVERY_NAMESPACE
1677 || handle.binding() != self.client.agent_card_digest()
1678 {
1679 return Err(Self::invalid_probe_contract(
1680 "probe.recovery_handle_mismatch",
1681 "The durable A2A recovery handle does not match this binding.",
1682 ));
1683 }
1684 let request = A2aGetTaskRequest::new(handle.opaque_id().to_owned()).map_err(|_| {
1685 Self::invalid_probe_contract(
1686 "probe.recovery_handle_invalid",
1687 "The durable A2A recovery handle is not a valid task identity.",
1688 )
1689 })?;
1690 let attempt = A2aClientAttemptIdentity::new(
1691 context.tenant_id().clone(),
1692 context.run_id(),
1693 context.invocation_id(),
1694 context.attempt_id(),
1695 );
1696 let task = self
1697 .client
1698 .get_task_with_attempt(request, attempt, self.required_scopes.clone())
1699 .await
1700 .map_err(|error| self.probe_client_error(&error))?;
1701 if task.id() != handle.opaque_id() {
1702 return Err(Self::invalid_probe_contract(
1703 "probe.task_identity_mismatch",
1704 "The A2A task response substituted the requested identity.",
1705 ));
1706 }
1707 return self
1708 .reconciled_observation(&context, &A2aSendMessageResponse::Task(task))
1709 .await;
1710 }
1711 let message_id = self.reconciliation_message_id(&context).ok_or_else(|| {
1712 Self::invalid_probe_contract(
1713 "probe.idempotency_key_missing",
1714 "The original A2A message identity cannot be reconstructed.",
1715 )
1716 })?;
1717 match self.recovery.kind {
1718 A2aRemoteAgentRecoveryKind::Disabled => Err(Self::probe_error(
1719 FailureCategory::Unsupported,
1720 "probe.disabled",
1721 "Automated A2A reconciliation is disabled.",
1722 RetryAdvice::Never,
1723 )),
1724 A2aRemoteAgentRecoveryKind::ContextTaskHistory {
1725 maximum_pages,
1726 history_length,
1727 retry_after,
1728 } => {
1729 let context_id = self.reconciliation_context_id(&context).ok_or_else(|| {
1730 Self::invalid_probe_contract(
1731 "probe.context_missing",
1732 "The opaque A2A reconciliation context cannot be reconstructed.",
1733 )
1734 })?;
1735 let expected_request = self
1736 .request(message_id, Some(context_id.clone()), input.value())
1737 .map_err(|_| {
1738 Self::invalid_probe_contract(
1739 "probe.request_invalid",
1740 "The original A2A message cannot be reconstructed.",
1741 )
1742 })?;
1743 self.reconcile_context_task_history(
1744 &context,
1745 expected_request.message(),
1746 context_id,
1747 maximum_pages,
1748 history_length,
1749 retry_after,
1750 )
1751 .await
1752 }
1753 A2aRemoteAgentRecoveryKind::MessageIdReplay { .. } => {
1754 let request = self.request(message_id, None, input.value()).map_err(|_| {
1755 Self::invalid_probe_contract(
1756 "probe.request_invalid",
1757 "The original A2A request cannot be reconstructed.",
1758 )
1759 })?;
1760 let attempt = A2aClientAttemptIdentity::new(
1761 context.tenant_id().clone(),
1762 context.run_id(),
1763 context.invocation_id(),
1764 context.attempt_id(),
1765 );
1766 let response = self
1767 .client
1768 .send_message_with_attempt(
1769 request,
1770 attempt,
1771 self.required_scopes.clone(),
1772 Arc::new(AtomicBool::new(false)),
1773 )
1774 .await
1775 .map_err(|error| self.probe_client_error(&error))?;
1776 self.reconciled_observation(&context, &response).await
1777 }
1778 }
1779 }
1780
1781 fn client_error(&self, context: &ToolContext, error: &A2aClientError) -> ToolError {
1782 if !error.was_dispatched() {
1783 return match (error.kind(), error.authorization_error()) {
1784 (
1785 A2aClientErrorKind::Authorization,
1786 Some(A2aClientAuthorizationError::PermissionDenied),
1787 ) => self.preparation_error(
1788 context,
1789 FailureCategory::PermissionDenied,
1790 "authorization.permission_denied",
1791 "A2A authorization access was denied.",
1792 RetryAdvice::Never,
1793 ),
1794 (A2aClientErrorKind::Authorization, _) => self.preparation_error(
1795 context,
1796 FailureCategory::DependencyUnavailable,
1797 "authorization.unavailable",
1798 "The A2A authorization source is temporarily unavailable.",
1799 RetryAdvice::SafeAfter {
1800 delay: DurationMillis::new(250).expect("positive constant"),
1801 },
1802 ),
1803 (A2aClientErrorKind::Capability, _) => self.preparation_error(
1804 context,
1805 FailureCategory::Unsupported,
1806 "call.capability_unavailable",
1807 "The pinned A2A agent does not support this operation.",
1808 RetryAdvice::Never,
1809 ),
1810 (A2aClientErrorKind::Request, _) => self.preparation_error(
1811 context,
1812 FailureCategory::Internal,
1813 "request.encoding_failed",
1814 "The bounded A2A request could not be encoded.",
1815 RetryAdvice::Never,
1816 ),
1817 _ => self.preparation_error(
1818 context,
1819 FailureCategory::Internal,
1820 "call.failed_before_dispatch",
1821 "The A2A attempt failed before dispatch.",
1822 RetryAdvice::Never,
1823 ),
1824 };
1825 }
1826
1827 if error.kind() == A2aClientErrorKind::Remote {
1828 if let Some((category, code, message)) = definitive_rejection(error.remote_code()) {
1829 return self.rejected_error(context, category, code, message);
1830 }
1831 }
1832 self.unknown_outcome(context)
1833 }
1834
1835 fn stop_before_dispatch(&self, context: &ToolContext, reason: ToolStopReason) -> ToolError {
1836 let (category, code, message) = stop_failure(reason);
1837 self.preparation_error(context, category, code, message, RetryAdvice::Never)
1838 }
1839
1840 fn stop_after_dispatch(&self, context: &ToolContext, _reason: ToolStopReason) -> ToolError {
1841 self.unknown_outcome(context)
1842 }
1843}
1844
1845impl ErasedTool for A2aRemoteAgent {
1846 fn descriptor(&self) -> &ToolDescriptor {
1847 &self.descriptor
1848 }
1849
1850 fn supports_reconciliation(&self) -> bool {
1851 self.recovery.mode() != A2aRemoteAgentRecoveryMode::Disabled
1852 }
1853
1854 fn call(
1855 &self,
1856 context: ToolContext,
1857 input: ToolInput,
1858 ) -> BoxFuture<'_, Result<ToolResult, ToolError>> {
1859 Box::pin(self.call_inner(context, input))
1860 }
1861
1862 fn reconcile(
1863 &self,
1864 context: ToolReconciliationContext,
1865 input: ToolInput,
1866 ) -> BoxFuture<'_, Result<ToolReconciliationObservation, ToolReconciliationProbeError>> {
1867 Box::pin(self.reconcile_inner(context, input))
1868 }
1869}
1870
1871impl fmt::Debug for A2aRemoteAgent {
1872 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1873 formatter
1874 .debug_struct("A2aRemoteAgent")
1875 .field("descriptor", &self.descriptor)
1876 .field("skill_id", &self.skill_id)
1877 .field("delivery", &self.delivery)
1878 .field("recovery", &self.recovery.mode())
1879 .field("durable_artifacts", &self.artifact_ingestor.is_some())
1880 .field("client", &self.client)
1881 .finish_non_exhaustive()
1882 }
1883}
1884
1885fn validate_descriptor(
1886 descriptor: &ToolDescriptor,
1887 client: &A2aClient,
1888 delivery: A2aRemoteAgentDelivery,
1889 recovery: A2aRemoteAgentRecovery,
1890) -> Result<(), A2aRemoteAgentBuildError> {
1891 let semantics = descriptor.semantics();
1892 let valid_delivery = matches!(
1893 (delivery, semantics.risk(), semantics.idempotency()),
1894 (
1895 A2aRemoteAgentDelivery::AtMostOnce,
1896 ToolRisk::NonIdempotentWrite,
1897 ToolIdempotency::Unsupported
1898 ) | (
1899 A2aRemoteAgentDelivery::MessageIdDeduplicated,
1900 ToolRisk::IdempotentWrite,
1901 ToolIdempotency::RequiredKey
1902 )
1903 );
1904 if !valid_delivery {
1905 return Err(A2aRemoteAgentBuildError::DeliverySemanticsMismatch);
1906 }
1907 let recovery_enabled = recovery.mode() != A2aRemoteAgentRecoveryMode::Disabled;
1908 if semantics.supports_status_query() != recovery_enabled || semantics.supports_compensation() {
1909 return Err(A2aRemoteAgentBuildError::RecoveryOperationsUnsupported);
1910 }
1911 if recovery.mode() == A2aRemoteAgentRecoveryMode::MessageIdReplay
1912 && delivery != A2aRemoteAgentDelivery::MessageIdDeduplicated
1913 {
1914 return Err(A2aRemoteAgentBuildError::RecoveryDeliveryMismatch);
1915 }
1916 if descriptor.invocation().cancellation() != ToolCancellationSupport::Cooperative {
1917 return Err(A2aRemoteAgentBuildError::CancellationContractMismatch);
1918 }
1919 if descriptor.invocation().supports_progress_events() {
1920 return Err(A2aRemoteAgentBuildError::ProgressUnsupported);
1921 }
1922 let resources = descriptor.resources();
1923 if resources.network() != ToolResourceAccess::ReadWrite {
1924 return Err(A2aRemoteAgentBuildError::NetworkAccessMismatch);
1925 }
1926 if resources.filesystem() != ToolResourceAccess::None {
1927 return Err(A2aRemoteAgentBuildError::FilesystemAccessUnsupported);
1928 }
1929 if resources.executes_dynamic_code() {
1930 return Err(A2aRemoteAgentBuildError::DynamicCodeUnsupported);
1931 }
1932 if resources.requires_credentials() != client.requires_credentials() {
1933 return Err(A2aRemoteAgentBuildError::CredentialRequirementMismatch);
1934 }
1935 Ok(())
1936}
1937
1938fn accepts_json(value: &str) -> bool {
1939 value.parse::<mime::Mime>().is_ok_and(|mode| {
1940 let type_name = mode.type_().as_str();
1941 let subtype = mode.subtype().as_str();
1942 (type_name == "application" && matches!(subtype, "json" | "*"))
1943 || (type_name == "*" && subtype == "*")
1944 })
1945}
1946
1947fn digest_bytes_hex(bytes: &[u8]) -> String {
1948 const HEX: &[u8; 16] = b"0123456789abcdef";
1949 let mut value = String::with_capacity(bytes.len() * 2);
1950 for byte in bytes {
1951 value.push(char::from(HEX[usize::from(byte >> 4)]));
1952 value.push(char::from(HEX[usize::from(byte & 0x0f)]));
1953 }
1954 value
1955}
1956
1957fn definitive_rejection(
1958 code: Option<i32>,
1959) -> Option<(FailureCategory, &'static str, &'static str)> {
1960 match code? {
1961 a2a::error_code::PARSE_ERROR
1962 | a2a::error_code::INVALID_REQUEST
1963 | a2a::error_code::INVALID_PARAMS => Some((
1964 FailureCategory::InvalidInput,
1965 "call.remote_request_rejected",
1966 "The A2A agent rejected the request before applying it.",
1967 )),
1968 a2a::error_code::METHOD_NOT_FOUND
1969 | a2a::error_code::UNSUPPORTED_OPERATION
1970 | a2a::error_code::CONTENT_TYPE_NOT_SUPPORTED
1971 | a2a::error_code::EXTENSION_SUPPORT_REQUIRED
1972 | a2a::error_code::VERSION_NOT_SUPPORTED => Some((
1973 FailureCategory::Unsupported,
1974 "call.remote_operation_unsupported",
1975 "The A2A agent rejected the pinned protocol operation.",
1976 )),
1977 _ => None,
1978 }
1979}
1980
1981fn terminal_task_failure(state: A2aTaskState) -> (FailureCategory, &'static str, &'static str) {
1982 match state {
1983 A2aTaskState::Failed => (
1984 FailureCategory::Internal,
1985 "task.failed",
1986 "The A2A task completed with a failure.",
1987 ),
1988 A2aTaskState::Canceled => (
1989 FailureCategory::Cancelled,
1990 "task.canceled",
1991 "The A2A task was canceled.",
1992 ),
1993 A2aTaskState::Rejected => (
1994 FailureCategory::PermissionDenied,
1995 "task.rejected",
1996 "The A2A task was rejected.",
1997 ),
1998 _ => (
1999 FailureCategory::DataCorruption,
2000 "task.state_invalid",
2001 "The A2A task supplied an invalid terminal state.",
2002 ),
2003 }
2004}
2005
2006async fn wait_for_tool<T, F>(context: &ToolContext, future: F) -> Result<T, ToolStopReason>
2007where
2008 F: std::future::Future<Output = T>,
2009{
2010 if let Some(reason) = context.stop_reason_at(Instant::now()) {
2011 return Err(reason);
2012 }
2013 let deadline = tokio::time::Instant::from_std(context.deadline_instant());
2014 tokio::select! {
2015 biased;
2016 () = context.cancellation().cancelled() => Err(ToolStopReason::Cancelled),
2017 () = tokio::time::sleep_until(deadline) => {
2018 Err(context.stop_reason_at(Instant::now()).unwrap_or(ToolStopReason::DeadlineExceeded))
2019 }
2020 output = future => Ok(output),
2021 }
2022}
2023
2024const fn stop_failure(reason: ToolStopReason) -> (FailureCategory, &'static str, &'static str) {
2025 match reason {
2026 ToolStopReason::Cancelled => (
2027 FailureCategory::Cancelled,
2028 "call.cancelled",
2029 "The A2A attempt was cancelled before dispatch.",
2030 ),
2031 ToolStopReason::DeadlineExceeded => (
2032 FailureCategory::DeadlineExceeded,
2033 "call.deadline_exceeded",
2034 "The A2A attempt deadline elapsed before dispatch.",
2035 ),
2036 _ => (
2037 FailureCategory::Internal,
2038 "call.unknown_stop_reason",
2039 "The A2A attempt stopped for an unsupported reason.",
2040 ),
2041 }
2042}
2043
2044#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
2046#[non_exhaustive]
2047pub enum A2aRemoteAgentBuildError {
2048 #[error("A2A delivery assertion does not match descriptor semantics")]
2050 DeliverySemanticsMismatch,
2051 #[error("A2A remote-agent recovery policy does not match descriptor semantics")]
2054 RecoveryOperationsUnsupported,
2055 #[error("A2A message replay recovery requires message-ID-deduplicated delivery")]
2057 RecoveryDeliveryMismatch,
2058 #[error("durable A2A artifacts require an enabled recovery mode")]
2061 DurableArtifactsRequireRecovery,
2062 #[error("durable A2A artifacts require positive descriptor artifact capacity")]
2065 ArtifactCapacityRequired,
2066 #[error("A2A remote-agent binding requires cooperative cancellation semantics")]
2068 CancellationContractMismatch,
2069 #[error("A2A remote-agent binding does not support declared progress events")]
2071 ProgressUnsupported,
2072 #[error("A2A remote-agent binding requires read/write network access")]
2074 NetworkAccessMismatch,
2075 #[error("A2A remote-agent binding does not support filesystem access")]
2077 FilesystemAccessUnsupported,
2078 #[error("A2A remote-agent binding does not support dynamic code execution")]
2080 DynamicCodeUnsupported,
2081 #[error("A2A descriptor credential requirement does not match client security")]
2083 CredentialRequirementMismatch,
2084 #[error("A2A input schema is unavailable in the local registry")]
2086 InputSchemaUnavailable,
2087 #[error("A2A output schema is unavailable in the local registry")]
2089 OutputSchemaUnavailable,
2090 #[error("A2A skill is unavailable in the frozen Agent Card")]
2092 SkillUnavailable,
2093 #[error("A2A skill does not advertise a compatible JSON input mode")]
2095 JsonInputModeUnsupported,
2096 #[error("A2A skill does not advertise an output mode")]
2098 OutputModesUnavailable,
2099 #[error(transparent)]
2101 SkillSecurity(#[from] A2aClientSecurityError),
2102}
2103
2104#[cfg(test)]
2105mod tests {
2106 use super::*;
2107
2108 #[test]
2109 fn json_mode_matching_is_deliberately_narrow() {
2110 for accepted in ["application/json", "application/*", "*/*"] {
2111 assert!(accepts_json(accepted), "expected {accepted} to accept JSON");
2112 }
2113 for rejected in [
2114 "text/plain",
2115 "application/problem+json",
2116 "application/json invalid",
2117 "",
2118 ] {
2119 assert!(
2120 !accepts_json(rejected),
2121 "expected {rejected} to reject the exact JSON data-part mapping"
2122 );
2123 }
2124 }
2125
2126 #[test]
2127 fn only_pre_execution_protocol_rejections_prove_not_applied() {
2128 assert!(definitive_rejection(Some(a2a::error_code::INVALID_PARAMS)).is_some());
2129 assert!(definitive_rejection(Some(a2a::error_code::CONTENT_TYPE_NOT_SUPPORTED)).is_some());
2130 assert!(definitive_rejection(Some(a2a::error_code::INTERNAL_ERROR)).is_none());
2131 assert!(definitive_rejection(Some(a2a::error_code::INVALID_AGENT_RESPONSE)).is_none());
2132 assert!(definitive_rejection(None).is_none());
2133 }
2134
2135 #[test]
2136 fn recovery_attestations_enforce_bounded_polling_and_scan_work() {
2137 assert_eq!(
2138 A2aRemoteAgentRecovery::operator_attested_context_task_history(
2139 0,
2140 1,
2141 DurationMillis::new(250).unwrap(),
2142 )
2143 .unwrap_err(),
2144 A2aRemoteAgentRecoveryError::InvalidMaximumPages
2145 );
2146 assert_eq!(
2147 A2aRemoteAgentRecovery::operator_attested_context_task_history(
2148 1,
2149 0,
2150 DurationMillis::new(250).unwrap(),
2151 )
2152 .unwrap_err(),
2153 A2aRemoteAgentRecoveryError::InvalidHistoryLength
2154 );
2155 assert!(matches!(
2156 A2aRemoteAgentRecovery::operator_attested_message_id_replay(DurationMillis::ZERO),
2157 Err(A2aRemoteAgentRecoveryError::InvalidRetryDelay { .. })
2158 ));
2159 assert_eq!(
2160 A2aRemoteAgentRecovery::operator_attested_context_task_history(
2161 2,
2162 32,
2163 DurationMillis::new(250).unwrap(),
2164 )
2165 .unwrap()
2166 .mode(),
2167 A2aRemoteAgentRecoveryMode::ContextTaskHistory
2168 );
2169 }
2170}