Skip to main content

stateknot_integrations/
a2a_contract.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded StateKnot-owned contracts for the A2A 1.0 adapter.
5//!
6//! The official SDK structs are deliberately private to the adapter. These
7//! wrappers validate every inbound and outbound value, keep credentials out of
8//! `Debug`, and prevent a wire dependency from becoming `StateKnot`'s domain API.
9
10use std::{
11    collections::{HashMap, HashSet},
12    fmt,
13};
14
15use a2a as wire;
16use chrono::{DateTime, Utc};
17use serde_json::Value;
18use thiserror::Error;
19use zeroize::Zeroizing;
20
21/// A2A protocol version implemented by this profile.
22pub const A2A_PROTOCOL_VERSION_1_0: &str = "1.0";
23
24/// HTTP+JSON protocol-binding identifier used in Agent Cards.
25pub const A2A_BINDING_HTTP_JSON: &str = "HTTP+JSON";
26
27/// JSON-RPC protocol-binding identifier used in Agent Cards.
28pub const A2A_BINDING_JSONRPC: &str = "JSONRPC";
29
30/// Standard public Agent Card discovery path.
31pub const A2A_AGENT_CARD_PATH: &str = "/.well-known/agent-card.json";
32
33const MAX_ID_BYTES: usize = 512;
34const MAX_LABEL_BYTES: usize = 512;
35const MAX_DESCRIPTION_BYTES: usize = 16 * 1024;
36const MAX_URL_BYTES: usize = 4096;
37const MAX_MODE_BYTES: usize = 256;
38const MAX_PARTS: usize = 128;
39const MAX_PART_BYTES: usize = 1024 * 1024;
40const MAX_METADATA_BYTES: usize = 256 * 1024;
41const MAX_METADATA_ENTRIES: usize = 256;
42const MAX_MESSAGES: usize = 256;
43const MAX_ARTIFACTS: usize = 128;
44const MAX_EXTENSIONS: usize = 64;
45const MAX_REFERENCE_TASKS: usize = 128;
46const MAX_SKILLS: usize = 256;
47const MAX_INTERFACES: usize = 16;
48const MAX_MODES: usize = 64;
49const MAX_TAGS: usize = 64;
50const MAX_EXAMPLES: usize = 64;
51const MAX_SECURITY_SCHEMES: usize = 64;
52const MAX_SECURITY_REQUIREMENTS: usize = 64;
53const MAX_SCOPES: usize = 128;
54const MAX_SECRET_BYTES: usize = 16 * 1024;
55
56/// Invalid or unbounded A2A contract data.
57#[derive(Debug, Error)]
58#[non_exhaustive]
59pub enum A2aContractError {
60    /// A required value was absent.
61    #[error("A2A {field} must not be empty")]
62    Empty {
63        /// Stable field label.
64        field: &'static str,
65    },
66    /// A bounded collection exceeded its hard ceiling.
67    #[error("A2A {field} has {actual} entries; maximum is {maximum}")]
68    TooMany {
69        /// Stable field label.
70        field: &'static str,
71        /// Maximum accepted count.
72        maximum: usize,
73        /// Observed count.
74        actual: usize,
75    },
76    /// A string or encoded JSON value exceeded its hard byte ceiling.
77    #[error("A2A {field} is {actual} bytes; maximum is {maximum}")]
78    TooLarge {
79        /// Stable field label.
80        field: &'static str,
81        /// Maximum accepted byte length.
82        maximum: usize,
83        /// Observed byte length.
84        actual: usize,
85    },
86    /// Text contained boundary whitespace or control characters.
87    #[error("A2A {field} contains invalid text")]
88    InvalidText {
89        /// Stable field label.
90        field: &'static str,
91    },
92    /// A protocol identifier or enum value is unsupported.
93    #[error("unsupported A2A {field}: {value}")]
94    Unsupported {
95        /// Stable field label.
96        field: &'static str,
97        /// Public-safe rejected value.
98        value: String,
99    },
100    /// A URL is malformed or violates a contract-level rule.
101    #[error("invalid A2A {field} URL")]
102    InvalidUrl {
103        /// Stable field label.
104        field: &'static str,
105    },
106    /// JSON could not be encoded within the contract boundary.
107    #[error("invalid A2A {field} JSON")]
108    InvalidJson {
109        /// Stable field label.
110        field: &'static str,
111    },
112    /// A task or stream value violates a lifecycle invariant.
113    #[error("invalid A2A lifecycle: {0}")]
114    InvalidLifecycle(&'static str),
115    /// A response union had no valid member.
116    #[error("invalid A2A union: {0}")]
117    InvalidUnion(&'static str),
118}
119
120fn validate_required_text(
121    field: &'static str,
122    value: &str,
123    maximum: usize,
124) -> Result<(), A2aContractError> {
125    if value.is_empty() {
126        return Err(A2aContractError::Empty { field });
127    }
128    if value.len() > maximum {
129        return Err(A2aContractError::TooLarge {
130            field,
131            maximum,
132            actual: value.len(),
133        });
134    }
135    if value.trim() != value || value.chars().any(char::is_control) {
136        return Err(A2aContractError::InvalidText { field });
137    }
138    Ok(())
139}
140
141fn validate_optional_text(
142    field: &'static str,
143    value: Option<&str>,
144    maximum: usize,
145) -> Result<(), A2aContractError> {
146    if let Some(value) = value {
147        validate_required_text(field, value, maximum)?;
148    }
149    Ok(())
150}
151
152fn validate_count(
153    field: &'static str,
154    actual: usize,
155    maximum: usize,
156) -> Result<(), A2aContractError> {
157    if actual > maximum {
158        return Err(A2aContractError::TooMany {
159            field,
160            maximum,
161            actual,
162        });
163    }
164    Ok(())
165}
166
167fn validate_json(
168    field: &'static str,
169    value: &Value,
170    maximum: usize,
171) -> Result<(), A2aContractError> {
172    let bytes = serde_json::to_vec(value).map_err(|_| A2aContractError::InvalidJson { field })?;
173    if bytes.len() > maximum {
174        return Err(A2aContractError::TooLarge {
175            field,
176            maximum,
177            actual: bytes.len(),
178        });
179    }
180    Ok(())
181}
182
183fn validate_metadata(
184    field: &'static str,
185    metadata: Option<&HashMap<String, Value>>,
186) -> Result<(), A2aContractError> {
187    let Some(metadata) = metadata else {
188        return Ok(());
189    };
190    validate_count(field, metadata.len(), MAX_METADATA_ENTRIES)?;
191    for key in metadata.keys() {
192        validate_required_text(field, key, MAX_LABEL_BYTES)?;
193    }
194    validate_json(
195        field,
196        &serde_json::to_value(metadata).map_err(|_| A2aContractError::InvalidJson { field })?,
197        MAX_METADATA_BYTES,
198    )
199}
200
201fn validate_url(field: &'static str, value: &str) -> Result<(), A2aContractError> {
202    validate_required_text(field, value, MAX_URL_BYTES)?;
203    let parsed = reqwest::Url::parse(value).map_err(|_| A2aContractError::InvalidUrl { field })?;
204    if parsed.host_str().is_none() || parsed.username() != "" || parsed.password().is_some() {
205        return Err(A2aContractError::InvalidUrl { field });
206    }
207    Ok(())
208}
209
210/// Secret A2A material that is zeroized and never formatted in plaintext.
211#[derive(Clone, PartialEq)]
212pub struct A2aSecret(Zeroizing<String>);
213
214impl A2aSecret {
215    /// Constructs bounded, non-empty secret material.
216    pub fn new(value: impl Into<String>) -> Result<Self, A2aContractError> {
217        let value = Zeroizing::new(value.into());
218        if value.is_empty() {
219            return Err(A2aContractError::Empty { field: "secret" });
220        }
221        if value.len() > MAX_SECRET_BYTES {
222            return Err(A2aContractError::TooLarge {
223                field: "secret",
224                maximum: MAX_SECRET_BYTES,
225                actual: value.len(),
226            });
227        }
228        if value.chars().any(char::is_control) {
229            return Err(A2aContractError::InvalidText { field: "secret" });
230        }
231        Ok(Self(value))
232    }
233
234    /// Borrows the secret for immediate credential verification or encryption.
235    #[must_use]
236    pub fn expose_secret(&self) -> &str {
237        self.0.as_str()
238    }
239}
240
241impl fmt::Debug for A2aSecret {
242    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
243        formatter.write_str("A2aSecret([REDACTED])")
244    }
245}
246
247/// Directional role of an A2A message.
248#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
249#[non_exhaustive]
250pub enum A2aMessageRole {
251    /// Message sent by the calling agent or user side.
252    User,
253    /// Message sent by the serving agent side.
254    Agent,
255}
256
257impl From<A2aMessageRole> for wire::Role {
258    fn from(value: A2aMessageRole) -> Self {
259        match value {
260            A2aMessageRole::User => Self::User,
261            A2aMessageRole::Agent => Self::Agent,
262        }
263    }
264}
265
266impl TryFrom<wire::Role> for A2aMessageRole {
267    type Error = A2aContractError;
268
269    fn try_from(value: wire::Role) -> Result<Self, Self::Error> {
270        match value {
271            wire::Role::User => Ok(Self::User),
272            wire::Role::Agent => Ok(Self::Agent),
273            wire::Role::Unspecified => Err(A2aContractError::Unsupported {
274                field: "message role",
275                value: "ROLE_UNSPECIFIED".to_string(),
276            }),
277        }
278    }
279}
280
281/// Borrowed content view for an A2A part.
282#[derive(Clone, Copy, Debug)]
283#[non_exhaustive]
284pub enum A2aPartContent<'a> {
285    /// UTF-8 text.
286    Text(&'a str),
287    /// Structured JSON data.
288    Data(&'a Value),
289    /// Inline decoded bytes.
290    Raw(&'a [u8]),
291    /// External resource URL.
292    Url(&'a str),
293}
294
295/// Borrowed, allocation-free view of a bounded A2A content part.
296///
297/// Services use this view to enforce media and egress policy without cloning
298/// potentially large inline payloads or depending on the upstream SDK model.
299#[derive(Clone, Copy, Debug)]
300pub struct A2aPartRef<'a> {
301    inner: &'a wire::Part,
302}
303
304impl<'a> A2aPartRef<'a> {
305    /// Returns the content variant without exposing SDK types.
306    #[must_use]
307    pub fn content(self) -> A2aPartContent<'a> {
308        match &self.inner.content {
309            wire::PartContent::Text(value) => A2aPartContent::Text(value),
310            wire::PartContent::Data(value) => A2aPartContent::Data(value),
311            wire::PartContent::Raw(value) => A2aPartContent::Raw(value),
312            wire::PartContent::Url(value) => A2aPartContent::Url(value),
313        }
314    }
315
316    /// Returns the optional display filename.
317    #[must_use]
318    pub fn filename(self) -> Option<&'a str> {
319        self.inner.filename.as_deref()
320    }
321
322    /// Returns the optional media type.
323    #[must_use]
324    pub fn media_type(self) -> Option<&'a str> {
325        self.inner.media_type.as_deref()
326    }
327
328    /// Returns untrusted protocol metadata.
329    #[must_use]
330    pub const fn metadata(self) -> Option<&'a HashMap<String, Value>> {
331        self.inner.metadata.as_ref()
332    }
333
334    /// Clones this already validated part for an asynchronous ingestion job.
335    #[must_use]
336    pub fn to_owned(self) -> A2aPart {
337        A2aPart {
338            inner: self.inner.clone(),
339        }
340    }
341}
342
343/// A bounded A2A content part.
344#[derive(Clone, Debug, PartialEq)]
345pub struct A2aPart {
346    inner: wire::Part,
347}
348
349impl A2aPart {
350    /// Creates a text part.
351    pub fn text(value: impl Into<String>) -> Result<Self, A2aContractError> {
352        let value = value.into();
353        if value.len() > MAX_PART_BYTES {
354            return Err(A2aContractError::TooLarge {
355                field: "part text",
356                maximum: MAX_PART_BYTES,
357                actual: value.len(),
358            });
359        }
360        Ok(Self {
361            inner: wire::Part::text(value),
362        })
363    }
364
365    /// Creates a structured-data part.
366    pub fn data(value: Value) -> Result<Self, A2aContractError> {
367        validate_json("part data", &value, MAX_PART_BYTES)?;
368        Ok(Self {
369            inner: wire::Part::data(value),
370        })
371    }
372
373    /// Creates an inline binary part.
374    ///
375    /// Server ingress should normally materialize this through the artifact
376    /// registry before constructing trusted core content.
377    pub fn raw(value: Vec<u8>) -> Result<Self, A2aContractError> {
378        if value.len() > MAX_PART_BYTES {
379            return Err(A2aContractError::TooLarge {
380                field: "part raw bytes",
381                maximum: MAX_PART_BYTES,
382                actual: value.len(),
383            });
384        }
385        Ok(Self {
386            inner: wire::Part::raw(value),
387        })
388    }
389
390    /// Creates an external URL part.
391    ///
392    /// Constructing this value does not fetch or trust the URL. Callers must
393    /// pass it through the configured egress and artifact-ingestion boundary.
394    pub fn url(value: impl Into<String>) -> Result<Self, A2aContractError> {
395        let value = value.into();
396        validate_url("part", &value)?;
397        Ok(Self {
398            inner: wire::Part::url(value),
399        })
400    }
401
402    /// Adds a validated media type.
403    pub fn with_media_type(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
404        let value = value.into();
405        validate_required_text("part media type", &value, MAX_MODE_BYTES)?;
406        value
407            .parse::<mime::Mime>()
408            .map_err(|_| A2aContractError::InvalidText {
409                field: "part media type",
410            })?;
411        self.inner.media_type = Some(value);
412        Ok(self)
413    }
414
415    /// Adds a bounded display filename.
416    pub fn with_filename(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
417        let value = value.into();
418        validate_required_text("part filename", &value, MAX_LABEL_BYTES)?;
419        self.inner.filename = Some(value);
420        Ok(self)
421    }
422
423    /// Adds bounded protocol metadata.
424    pub fn with_metadata(
425        mut self,
426        value: HashMap<String, Value>,
427    ) -> Result<Self, A2aContractError> {
428        validate_metadata("part metadata", Some(&value))?;
429        self.inner.metadata = Some(value);
430        Ok(self)
431    }
432
433    /// Returns the content variant without exposing SDK types.
434    #[must_use]
435    pub fn content(&self) -> A2aPartContent<'_> {
436        match &self.inner.content {
437            wire::PartContent::Text(value) => A2aPartContent::Text(value),
438            wire::PartContent::Data(value) => A2aPartContent::Data(value),
439            wire::PartContent::Raw(value) => A2aPartContent::Raw(value),
440            wire::PartContent::Url(value) => A2aPartContent::Url(value),
441        }
442    }
443
444    /// Returns the optional filename.
445    #[must_use]
446    pub fn filename(&self) -> Option<&str> {
447        self.inner.filename.as_deref()
448    }
449
450    /// Returns the optional media type.
451    #[must_use]
452    pub fn media_type(&self) -> Option<&str> {
453        self.inner.media_type.as_deref()
454    }
455
456    /// Returns untrusted protocol metadata.
457    #[must_use]
458    pub const fn metadata(&self) -> Option<&HashMap<String, Value>> {
459        self.inner.metadata.as_ref()
460    }
461
462    pub(crate) fn try_from_wire(inner: wire::Part) -> Result<Self, A2aContractError> {
463        match &inner.content {
464            wire::PartContent::Text(value) if value.len() > MAX_PART_BYTES => {
465                return Err(A2aContractError::TooLarge {
466                    field: "part text",
467                    maximum: MAX_PART_BYTES,
468                    actual: value.len(),
469                });
470            }
471            wire::PartContent::Data(value) => validate_json("part data", value, MAX_PART_BYTES)?,
472            wire::PartContent::Raw(value) if value.len() > MAX_PART_BYTES => {
473                return Err(A2aContractError::TooLarge {
474                    field: "part raw bytes",
475                    maximum: MAX_PART_BYTES,
476                    actual: value.len(),
477                });
478            }
479            wire::PartContent::Url(value) => validate_url("part", value)?,
480            _ => {}
481        }
482        validate_optional_text("part filename", inner.filename.as_deref(), MAX_LABEL_BYTES)?;
483        validate_optional_text(
484            "part media type",
485            inner.media_type.as_deref(),
486            MAX_MODE_BYTES,
487        )?;
488        if let Some(media_type) = inner.media_type.as_deref() {
489            media_type
490                .parse::<mime::Mime>()
491                .map_err(|_| A2aContractError::InvalidText {
492                    field: "part media type",
493                })?;
494        }
495        validate_metadata("part metadata", inner.metadata.as_ref())?;
496        Ok(Self { inner })
497    }
498
499    pub(crate) fn into_wire(self) -> wire::Part {
500        self.inner
501    }
502}
503
504/// A bounded A2A message.
505#[derive(Clone, Debug, PartialEq)]
506pub struct A2aMessage {
507    inner: wire::Message,
508}
509
510impl A2aMessage {
511    /// Constructs a message with a sender-generated stable identifier.
512    pub fn new(
513        message_id: impl Into<String>,
514        role: A2aMessageRole,
515        parts: Vec<A2aPart>,
516    ) -> Result<Self, A2aContractError> {
517        let message_id = message_id.into();
518        validate_required_text("message id", &message_id, MAX_ID_BYTES)?;
519        if parts.is_empty() {
520            return Err(A2aContractError::Empty {
521                field: "message parts",
522            });
523        }
524        validate_count("message parts", parts.len(), MAX_PARTS)?;
525        Ok(Self {
526            inner: wire::Message {
527                message_id,
528                context_id: None,
529                task_id: None,
530                role: role.into(),
531                parts: parts.into_iter().map(A2aPart::into_wire).collect(),
532                metadata: None,
533                extensions: None,
534                reference_task_ids: None,
535            },
536        })
537    }
538
539    /// Binds the message to an A2A context.
540    pub fn with_context_id(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
541        let value = value.into();
542        validate_required_text("context id", &value, MAX_ID_BYTES)?;
543        self.inner.context_id = Some(value);
544        Ok(self)
545    }
546
547    /// Binds the message to an A2A task.
548    pub fn with_task_id(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
549        let value = value.into();
550        validate_required_text("task id", &value, MAX_ID_BYTES)?;
551        self.inner.task_id = Some(value);
552        Ok(self)
553    }
554
555    /// Adds bounded message metadata.
556    pub fn with_metadata(
557        mut self,
558        value: HashMap<String, Value>,
559    ) -> Result<Self, A2aContractError> {
560        validate_metadata("message metadata", Some(&value))?;
561        self.inner.metadata = Some(value);
562        Ok(self)
563    }
564
565    /// Adds negotiated extension URIs.
566    pub fn with_extensions(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
567        validate_string_list("message extensions", &values, MAX_EXTENSIONS, MAX_URL_BYTES)?;
568        for value in &values {
569            validate_url("message extension", value)?;
570        }
571        self.inner.extensions = Some(values);
572        Ok(self)
573    }
574
575    /// Adds related task identifiers.
576    pub fn with_reference_task_ids(
577        mut self,
578        values: Vec<String>,
579    ) -> Result<Self, A2aContractError> {
580        validate_string_list(
581            "reference task ids",
582            &values,
583            MAX_REFERENCE_TASKS,
584            MAX_ID_BYTES,
585        )?;
586        self.inner.reference_task_ids = Some(values);
587        Ok(self)
588    }
589
590    /// Returns the stable sender-generated message identifier.
591    #[must_use]
592    pub fn message_id(&self) -> &str {
593        &self.inner.message_id
594    }
595
596    /// Returns the context identifier when present.
597    #[must_use]
598    pub fn context_id(&self) -> Option<&str> {
599        self.inner.context_id.as_deref()
600    }
601
602    /// Returns the task identifier when present.
603    #[must_use]
604    pub fn task_id(&self) -> Option<&str> {
605        self.inner.task_id.as_deref()
606    }
607
608    /// Returns the directional message role.
609    #[must_use]
610    pub fn role(&self) -> A2aMessageRole {
611        match self.inner.role {
612            wire::Role::User => A2aMessageRole::User,
613            wire::Role::Agent | wire::Role::Unspecified => A2aMessageRole::Agent,
614        }
615    }
616
617    /// Iterates allocation-free borrowed views of the content parts.
618    pub fn parts(&self) -> impl ExactSizeIterator<Item = A2aPartRef<'_>> {
619        self.inner.parts.iter().map(|inner| A2aPartRef { inner })
620    }
621
622    /// Returns untrusted protocol metadata.
623    #[must_use]
624    pub const fn metadata(&self) -> Option<&HashMap<String, Value>> {
625        self.inner.metadata.as_ref()
626    }
627
628    /// Returns negotiated extension URIs.
629    pub fn extensions(&self) -> impl ExactSizeIterator<Item = &str> {
630        self.inner
631            .extensions
632            .as_deref()
633            .unwrap_or_default()
634            .iter()
635            .map(String::as_str)
636    }
637
638    /// Returns related task identifiers.
639    pub fn reference_task_ids(&self) -> impl ExactSizeIterator<Item = &str> {
640        self.inner
641            .reference_task_ids
642            .as_deref()
643            .unwrap_or_default()
644            .iter()
645            .map(String::as_str)
646    }
647
648    pub(crate) fn try_from_wire(inner: wire::Message) -> Result<Self, A2aContractError> {
649        validate_required_text("message id", &inner.message_id, MAX_ID_BYTES)?;
650        validate_optional_text("context id", inner.context_id.as_deref(), MAX_ID_BYTES)?;
651        validate_optional_text("task id", inner.task_id.as_deref(), MAX_ID_BYTES)?;
652        A2aMessageRole::try_from(inner.role.clone())?;
653        if inner.parts.is_empty() {
654            return Err(A2aContractError::Empty {
655                field: "message parts",
656            });
657        }
658        validate_count("message parts", inner.parts.len(), MAX_PARTS)?;
659        for part in inner.parts.iter().cloned() {
660            A2aPart::try_from_wire(part)?;
661        }
662        validate_metadata("message metadata", inner.metadata.as_ref())?;
663        if let Some(extensions) = inner.extensions.as_ref() {
664            validate_string_list(
665                "message extensions",
666                extensions,
667                MAX_EXTENSIONS,
668                MAX_URL_BYTES,
669            )?;
670            for extension in extensions {
671                validate_url("message extension", extension)?;
672            }
673        }
674        if let Some(references) = inner.reference_task_ids.as_ref() {
675            validate_string_list(
676                "reference task ids",
677                references,
678                MAX_REFERENCE_TASKS,
679                MAX_ID_BYTES,
680            )?;
681        }
682        Ok(Self { inner })
683    }
684
685    pub(crate) fn into_wire(self) -> wire::Message {
686        self.inner
687    }
688}
689
690fn validate_string_list(
691    field: &'static str,
692    values: &[String],
693    maximum_count: usize,
694    maximum_bytes: usize,
695) -> Result<(), A2aContractError> {
696    validate_count(field, values.len(), maximum_count)?;
697    for value in values {
698        validate_required_text(field, value, maximum_bytes)?;
699    }
700    Ok(())
701}
702
703/// A2A task state, kept separate from `StateKnot` run lifecycle states.
704#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
705#[non_exhaustive]
706pub enum A2aTaskState {
707    /// Accepted but not yet executing.
708    Submitted,
709    /// Actively executing.
710    Working,
711    /// Successfully completed.
712    Completed,
713    /// Failed terminally.
714    Failed,
715    /// Confirmed canceled.
716    Canceled,
717    /// Waiting for caller input.
718    InputRequired,
719    /// Rejected terminally.
720    Rejected,
721    /// Waiting for out-of-band authorization.
722    AuthRequired,
723}
724
725impl A2aTaskState {
726    /// Returns whether no later task state is permitted.
727    #[must_use]
728    pub const fn is_terminal(self) -> bool {
729        matches!(
730            self,
731            Self::Completed | Self::Failed | Self::Canceled | Self::Rejected
732        )
733    }
734}
735
736impl From<A2aTaskState> for wire::TaskState {
737    fn from(value: A2aTaskState) -> Self {
738        match value {
739            A2aTaskState::Submitted => Self::Submitted,
740            A2aTaskState::Working => Self::Working,
741            A2aTaskState::Completed => Self::Completed,
742            A2aTaskState::Failed => Self::Failed,
743            A2aTaskState::Canceled => Self::Canceled,
744            A2aTaskState::InputRequired => Self::InputRequired,
745            A2aTaskState::Rejected => Self::Rejected,
746            A2aTaskState::AuthRequired => Self::AuthRequired,
747        }
748    }
749}
750
751impl TryFrom<wire::TaskState> for A2aTaskState {
752    type Error = A2aContractError;
753
754    fn try_from(value: wire::TaskState) -> Result<Self, Self::Error> {
755        match value {
756            wire::TaskState::Submitted => Ok(Self::Submitted),
757            wire::TaskState::Working => Ok(Self::Working),
758            wire::TaskState::Completed => Ok(Self::Completed),
759            wire::TaskState::Failed => Ok(Self::Failed),
760            wire::TaskState::Canceled => Ok(Self::Canceled),
761            wire::TaskState::InputRequired => Ok(Self::InputRequired),
762            wire::TaskState::Rejected => Ok(Self::Rejected),
763            wire::TaskState::AuthRequired => Ok(Self::AuthRequired),
764            wire::TaskState::Unspecified => Err(A2aContractError::Unsupported {
765                field: "task state",
766                value: "TASK_STATE_UNSPECIFIED".to_string(),
767            }),
768        }
769    }
770}
771
772/// Status snapshot for an A2A task.
773#[derive(Clone, Debug, PartialEq)]
774pub struct A2aTaskStatus {
775    inner: wire::TaskStatus,
776}
777
778impl A2aTaskStatus {
779    /// Constructs a status snapshot.
780    pub fn new(
781        state: A2aTaskState,
782        message: Option<A2aMessage>,
783        timestamp: Option<DateTime<Utc>>,
784    ) -> Result<Self, A2aContractError> {
785        if matches!(state, A2aTaskState::AuthRequired) && message.is_none() {
786            return Err(A2aContractError::InvalidLifecycle(
787                "auth-required status needs an explanatory message",
788            ));
789        }
790        Ok(Self {
791            inner: wire::TaskStatus {
792                state: state.into(),
793                message: message.map(A2aMessage::into_wire),
794                timestamp,
795            },
796        })
797    }
798
799    /// Returns the A2A state.
800    #[must_use]
801    pub fn state(&self) -> A2aTaskState {
802        A2aTaskState::try_from(self.inner.state.clone())
803            .expect("A2aTaskStatus construction validates task state")
804    }
805
806    /// Returns the optional status timestamp.
807    #[must_use]
808    pub const fn timestamp(&self) -> Option<DateTime<Utc>> {
809        self.inner.timestamp
810    }
811
812    /// Clones the optional status message.
813    #[must_use]
814    pub fn message(&self) -> Option<A2aMessage> {
815        self.inner.message.clone().map(|inner| A2aMessage { inner })
816    }
817
818    fn try_from_wire(inner: wire::TaskStatus) -> Result<Self, A2aContractError> {
819        let state = A2aTaskState::try_from(inner.state.clone())?;
820        if matches!(state, A2aTaskState::AuthRequired) && inner.message.is_none() {
821            return Err(A2aContractError::InvalidLifecycle(
822                "auth-required status needs an explanatory message",
823            ));
824        }
825        if let Some(message) = inner.message.iter().next().cloned() {
826            A2aMessage::try_from_wire(message)?;
827        }
828        Ok(Self { inner })
829    }
830
831    fn into_wire(self) -> wire::TaskStatus {
832        self.inner
833    }
834}
835
836/// Bounded output artifact attached to an A2A task.
837#[derive(Clone, Debug, PartialEq)]
838pub struct A2aArtifact {
839    inner: wire::Artifact,
840}
841
842impl A2aArtifact {
843    /// Constructs an artifact from one or more bounded parts.
844    pub fn new(
845        artifact_id: impl Into<String>,
846        parts: Vec<A2aPart>,
847    ) -> Result<Self, A2aContractError> {
848        let artifact_id = artifact_id.into();
849        validate_required_text("artifact id", &artifact_id, MAX_ID_BYTES)?;
850        if parts.is_empty() {
851            return Err(A2aContractError::Empty {
852                field: "artifact parts",
853            });
854        }
855        validate_count("artifact parts", parts.len(), MAX_PARTS)?;
856        Ok(Self {
857            inner: wire::Artifact {
858                artifact_id,
859                name: None,
860                description: None,
861                parts: parts.into_iter().map(A2aPart::into_wire).collect(),
862                metadata: None,
863                extensions: None,
864            },
865        })
866    }
867
868    /// Adds a bounded display name.
869    pub fn with_name(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
870        let value = value.into();
871        validate_required_text("artifact name", &value, MAX_LABEL_BYTES)?;
872        self.inner.name = Some(value);
873        Ok(self)
874    }
875
876    /// Adds a bounded description.
877    pub fn with_description(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
878        let value = value.into();
879        validate_required_text("artifact description", &value, MAX_DESCRIPTION_BYTES)?;
880        self.inner.description = Some(value);
881        Ok(self)
882    }
883
884    /// Adds bounded metadata.
885    pub fn with_metadata(
886        mut self,
887        value: HashMap<String, Value>,
888    ) -> Result<Self, A2aContractError> {
889        validate_metadata("artifact metadata", Some(&value))?;
890        self.inner.metadata = Some(value);
891        Ok(self)
892    }
893
894    /// Returns the stable artifact identifier.
895    #[must_use]
896    pub fn artifact_id(&self) -> &str {
897        &self.inner.artifact_id
898    }
899
900    /// Returns the optional untrusted display name.
901    #[must_use]
902    pub fn name(&self) -> Option<&str> {
903        self.inner.name.as_deref()
904    }
905
906    /// Returns the optional untrusted description.
907    #[must_use]
908    pub fn description(&self) -> Option<&str> {
909        self.inner.description.as_deref()
910    }
911
912    /// Iterates allocation-free borrowed views of the artifact parts.
913    pub fn parts(&self) -> impl ExactSizeIterator<Item = A2aPartRef<'_>> {
914        self.inner.parts.iter().map(|inner| A2aPartRef { inner })
915    }
916
917    /// Returns untrusted protocol metadata.
918    #[must_use]
919    pub const fn metadata(&self) -> Option<&HashMap<String, Value>> {
920        self.inner.metadata.as_ref()
921    }
922
923    fn try_from_wire(inner: wire::Artifact) -> Result<Self, A2aContractError> {
924        validate_required_text("artifact id", &inner.artifact_id, MAX_ID_BYTES)?;
925        validate_optional_text("artifact name", inner.name.as_deref(), MAX_LABEL_BYTES)?;
926        validate_optional_text(
927            "artifact description",
928            inner.description.as_deref(),
929            MAX_DESCRIPTION_BYTES,
930        )?;
931        if inner.parts.is_empty() {
932            return Err(A2aContractError::Empty {
933                field: "artifact parts",
934            });
935        }
936        validate_count("artifact parts", inner.parts.len(), MAX_PARTS)?;
937        for part in inner.parts.iter().cloned() {
938            A2aPart::try_from_wire(part)?;
939        }
940        validate_metadata("artifact metadata", inner.metadata.as_ref())?;
941        if let Some(extensions) = inner.extensions.as_ref() {
942            validate_string_list(
943                "artifact extensions",
944                extensions,
945                MAX_EXTENSIONS,
946                MAX_URL_BYTES,
947            )?;
948            for extension in extensions {
949                validate_url("artifact extension", extension)?;
950            }
951        }
952        Ok(Self { inner })
953    }
954
955    fn into_wire(self) -> wire::Artifact {
956        self.inner
957    }
958}
959
960/// A bounded A2A task projection.
961#[derive(Clone, Debug, PartialEq)]
962pub struct A2aTask {
963    inner: wire::Task,
964}
965
966impl A2aTask {
967    /// Constructs a task projection. The identifier is an A2A identifier and
968    /// must not be an exposed `StateKnot` run identifier.
969    pub fn new(
970        id: impl Into<String>,
971        context_id: impl Into<String>,
972        status: A2aTaskStatus,
973    ) -> Result<Self, A2aContractError> {
974        let id = id.into();
975        let context_id = context_id.into();
976        validate_required_text("task id", &id, MAX_ID_BYTES)?;
977        validate_required_text("context id", &context_id, MAX_ID_BYTES)?;
978        Ok(Self {
979            inner: wire::Task {
980                id,
981                context_id,
982                status: status.into_wire(),
983                artifacts: None,
984                history: None,
985                metadata: None,
986            },
987        })
988    }
989
990    /// Adds a bounded artifact projection.
991    pub fn with_artifacts(mut self, artifacts: Vec<A2aArtifact>) -> Result<Self, A2aContractError> {
992        validate_count("task artifacts", artifacts.len(), MAX_ARTIFACTS)?;
993        validate_unique_artifact_ids(&artifacts)?;
994        self.inner.artifacts = Some(artifacts.into_iter().map(A2aArtifact::into_wire).collect());
995        Ok(self)
996    }
997
998    /// Adds bounded message history in chronological order.
999    pub fn with_history(mut self, history: Vec<A2aMessage>) -> Result<Self, A2aContractError> {
1000        validate_count("task history", history.len(), MAX_MESSAGES)?;
1001        self.inner.history = Some(history.into_iter().map(A2aMessage::into_wire).collect());
1002        Ok(self)
1003    }
1004
1005    /// Adds bounded task metadata.
1006    pub fn with_metadata(
1007        mut self,
1008        metadata: HashMap<String, Value>,
1009    ) -> Result<Self, A2aContractError> {
1010        validate_metadata("task metadata", Some(&metadata))?;
1011        self.inner.metadata = Some(metadata);
1012        Ok(self)
1013    }
1014
1015    /// Returns the opaque A2A task identifier.
1016    #[must_use]
1017    pub fn id(&self) -> &str {
1018        &self.inner.id
1019    }
1020
1021    /// Returns the opaque A2A context identifier.
1022    #[must_use]
1023    pub fn context_id(&self) -> &str {
1024        &self.inner.context_id
1025    }
1026
1027    /// Returns the task state.
1028    #[must_use]
1029    pub fn state(&self) -> A2aTaskState {
1030        A2aTaskState::try_from(self.inner.status.state.clone())
1031            .expect("A2aTask construction validates task state")
1032    }
1033
1034    /// Clones the status projection.
1035    #[must_use]
1036    pub fn status(&self) -> A2aTaskStatus {
1037        A2aTaskStatus {
1038            inner: self.inner.status.clone(),
1039        }
1040    }
1041
1042    /// Clones message history for application mapping.
1043    #[must_use]
1044    pub fn history(&self) -> Vec<A2aMessage> {
1045        self.inner
1046            .history
1047            .as_deref()
1048            .unwrap_or_default()
1049            .iter()
1050            .cloned()
1051            .map(|inner| A2aMessage { inner })
1052            .collect()
1053    }
1054
1055    /// Clones artifact projections for application mapping.
1056    #[must_use]
1057    pub fn artifacts(&self) -> Vec<A2aArtifact> {
1058        self.inner
1059            .artifacts
1060            .as_deref()
1061            .unwrap_or_default()
1062            .iter()
1063            .cloned()
1064            .map(|inner| A2aArtifact { inner })
1065            .collect()
1066    }
1067
1068    pub(crate) fn history_len(&self) -> usize {
1069        self.inner.history.as_ref().map_or(0, Vec::len)
1070    }
1071
1072    pub(crate) fn has_artifact_projection(&self) -> bool {
1073        self.inner.artifacts.is_some()
1074    }
1075
1076    pub(crate) fn artifact_ids(&self) -> impl Iterator<Item = &str> {
1077        self.inner
1078            .artifacts
1079            .as_deref()
1080            .unwrap_or_default()
1081            .iter()
1082            .map(|artifact| artifact.artifact_id.as_str())
1083    }
1084
1085    pub(crate) fn try_from_wire(inner: wire::Task) -> Result<Self, A2aContractError> {
1086        validate_required_text("task id", &inner.id, MAX_ID_BYTES)?;
1087        validate_required_text("context id", &inner.context_id, MAX_ID_BYTES)?;
1088        A2aTaskStatus::try_from_wire(inner.status.clone())?;
1089        if let Some(artifacts) = inner.artifacts.as_ref() {
1090            validate_count("task artifacts", artifacts.len(), MAX_ARTIFACTS)?;
1091            let artifacts = artifacts
1092                .iter()
1093                .cloned()
1094                .map(A2aArtifact::try_from_wire)
1095                .collect::<Result<Vec<_>, _>>()?;
1096            validate_unique_artifact_ids(&artifacts)?;
1097        }
1098        if let Some(history) = inner.history.as_ref() {
1099            validate_count("task history", history.len(), MAX_MESSAGES)?;
1100            for message in history.iter().cloned() {
1101                A2aMessage::try_from_wire(message)?;
1102            }
1103        }
1104        validate_metadata("task metadata", inner.metadata.as_ref())?;
1105        Ok(Self { inner })
1106    }
1107
1108    pub(crate) fn into_wire(self) -> wire::Task {
1109        self.inner
1110    }
1111}
1112
1113fn validate_unique_artifact_ids(artifacts: &[A2aArtifact]) -> Result<(), A2aContractError> {
1114    let mut ids = HashSet::with_capacity(artifacts.len());
1115    if artifacts
1116        .iter()
1117        .any(|artifact| !ids.insert(artifact.artifact_id()))
1118    {
1119        return Err(A2aContractError::InvalidLifecycle(
1120            "artifact identifiers must be unique within a task",
1121        ));
1122    }
1123    Ok(())
1124}
1125
1126/// Optional execution controls on a send request.
1127#[derive(Clone, Debug, Default, PartialEq)]
1128pub struct A2aSendConfiguration {
1129    accepted_output_modes: Vec<String>,
1130    push_config: Option<A2aPushConfig>,
1131    history_length: Option<u32>,
1132    return_immediately: bool,
1133}
1134
1135impl A2aSendConfiguration {
1136    /// Constructs default execution controls.
1137    #[must_use]
1138    pub const fn new() -> Self {
1139        Self {
1140            accepted_output_modes: Vec::new(),
1141            push_config: None,
1142            history_length: None,
1143            return_immediately: false,
1144        }
1145    }
1146
1147    /// Restricts acceptable response media modes.
1148    pub fn with_accepted_output_modes(
1149        mut self,
1150        modes: Vec<String>,
1151    ) -> Result<Self, A2aContractError> {
1152        validate_modes("accepted output modes", &modes)?;
1153        self.accepted_output_modes = modes;
1154        Ok(self)
1155    }
1156
1157    /// Requests an initial push-notification configuration.
1158    #[must_use]
1159    pub fn with_push_config(mut self, config: A2aPushConfig) -> Self {
1160        self.push_config = Some(config);
1161        self
1162    }
1163
1164    /// Requests a bounded suffix of task history in the response.
1165    pub fn with_history_length(mut self, length: u32) -> Result<Self, A2aContractError> {
1166        if usize::try_from(length).unwrap_or(usize::MAX) > MAX_MESSAGES {
1167            return Err(A2aContractError::TooLarge {
1168                field: "history length",
1169                maximum: MAX_MESSAGES,
1170                actual: usize::try_from(length).unwrap_or(usize::MAX),
1171            });
1172        }
1173        self.history_length = Some(length);
1174        Ok(self)
1175    }
1176
1177    /// Requests a task snapshot as soon as the server durably accepts work.
1178    #[must_use]
1179    pub const fn return_immediately(mut self, enabled: bool) -> Self {
1180        self.return_immediately = enabled;
1181        self
1182    }
1183
1184    /// Returns whether the caller requested immediate acknowledgement.
1185    #[must_use]
1186    pub const fn should_return_immediately(&self) -> bool {
1187        self.return_immediately
1188    }
1189
1190    /// Returns the requested history length.
1191    #[must_use]
1192    pub const fn history_length(&self) -> Option<u32> {
1193        self.history_length
1194    }
1195
1196    /// Returns acceptable output modes in preference order.
1197    pub fn accepted_output_modes(&self) -> impl ExactSizeIterator<Item = &str> {
1198        self.accepted_output_modes.iter().map(String::as_str)
1199    }
1200
1201    /// Returns an initial push configuration when supplied.
1202    #[must_use]
1203    pub const fn push_config(&self) -> Option<&A2aPushConfig> {
1204        self.push_config.as_ref()
1205    }
1206
1207    fn try_from_wire(value: wire::SendMessageConfiguration) -> Result<Self, A2aContractError> {
1208        let accepted_output_modes = value.accepted_output_modes.unwrap_or_default();
1209        validate_modes("accepted output modes", &accepted_output_modes)?;
1210        let history_length = value
1211            .history_length
1212            .map(|value| {
1213                u32::try_from(value).map_err(|_| {
1214                    A2aContractError::InvalidLifecycle("history length must be non-negative")
1215                })
1216            })
1217            .transpose()?;
1218        if history_length.is_some_and(|value| value as usize > MAX_MESSAGES) {
1219            return Err(A2aContractError::TooLarge {
1220                field: "history length",
1221                maximum: MAX_MESSAGES,
1222                actual: history_length.unwrap_or_default() as usize,
1223            });
1224        }
1225        let push_config = value
1226            .task_push_notification_config
1227            .map(A2aPushConfig::try_from_wire)
1228            .transpose()?;
1229        if push_config
1230            .as_ref()
1231            .is_some_and(|config| config.task_id().is_some())
1232        {
1233            return Err(A2aContractError::InvalidLifecycle(
1234                "send-message push configuration must not contain a task id",
1235            ));
1236        }
1237        Ok(Self {
1238            accepted_output_modes,
1239            push_config,
1240            history_length,
1241            return_immediately: value.return_immediately.unwrap_or(false),
1242        })
1243    }
1244
1245    fn into_wire(self) -> Result<wire::SendMessageConfiguration, A2aContractError> {
1246        if self
1247            .push_config
1248            .as_ref()
1249            .is_some_and(|config| config.task_id().is_some())
1250        {
1251            return Err(A2aContractError::InvalidLifecycle(
1252                "send-message push configuration must not contain a task id",
1253            ));
1254        }
1255        Ok(wire::SendMessageConfiguration {
1256            accepted_output_modes: (!self.accepted_output_modes.is_empty())
1257                .then_some(self.accepted_output_modes),
1258            task_push_notification_config: self.push_config.map(A2aPushConfig::into_wire),
1259            history_length: self
1260                .history_length
1261                .map(|value| {
1262                    i32::try_from(value).map_err(|_| {
1263                        A2aContractError::InvalidLifecycle(
1264                            "history length cannot be represented on the wire",
1265                        )
1266                    })
1267                })
1268                .transpose()?,
1269            return_immediately: self.return_immediately.then_some(true),
1270        })
1271    }
1272}
1273
1274fn validate_modes(field: &'static str, modes: &[String]) -> Result<(), A2aContractError> {
1275    validate_string_list(field, modes, MAX_MODES, MAX_MODE_BYTES)?;
1276    for mode in modes {
1277        mode.parse::<mime::Mime>()
1278            .map_err(|_| A2aContractError::InvalidText { field })?;
1279    }
1280    Ok(())
1281}
1282
1283/// A validated request to send a message.
1284#[derive(Clone, Debug, PartialEq)]
1285pub struct A2aSendMessageRequest {
1286    message: A2aMessage,
1287    configuration: Option<A2aSendConfiguration>,
1288    metadata: Option<HashMap<String, Value>>,
1289}
1290
1291impl A2aSendMessageRequest {
1292    /// Constructs a send request.
1293    #[must_use]
1294    pub const fn new(message: A2aMessage) -> Self {
1295        Self {
1296            message,
1297            configuration: None,
1298            metadata: None,
1299        }
1300    }
1301
1302    /// Adds execution controls.
1303    #[must_use]
1304    pub fn with_configuration(mut self, configuration: A2aSendConfiguration) -> Self {
1305        self.configuration = Some(configuration);
1306        self
1307    }
1308
1309    /// Adds bounded request metadata.
1310    pub fn with_metadata(
1311        mut self,
1312        metadata: HashMap<String, Value>,
1313    ) -> Result<Self, A2aContractError> {
1314        validate_metadata("send metadata", Some(&metadata))?;
1315        self.metadata = Some(metadata);
1316        Ok(self)
1317    }
1318
1319    /// Returns the message.
1320    #[must_use]
1321    pub const fn message(&self) -> &A2aMessage {
1322        &self.message
1323    }
1324
1325    /// Returns execution controls.
1326    #[must_use]
1327    pub const fn configuration(&self) -> Option<&A2aSendConfiguration> {
1328        self.configuration.as_ref()
1329    }
1330
1331    /// Returns request metadata.
1332    #[must_use]
1333    pub const fn metadata(&self) -> Option<&HashMap<String, Value>> {
1334        self.metadata.as_ref()
1335    }
1336
1337    pub(crate) fn try_from_wire(value: wire::SendMessageRequest) -> Result<Self, A2aContractError> {
1338        validate_metadata("send metadata", value.metadata.as_ref())?;
1339        if value.tenant.is_some() {
1340            return Err(A2aContractError::Unsupported {
1341                field: "request tenant override",
1342                value: "tenant".to_string(),
1343            });
1344        }
1345        let message = A2aMessage::try_from_wire(value.message)?;
1346        if message.role() != A2aMessageRole::User {
1347            return Err(A2aContractError::InvalidLifecycle(
1348                "send-message requests require a user-role message",
1349            ));
1350        }
1351        Ok(Self {
1352            message,
1353            configuration: value
1354                .configuration
1355                .map(A2aSendConfiguration::try_from_wire)
1356                .transpose()?,
1357            metadata: value.metadata,
1358        })
1359    }
1360
1361    pub(crate) fn into_wire(
1362        self,
1363        tenant: Option<String>,
1364    ) -> Result<wire::SendMessageRequest, A2aContractError> {
1365        if self.message.role() != A2aMessageRole::User {
1366            return Err(A2aContractError::InvalidLifecycle(
1367                "send-message requests require a user-role message",
1368            ));
1369        }
1370        Ok(wire::SendMessageRequest {
1371            message: self.message.into_wire(),
1372            configuration: self
1373                .configuration
1374                .map(A2aSendConfiguration::into_wire)
1375                .transpose()?,
1376            metadata: self.metadata,
1377            tenant,
1378        })
1379    }
1380}
1381
1382/// Unary response to a send operation.
1383#[derive(Clone, Debug, PartialEq)]
1384#[non_exhaustive]
1385pub enum A2aSendMessageResponse {
1386    /// A durable task was accepted or updated.
1387    Task(A2aTask),
1388    /// The operation completed directly with a message.
1389    Message(A2aMessage),
1390}
1391
1392impl A2aSendMessageResponse {
1393    pub(crate) fn try_from_wire(
1394        value: wire::SendMessageResponse,
1395    ) -> Result<Self, A2aContractError> {
1396        match value {
1397            wire::SendMessageResponse::Task(task) => Ok(Self::Task(A2aTask::try_from_wire(task)?)),
1398            wire::SendMessageResponse::Message(message) => {
1399                Ok(Self::Message(A2aMessage::try_from_wire(message)?))
1400            }
1401        }
1402    }
1403
1404    /// Returns the standard field-presence JSON representation.
1405    pub fn to_json(&self) -> Result<Value, A2aContractError> {
1406        let wire = match self {
1407            Self::Task(task) => wire::SendMessageResponse::Task(task.inner.clone()),
1408            Self::Message(message) => wire::SendMessageResponse::Message(message.inner.clone()),
1409        };
1410        serde_json::to_value(wire).map_err(|_| A2aContractError::InvalidJson {
1411            field: "send response",
1412        })
1413    }
1414
1415    /// Parses and bounds a standard field-presence JSON response.
1416    pub fn from_json(value: Value) -> Result<Self, A2aContractError> {
1417        validate_json("send response", &value, MAX_PART_BYTES * 2)?;
1418        let object = value.as_object().ok_or(A2aContractError::InvalidJson {
1419            field: "send response",
1420        })?;
1421        if object.len() != 1 || !(object.contains_key("task") || object.contains_key("message")) {
1422            return Err(A2aContractError::InvalidJson {
1423                field: "send response",
1424            });
1425        }
1426        let wire = serde_json::from_value(value).map_err(|_| A2aContractError::InvalidJson {
1427            field: "send response",
1428        })?;
1429        Self::try_from_wire(wire)
1430    }
1431
1432    pub(crate) fn into_wire(self) -> wire::SendMessageResponse {
1433        match self {
1434            Self::Task(task) => wire::SendMessageResponse::Task(task.into_wire()),
1435            Self::Message(message) => wire::SendMessageResponse::Message(message.into_wire()),
1436        }
1437    }
1438}
1439
1440/// A validated task lookup request.
1441#[derive(Clone, Debug, Eq, PartialEq)]
1442pub struct A2aGetTaskRequest {
1443    id: Box<str>,
1444    history_length: Option<u32>,
1445}
1446
1447impl A2aGetTaskRequest {
1448    /// Constructs a lookup request.
1449    pub fn new(id: impl Into<String>) -> Result<Self, A2aContractError> {
1450        let id = id.into();
1451        validate_required_text("task id", &id, MAX_ID_BYTES)?;
1452        Ok(Self {
1453            id: id.into_boxed_str(),
1454            history_length: None,
1455        })
1456    }
1457
1458    /// Selects a bounded history suffix.
1459    pub fn with_history_length(mut self, length: u32) -> Result<Self, A2aContractError> {
1460        if length as usize > MAX_MESSAGES {
1461            return Err(A2aContractError::TooLarge {
1462                field: "history length",
1463                maximum: MAX_MESSAGES,
1464                actual: length as usize,
1465            });
1466        }
1467        self.history_length = Some(length);
1468        Ok(self)
1469    }
1470
1471    /// Returns the task identifier.
1472    #[must_use]
1473    pub fn id(&self) -> &str {
1474        &self.id
1475    }
1476
1477    /// Returns the requested history length.
1478    #[must_use]
1479    pub const fn history_length(&self) -> Option<u32> {
1480        self.history_length
1481    }
1482
1483    pub(crate) fn try_from_wire(value: wire::GetTaskRequest) -> Result<Self, A2aContractError> {
1484        if value.tenant.is_some() {
1485            return Err(A2aContractError::Unsupported {
1486                field: "request tenant override",
1487                value: "tenant".to_string(),
1488            });
1489        }
1490        let mut request = Self::new(value.id)?;
1491        if let Some(length) = value.history_length {
1492            request = request.with_history_length(u32::try_from(length).map_err(|_| {
1493                A2aContractError::InvalidLifecycle("history length must be non-negative")
1494            })?)?;
1495        }
1496        Ok(request)
1497    }
1498
1499    pub(crate) fn into_wire(
1500        self,
1501        tenant: Option<String>,
1502    ) -> Result<wire::GetTaskRequest, A2aContractError> {
1503        Ok(wire::GetTaskRequest {
1504            id: self.id.into(),
1505            history_length: self
1506                .history_length
1507                .map(|value| {
1508                    i32::try_from(value).map_err(|_| {
1509                        A2aContractError::InvalidLifecycle(
1510                            "history length cannot be represented on the wire",
1511                        )
1512                    })
1513                })
1514                .transpose()?,
1515            tenant,
1516        })
1517    }
1518}
1519
1520/// Bounded filters and cursor for task listing.
1521#[derive(Clone, Debug, Default, PartialEq)]
1522pub struct A2aListTasksRequest {
1523    context_id: Option<Box<str>>,
1524    status: Option<A2aTaskState>,
1525    page_size: u16,
1526    page_token: Option<Box<str>>,
1527    history_length: Option<u32>,
1528    status_timestamp_after: Option<DateTime<Utc>>,
1529    include_artifacts: bool,
1530}
1531
1532impl A2aListTasksRequest {
1533    /// Protocol-defined default page size.
1534    pub const DEFAULT_PAGE_SIZE: u16 = 50;
1535    /// A2A 1.0 protocol page-size ceiling.
1536    pub const MAX_PAGE_SIZE: u16 = 100;
1537
1538    /// Constructs an unfiltered first page.
1539    #[must_use]
1540    pub const fn new() -> Self {
1541        Self {
1542            context_id: None,
1543            status: None,
1544            page_size: Self::DEFAULT_PAGE_SIZE,
1545            page_token: None,
1546            history_length: None,
1547            status_timestamp_after: None,
1548            include_artifacts: false,
1549        }
1550    }
1551
1552    /// Filters by exact context identifier.
1553    pub fn with_context_id(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
1554        let value = value.into();
1555        validate_required_text("context id", &value, MAX_ID_BYTES)?;
1556        self.context_id = Some(value.into_boxed_str());
1557        Ok(self)
1558    }
1559
1560    /// Filters by exact task state.
1561    #[must_use]
1562    pub const fn with_status(mut self, value: A2aTaskState) -> Self {
1563        self.status = Some(value);
1564        self
1565    }
1566
1567    /// Sets a bounded page size.
1568    pub fn with_page_size(mut self, value: u16) -> Result<Self, A2aContractError> {
1569        if value == 0 || value > Self::MAX_PAGE_SIZE {
1570            return Err(A2aContractError::InvalidLifecycle(
1571                "page size is outside the supported range",
1572            ));
1573        }
1574        self.page_size = value;
1575        Ok(self)
1576    }
1577
1578    /// Sets an opaque, bounded backend cursor.
1579    pub fn with_page_token(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
1580        let value = value.into();
1581        validate_required_text("page token", &value, MAX_ID_BYTES * 4)?;
1582        self.page_token = Some(value.into_boxed_str());
1583        Ok(self)
1584    }
1585
1586    /// Selects a bounded history suffix for each task.
1587    pub fn with_history_length(mut self, value: u32) -> Result<Self, A2aContractError> {
1588        if value as usize > MAX_MESSAGES {
1589            return Err(A2aContractError::TooLarge {
1590                field: "history length",
1591                maximum: MAX_MESSAGES,
1592                actual: value as usize,
1593            });
1594        }
1595        self.history_length = Some(value);
1596        Ok(self)
1597    }
1598
1599    /// Filters task status timestamps to this instant or later.
1600    #[must_use]
1601    pub const fn with_status_timestamp_after(mut self, value: DateTime<Utc>) -> Self {
1602        self.status_timestamp_after = Some(value);
1603        self
1604    }
1605
1606    /// Requests artifact projections in listed tasks.
1607    #[must_use]
1608    pub const fn include_artifacts(mut self, include: bool) -> Self {
1609        self.include_artifacts = include;
1610        self
1611    }
1612
1613    /// Returns the exact context filter.
1614    #[must_use]
1615    pub fn context_id(&self) -> Option<&str> {
1616        self.context_id.as_deref()
1617    }
1618
1619    /// Returns the task-state filter.
1620    #[must_use]
1621    pub const fn status(&self) -> Option<A2aTaskState> {
1622        self.status
1623    }
1624
1625    /// Returns the effective page size.
1626    #[must_use]
1627    pub const fn page_size(&self) -> u16 {
1628        self.page_size
1629    }
1630
1631    /// Returns the opaque cursor.
1632    #[must_use]
1633    pub fn page_token(&self) -> Option<&str> {
1634        self.page_token.as_deref()
1635    }
1636
1637    /// Returns the requested history length.
1638    #[must_use]
1639    pub const fn history_length(&self) -> Option<u32> {
1640        self.history_length
1641    }
1642
1643    /// Returns the timestamp lower bound.
1644    #[must_use]
1645    pub const fn status_timestamp_after(&self) -> Option<DateTime<Utc>> {
1646        self.status_timestamp_after
1647    }
1648
1649    /// Returns whether artifact projections were requested.
1650    #[must_use]
1651    pub const fn should_include_artifacts(&self) -> bool {
1652        self.include_artifacts
1653    }
1654
1655    pub(crate) fn try_from_wire(value: wire::ListTasksRequest) -> Result<Self, A2aContractError> {
1656        if value.tenant.is_some() {
1657            return Err(A2aContractError::Unsupported {
1658                field: "request tenant override",
1659                value: "tenant".to_string(),
1660            });
1661        }
1662        let mut request = Self::new();
1663        if let Some(context_id) = value.context_id {
1664            request = request.with_context_id(context_id)?;
1665        }
1666        if let Some(status) = value.status {
1667            request = request.with_status(A2aTaskState::try_from(status)?);
1668        }
1669        if let Some(page_size) = value.page_size {
1670            request = request.with_page_size(u16::try_from(page_size).map_err(|_| {
1671                A2aContractError::InvalidLifecycle("page size is outside the supported range")
1672            })?)?;
1673        }
1674        if let Some(page_token) = value.page_token {
1675            request = request.with_page_token(page_token)?;
1676        }
1677        if let Some(history_length) = value.history_length {
1678            request =
1679                request.with_history_length(u32::try_from(history_length).map_err(|_| {
1680                    A2aContractError::InvalidLifecycle("history length must be non-negative")
1681                })?)?;
1682        }
1683        if let Some(timestamp) = value.status_timestamp_after {
1684            request = request.with_status_timestamp_after(timestamp);
1685        }
1686        request.include_artifacts = value.include_artifacts.unwrap_or(false);
1687        Ok(request)
1688    }
1689
1690    pub(crate) fn into_wire(self, tenant: Option<String>) -> wire::ListTasksRequest {
1691        wire::ListTasksRequest {
1692            context_id: self.context_id.map(Into::into),
1693            status: self.status.map(Into::into),
1694            page_size: Some(i32::from(self.page_size)),
1695            page_token: self.page_token.map(Into::into),
1696            history_length: self
1697                .history_length
1698                .map(|value| i32::try_from(value).expect("bounded history length fits i32")),
1699            status_timestamp_after: self.status_timestamp_after,
1700            include_artifacts: self.include_artifacts.then_some(true),
1701            tenant,
1702        }
1703    }
1704}
1705
1706/// One stable-snapshot page of A2A tasks.
1707#[derive(Clone, Debug, PartialEq)]
1708pub struct A2aTaskPage {
1709    tasks: Vec<A2aTask>,
1710    next_page_token: Option<Box<str>>,
1711    page_size: u16,
1712    total_size: u64,
1713}
1714
1715impl A2aTaskPage {
1716    /// Constructs a bounded page.
1717    pub fn new(
1718        tasks: Vec<A2aTask>,
1719        next_page_token: Option<String>,
1720        page_size: u16,
1721        total_size: u64,
1722    ) -> Result<Self, A2aContractError> {
1723        validate_count(
1724            "task page",
1725            tasks.len(),
1726            usize::from(A2aListTasksRequest::MAX_PAGE_SIZE),
1727        )?;
1728        if page_size == 0 || page_size > A2aListTasksRequest::MAX_PAGE_SIZE {
1729            return Err(A2aContractError::InvalidLifecycle(
1730                "task response page size is outside the protocol range",
1731            ));
1732        }
1733        if tasks.len() > usize::from(page_size) {
1734            return Err(A2aContractError::InvalidLifecycle(
1735                "task response contains more tasks than its page size",
1736            ));
1737        }
1738        if total_size < tasks.len() as u64 {
1739            return Err(A2aContractError::InvalidLifecycle(
1740                "task response total size is smaller than the returned page",
1741            ));
1742        }
1743        let mut task_ids = HashSet::with_capacity(tasks.len());
1744        let mut previous_timestamp = None;
1745        for task in &tasks {
1746            let timestamp = task.status().timestamp();
1747            if !task_ids.insert(task.id())
1748                || previous_timestamp
1749                    .zip(timestamp)
1750                    .is_some_and(|(previous, current)| previous < current)
1751            {
1752                return Err(A2aContractError::InvalidLifecycle(
1753                    "task page must contain unique IDs in newest-status-first order",
1754                ));
1755            }
1756            if timestamp.is_some() {
1757                previous_timestamp = timestamp;
1758            }
1759        }
1760        if let Some(token) = next_page_token.as_deref() {
1761            validate_required_text("page token", token, MAX_ID_BYTES * 4)?;
1762        }
1763        Ok(Self {
1764            tasks,
1765            next_page_token: next_page_token.map(String::into_boxed_str),
1766            page_size,
1767            total_size,
1768        })
1769    }
1770
1771    /// Returns tasks in protocol-defined newest-status-first order.
1772    #[must_use]
1773    pub fn tasks(&self) -> &[A2aTask] {
1774        &self.tasks
1775    }
1776
1777    /// Returns the stable-snapshot continuation cursor.
1778    #[must_use]
1779    pub fn next_page_token(&self) -> Option<&str> {
1780        self.next_page_token.as_deref()
1781    }
1782
1783    /// Returns the page size used by the remote service.
1784    #[must_use]
1785    pub const fn page_size(&self) -> u16 {
1786        self.page_size
1787    }
1788
1789    /// Returns the authorized total size when known by the backend.
1790    #[must_use]
1791    pub const fn total_size(&self) -> u64 {
1792        self.total_size
1793    }
1794
1795    pub(crate) fn into_wire(self) -> Result<wire::ListTasksResponse, A2aContractError> {
1796        let total_size = i32::try_from(self.total_size).map_err(|_| {
1797            A2aContractError::InvalidLifecycle("task total count cannot be represented")
1798        })?;
1799        Ok(wire::ListTasksResponse {
1800            tasks: self.tasks.into_iter().map(A2aTask::into_wire).collect(),
1801            next_page_token: self.next_page_token.map(Into::into).unwrap_or_default(),
1802            page_size: i32::from(self.page_size),
1803            total_size,
1804        })
1805    }
1806
1807    pub(crate) fn try_from_wire(value: wire::ListTasksResponse) -> Result<Self, A2aContractError> {
1808        if value.total_size < 0 {
1809            return Err(A2aContractError::InvalidLifecycle(
1810                "task page counts must be non-negative",
1811            ));
1812        }
1813        let page_size = u16::try_from(value.page_size).map_err(|_| {
1814            A2aContractError::InvalidLifecycle(
1815                "task response page size is outside the protocol range",
1816            )
1817        })?;
1818        let tasks = value
1819            .tasks
1820            .into_iter()
1821            .map(A2aTask::try_from_wire)
1822            .collect::<Result<Vec<_>, _>>()?;
1823        let next = (!value.next_page_token.is_empty()).then_some(value.next_page_token);
1824        Self::new(
1825            tasks,
1826            next,
1827            page_size,
1828            u64::try_from(value.total_size)
1829                .expect("non-negative i32 task total always fits in u64"),
1830        )
1831    }
1832}
1833
1834/// Validated task-cancellation request.
1835#[derive(Clone, Debug, Eq, PartialEq)]
1836pub struct A2aCancelTaskRequest {
1837    id: Box<str>,
1838    metadata: Option<HashMap<String, Value>>,
1839}
1840
1841impl A2aCancelTaskRequest {
1842    /// Constructs a cancellation request.
1843    pub fn new(id: impl Into<String>) -> Result<Self, A2aContractError> {
1844        let id = id.into();
1845        validate_required_text("task id", &id, MAX_ID_BYTES)?;
1846        Ok(Self {
1847            id: id.into_boxed_str(),
1848            metadata: None,
1849        })
1850    }
1851
1852    /// Adds bounded cancellation metadata.
1853    pub fn with_metadata(
1854        mut self,
1855        value: HashMap<String, Value>,
1856    ) -> Result<Self, A2aContractError> {
1857        validate_metadata("cancel metadata", Some(&value))?;
1858        self.metadata = Some(value);
1859        Ok(self)
1860    }
1861
1862    /// Returns the task identifier.
1863    #[must_use]
1864    pub fn id(&self) -> &str {
1865        &self.id
1866    }
1867
1868    /// Returns cancellation metadata.
1869    #[must_use]
1870    pub const fn metadata(&self) -> Option<&HashMap<String, Value>> {
1871        self.metadata.as_ref()
1872    }
1873
1874    pub(crate) fn try_from_wire(value: wire::CancelTaskRequest) -> Result<Self, A2aContractError> {
1875        if value.tenant.is_some() {
1876            return Err(A2aContractError::Unsupported {
1877                field: "request tenant override",
1878                value: "tenant".to_string(),
1879            });
1880        }
1881        let mut request = Self::new(value.id)?;
1882        if let Some(metadata) = value.metadata {
1883            request = request.with_metadata(metadata)?;
1884        }
1885        Ok(request)
1886    }
1887
1888    pub(crate) fn into_wire(self, tenant: Option<String>) -> wire::CancelTaskRequest {
1889        wire::CancelTaskRequest {
1890            id: self.id.into(),
1891            metadata: self.metadata,
1892            tenant,
1893        }
1894    }
1895}
1896
1897/// Validated task-subscription request.
1898#[derive(Clone, Debug, Eq, PartialEq)]
1899pub struct A2aSubscribeTaskRequest {
1900    id: Box<str>,
1901}
1902
1903impl A2aSubscribeTaskRequest {
1904    /// Constructs a subscription request.
1905    pub fn new(id: impl Into<String>) -> Result<Self, A2aContractError> {
1906        let id = id.into();
1907        validate_required_text("task id", &id, MAX_ID_BYTES)?;
1908        Ok(Self {
1909            id: id.into_boxed_str(),
1910        })
1911    }
1912
1913    /// Returns the task identifier.
1914    #[must_use]
1915    pub fn id(&self) -> &str {
1916        &self.id
1917    }
1918
1919    pub(crate) fn try_from_wire(
1920        value: wire::SubscribeToTaskRequest,
1921    ) -> Result<Self, A2aContractError> {
1922        if value.tenant.is_some() {
1923            return Err(A2aContractError::Unsupported {
1924                field: "request tenant override",
1925                value: "tenant".to_string(),
1926            });
1927        }
1928        Self::new(value.id)
1929    }
1930
1931    pub(crate) fn into_wire(self, tenant: Option<String>) -> wire::SubscribeToTaskRequest {
1932        wire::SubscribeToTaskRequest {
1933            id: self.id.into(),
1934            tenant,
1935        }
1936    }
1937}
1938
1939/// Optional authentication attached to an A2A push destination.
1940#[derive(Clone)]
1941pub struct A2aPushAuthentication {
1942    scheme: Box<str>,
1943    credentials: Option<A2aSecret>,
1944}
1945
1946impl A2aPushAuthentication {
1947    /// Constructs a bounded authentication descriptor.
1948    pub fn new(
1949        scheme: impl Into<String>,
1950        credentials: Option<A2aSecret>,
1951    ) -> Result<Self, A2aContractError> {
1952        let scheme = scheme.into();
1953        validate_required_text("push authentication scheme", &scheme, MAX_LABEL_BYTES)?;
1954        Ok(Self {
1955            scheme: scheme.into_boxed_str(),
1956            credentials,
1957        })
1958    }
1959
1960    /// Returns the case-sensitive scheme token.
1961    #[must_use]
1962    pub fn scheme(&self) -> &str {
1963        &self.scheme
1964    }
1965
1966    /// Returns secret credentials for immediate encryption or dispatch only.
1967    #[must_use]
1968    pub const fn credentials(&self) -> Option<&A2aSecret> {
1969        self.credentials.as_ref()
1970    }
1971
1972    fn try_from_wire(value: wire::AuthenticationInfo) -> Result<Self, A2aContractError> {
1973        Self::new(
1974            value.scheme,
1975            value.credentials.map(A2aSecret::new).transpose()?,
1976        )
1977    }
1978
1979    fn into_wire(self) -> wire::AuthenticationInfo {
1980        wire::AuthenticationInfo {
1981            scheme: self.scheme.into(),
1982            credentials: self
1983                .credentials
1984                .map(|credential| credential.expose_secret().to_string()),
1985        }
1986    }
1987}
1988
1989impl fmt::Debug for A2aPushAuthentication {
1990    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1991        formatter
1992            .debug_struct("A2aPushAuthentication")
1993            .field("scheme", &self.scheme)
1994            .field(
1995                "credentials",
1996                &self.credentials.as_ref().map(|_| "[REDACTED]"),
1997            )
1998            .finish()
1999    }
2000}
2001
2002impl PartialEq for A2aPushAuthentication {
2003    fn eq(&self, other: &Self) -> bool {
2004        self.scheme == other.scheme
2005            && self.credentials.as_ref().map(A2aSecret::expose_secret)
2006                == other.credentials.as_ref().map(A2aSecret::expose_secret)
2007    }
2008}
2009
2010/// Bounded push-notification configuration.
2011///
2012/// The URL is untrusted until a push worker applies the configured egress
2013/// policy. Token and credentials are redacted from `Debug` and must be stored
2014/// encrypted by a production backend.
2015#[derive(Clone, PartialEq)]
2016pub struct A2aPushConfig {
2017    url: Box<str>,
2018    id: Option<Box<str>>,
2019    task_id: Option<Box<str>>,
2020    token: Option<A2aSecret>,
2021    authentication: Option<A2aPushAuthentication>,
2022}
2023
2024impl A2aPushConfig {
2025    /// Constructs a destination without performing network access.
2026    pub fn new(url: impl Into<String>) -> Result<Self, A2aContractError> {
2027        let url = url.into();
2028        validate_url("push destination", &url)?;
2029        Ok(Self {
2030            url: url.into_boxed_str(),
2031            id: None,
2032            task_id: None,
2033            token: None,
2034            authentication: None,
2035        })
2036    }
2037
2038    /// Adds a server-issued configuration identifier.
2039    pub fn with_id(mut self, id: impl Into<String>) -> Result<Self, A2aContractError> {
2040        let id = id.into();
2041        validate_required_text("push config id", &id, MAX_ID_BYTES)?;
2042        self.id = Some(id.into_boxed_str());
2043        Ok(self)
2044    }
2045
2046    /// Binds the configuration to a task.
2047    pub fn with_task_id(mut self, id: impl Into<String>) -> Result<Self, A2aContractError> {
2048        let id = id.into();
2049        validate_required_text("task id", &id, MAX_ID_BYTES)?;
2050        self.task_id = Some(id.into_boxed_str());
2051        Ok(self)
2052    }
2053
2054    /// Adds a caller-provided validation token.
2055    #[must_use]
2056    pub fn with_token(mut self, token: A2aSecret) -> Self {
2057        self.token = Some(token);
2058        self
2059    }
2060
2061    /// Adds destination authentication.
2062    #[must_use]
2063    pub fn with_authentication(mut self, authentication: A2aPushAuthentication) -> Self {
2064        self.authentication = Some(authentication);
2065        self
2066    }
2067
2068    /// Returns the untrusted callback URL.
2069    #[must_use]
2070    pub fn url(&self) -> &str {
2071        &self.url
2072    }
2073
2074    /// Returns the configuration identifier.
2075    #[must_use]
2076    pub fn id(&self) -> Option<&str> {
2077        self.id.as_deref()
2078    }
2079
2080    /// Returns the bound task identifier.
2081    #[must_use]
2082    pub fn task_id(&self) -> Option<&str> {
2083        self.task_id.as_deref()
2084    }
2085
2086    /// Returns the validation token for immediate encryption or dispatch only.
2087    #[must_use]
2088    pub const fn token(&self) -> Option<&A2aSecret> {
2089        self.token.as_ref()
2090    }
2091
2092    /// Returns destination authentication.
2093    #[must_use]
2094    pub const fn authentication(&self) -> Option<&A2aPushAuthentication> {
2095        self.authentication.as_ref()
2096    }
2097
2098    pub(crate) fn try_from_wire(
2099        value: wire::TaskPushNotificationConfig,
2100    ) -> Result<Self, A2aContractError> {
2101        if value.tenant.is_some() {
2102            return Err(A2aContractError::Unsupported {
2103                field: "request tenant override",
2104                value: "tenant".to_string(),
2105            });
2106        }
2107        let mut config = Self::new(value.url)?;
2108        if let Some(id) = value.id {
2109            config = config.with_id(id)?;
2110        }
2111        if !value.task_id.is_empty() {
2112            config = config.with_task_id(value.task_id)?;
2113        }
2114        if let Some(token) = value.token {
2115            config = config.with_token(A2aSecret::new(token)?);
2116        }
2117        if let Some(authentication) = value.authentication {
2118            config =
2119                config.with_authentication(A2aPushAuthentication::try_from_wire(authentication)?);
2120        }
2121        Ok(config)
2122    }
2123
2124    pub(crate) fn into_wire(self) -> wire::TaskPushNotificationConfig {
2125        wire::TaskPushNotificationConfig {
2126            url: self.url.into(),
2127            id: self.id.map(Into::into),
2128            task_id: self.task_id.map(Into::into).unwrap_or_default(),
2129            token: self.token.map(|token| token.expose_secret().to_string()),
2130            authentication: self.authentication.map(A2aPushAuthentication::into_wire),
2131            tenant: None,
2132        }
2133    }
2134
2135    pub(crate) fn into_wire_for_tenant(
2136        self,
2137        tenant: Option<String>,
2138    ) -> wire::TaskPushNotificationConfig {
2139        let mut value = self.into_wire();
2140        value.tenant = tenant;
2141        value
2142    }
2143}
2144
2145impl fmt::Debug for A2aPushConfig {
2146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2147        formatter
2148            .debug_struct("A2aPushConfig")
2149            .field("url", &"[REDACTED]")
2150            .field("id", &self.id)
2151            .field("task_id", &self.task_id)
2152            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
2153            .field("authentication", &self.authentication)
2154            .finish()
2155    }
2156}
2157
2158/// Request to read a push configuration after task authorization.
2159#[derive(Clone, Debug, Eq, PartialEq)]
2160pub struct A2aGetPushConfigRequest {
2161    task_id: Box<str>,
2162    config_id: Box<str>,
2163}
2164
2165impl A2aGetPushConfigRequest {
2166    /// Constructs a lookup request.
2167    pub fn new(
2168        task_id: impl Into<String>,
2169        config_id: impl Into<String>,
2170    ) -> Result<Self, A2aContractError> {
2171        let task_id = task_id.into();
2172        let config_id = config_id.into();
2173        validate_required_text("task id", &task_id, MAX_ID_BYTES)?;
2174        validate_required_text("push config id", &config_id, MAX_ID_BYTES)?;
2175        Ok(Self {
2176            task_id: task_id.into_boxed_str(),
2177            config_id: config_id.into_boxed_str(),
2178        })
2179    }
2180
2181    /// Returns the task identifier.
2182    #[must_use]
2183    pub fn task_id(&self) -> &str {
2184        &self.task_id
2185    }
2186
2187    /// Returns the configuration identifier.
2188    #[must_use]
2189    pub fn config_id(&self) -> &str {
2190        &self.config_id
2191    }
2192
2193    pub(crate) fn try_from_wire(
2194        value: wire::GetTaskPushNotificationConfigRequest,
2195    ) -> Result<Self, A2aContractError> {
2196        if value.tenant.is_some() {
2197            return Err(A2aContractError::Unsupported {
2198                field: "request tenant override",
2199                value: "tenant".to_string(),
2200            });
2201        }
2202        Self::new(value.task_id, value.id)
2203    }
2204
2205    pub(crate) fn into_get_wire(
2206        self,
2207        tenant: Option<String>,
2208    ) -> wire::GetTaskPushNotificationConfigRequest {
2209        wire::GetTaskPushNotificationConfigRequest {
2210            task_id: self.task_id.into(),
2211            id: self.config_id.into(),
2212            tenant,
2213        }
2214    }
2215
2216    pub(crate) fn into_delete_wire(
2217        self,
2218        tenant: Option<String>,
2219    ) -> wire::DeleteTaskPushNotificationConfigRequest {
2220        wire::DeleteTaskPushNotificationConfigRequest {
2221            task_id: self.task_id.into(),
2222            id: self.config_id.into(),
2223            tenant,
2224        }
2225    }
2226}
2227
2228/// Bounded request to list push configurations for one task.
2229#[derive(Clone, Debug, Eq, PartialEq)]
2230pub struct A2aListPushConfigsRequest {
2231    task_id: Box<str>,
2232    page_size: u16,
2233    page_token: Option<Box<str>>,
2234}
2235
2236impl A2aListPushConfigsRequest {
2237    /// Constructs a first-page request.
2238    pub fn new(task_id: impl Into<String>) -> Result<Self, A2aContractError> {
2239        let task_id = task_id.into();
2240        validate_required_text("task id", &task_id, MAX_ID_BYTES)?;
2241        Ok(Self {
2242            task_id: task_id.into_boxed_str(),
2243            page_size: 50,
2244            page_token: None,
2245        })
2246    }
2247
2248    /// Sets a bounded page size.
2249    pub fn with_page_size(mut self, value: u16) -> Result<Self, A2aContractError> {
2250        if value == 0 || value > 256 {
2251            return Err(A2aContractError::InvalidLifecycle(
2252                "push-config page size is outside the supported range",
2253            ));
2254        }
2255        self.page_size = value;
2256        Ok(self)
2257    }
2258
2259    /// Sets an opaque continuation cursor.
2260    pub fn with_page_token(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
2261        let value = value.into();
2262        validate_required_text("page token", &value, MAX_ID_BYTES * 4)?;
2263        self.page_token = Some(value.into_boxed_str());
2264        Ok(self)
2265    }
2266
2267    /// Returns the task identifier.
2268    #[must_use]
2269    pub fn task_id(&self) -> &str {
2270        &self.task_id
2271    }
2272
2273    /// Returns the effective page size.
2274    #[must_use]
2275    pub const fn page_size(&self) -> u16 {
2276        self.page_size
2277    }
2278
2279    /// Returns the opaque continuation cursor.
2280    #[must_use]
2281    pub fn page_token(&self) -> Option<&str> {
2282        self.page_token.as_deref()
2283    }
2284
2285    pub(crate) fn try_from_wire(
2286        value: wire::ListTaskPushNotificationConfigsRequest,
2287    ) -> Result<Self, A2aContractError> {
2288        if value.tenant.is_some() {
2289            return Err(A2aContractError::Unsupported {
2290                field: "request tenant override",
2291                value: "tenant".to_string(),
2292            });
2293        }
2294        let mut request = Self::new(value.task_id)?;
2295        if let Some(page_size) = value.page_size {
2296            request = request.with_page_size(u16::try_from(page_size).map_err(|_| {
2297                A2aContractError::InvalidLifecycle(
2298                    "push-config page size is outside the supported range",
2299                )
2300            })?)?;
2301        }
2302        if let Some(page_token) = value.page_token {
2303            request = request.with_page_token(page_token)?;
2304        }
2305        Ok(request)
2306    }
2307
2308    pub(crate) fn into_wire(
2309        self,
2310        tenant: Option<String>,
2311    ) -> wire::ListTaskPushNotificationConfigsRequest {
2312        wire::ListTaskPushNotificationConfigsRequest {
2313            task_id: self.task_id.into(),
2314            page_size: Some(i32::from(self.page_size)),
2315            page_token: self.page_token.map(Into::into),
2316            tenant,
2317        }
2318    }
2319}
2320
2321/// One stable page of push configurations.
2322#[derive(Clone, Debug, PartialEq)]
2323pub struct A2aPushConfigPage {
2324    configs: Vec<A2aPushConfig>,
2325    next_page_token: Option<Box<str>>,
2326}
2327
2328impl A2aPushConfigPage {
2329    /// Constructs a bounded page.
2330    pub fn new(
2331        configs: Vec<A2aPushConfig>,
2332        next_page_token: Option<String>,
2333    ) -> Result<Self, A2aContractError> {
2334        validate_count("push config page", configs.len(), 256)?;
2335        if let Some(token) = next_page_token.as_deref() {
2336            validate_required_text("page token", token, MAX_ID_BYTES * 4)?;
2337        }
2338        Ok(Self {
2339            configs,
2340            next_page_token: next_page_token.map(String::into_boxed_str),
2341        })
2342    }
2343
2344    /// Returns configurations in stable backend order.
2345    #[must_use]
2346    pub fn configs(&self) -> &[A2aPushConfig] {
2347        &self.configs
2348    }
2349
2350    /// Returns the continuation cursor.
2351    #[must_use]
2352    pub fn next_page_token(&self) -> Option<&str> {
2353        self.next_page_token.as_deref()
2354    }
2355
2356    pub(crate) fn into_wire(self) -> wire::ListTaskPushNotificationConfigsResponse {
2357        wire::ListTaskPushNotificationConfigsResponse {
2358            configs: self
2359                .configs
2360                .into_iter()
2361                .map(A2aPushConfig::into_wire)
2362                .collect(),
2363            next_page_token: self.next_page_token.map(Into::into),
2364        }
2365    }
2366
2367    pub(crate) fn try_from_wire(
2368        value: wire::ListTaskPushNotificationConfigsResponse,
2369    ) -> Result<Self, A2aContractError> {
2370        let configs = value
2371            .configs
2372            .into_iter()
2373            .map(A2aPushConfig::try_from_wire)
2374            .collect::<Result<Vec<_>, _>>()?;
2375        Self::new(configs, value.next_page_token)
2376    }
2377}
2378
2379/// Request to delete one push configuration.
2380pub type A2aDeletePushConfigRequest = A2aGetPushConfigRequest;
2381
2382/// Ordered task stream event.
2383#[derive(Clone, Debug, PartialEq)]
2384#[non_exhaustive]
2385pub enum A2aStreamEvent {
2386    /// Complete task snapshot.
2387    Task(A2aTask),
2388    /// Direct message response.
2389    Message(A2aMessage),
2390    /// Task status transition.
2391    StatusUpdate(A2aStatusUpdate),
2392    /// Artifact or artifact chunk update.
2393    ArtifactUpdate(A2aArtifactUpdate),
2394}
2395
2396impl A2aStreamEvent {
2397    /// Returns whether this event commits a terminal task state.
2398    #[must_use]
2399    pub fn is_terminal(&self) -> bool {
2400        match self {
2401            Self::Task(task) => task.state().is_terminal(),
2402            Self::StatusUpdate(update) => update.status.state().is_terminal(),
2403            Self::Message(_) | Self::ArtifactUpdate(_) => false,
2404        }
2405    }
2406
2407    pub(crate) fn into_wire(self) -> wire::StreamResponse {
2408        match self {
2409            Self::Task(task) => wire::StreamResponse::Task(task.into_wire()),
2410            Self::Message(message) => wire::StreamResponse::Message(message.into_wire()),
2411            Self::StatusUpdate(update) => wire::StreamResponse::StatusUpdate(update.into_wire()),
2412            Self::ArtifactUpdate(update) => {
2413                wire::StreamResponse::ArtifactUpdate(update.into_wire())
2414            }
2415        }
2416    }
2417
2418    pub(crate) fn try_from_wire(value: wire::StreamResponse) -> Result<Self, A2aContractError> {
2419        match value {
2420            wire::StreamResponse::Task(task) => Ok(Self::Task(A2aTask::try_from_wire(task)?)),
2421            wire::StreamResponse::Message(message) => {
2422                Ok(Self::Message(A2aMessage::try_from_wire(message)?))
2423            }
2424            wire::StreamResponse::StatusUpdate(update) => {
2425                Ok(Self::StatusUpdate(A2aStatusUpdate::try_from_wire(update)?))
2426            }
2427            wire::StreamResponse::ArtifactUpdate(update) => Ok(Self::ArtifactUpdate(
2428                A2aArtifactUpdate::try_from_wire(update)?,
2429            )),
2430        }
2431    }
2432}
2433
2434/// Task status update with exact task/context identity.
2435#[derive(Clone, Debug, PartialEq)]
2436pub struct A2aStatusUpdate {
2437    task_id: Box<str>,
2438    context_id: Box<str>,
2439    status: A2aTaskStatus,
2440    metadata: Option<HashMap<String, Value>>,
2441}
2442
2443impl A2aStatusUpdate {
2444    /// Constructs an ordered status update.
2445    pub fn new(
2446        task_id: impl Into<String>,
2447        context_id: impl Into<String>,
2448        status: A2aTaskStatus,
2449    ) -> Result<Self, A2aContractError> {
2450        let task_id = task_id.into();
2451        let context_id = context_id.into();
2452        validate_required_text("task id", &task_id, MAX_ID_BYTES)?;
2453        validate_required_text("context id", &context_id, MAX_ID_BYTES)?;
2454        Ok(Self {
2455            task_id: task_id.into_boxed_str(),
2456            context_id: context_id.into_boxed_str(),
2457            status,
2458            metadata: None,
2459        })
2460    }
2461
2462    /// Adds bounded event metadata.
2463    pub fn with_metadata(
2464        mut self,
2465        metadata: HashMap<String, Value>,
2466    ) -> Result<Self, A2aContractError> {
2467        validate_metadata("status update metadata", Some(&metadata))?;
2468        self.metadata = Some(metadata);
2469        Ok(self)
2470    }
2471
2472    /// Returns the task identifier.
2473    #[must_use]
2474    pub fn task_id(&self) -> &str {
2475        &self.task_id
2476    }
2477
2478    /// Returns the context identifier.
2479    #[must_use]
2480    pub fn context_id(&self) -> &str {
2481        &self.context_id
2482    }
2483
2484    /// Returns the task status.
2485    #[must_use]
2486    pub const fn status(&self) -> &A2aTaskStatus {
2487        &self.status
2488    }
2489
2490    fn into_wire(self) -> wire::TaskStatusUpdateEvent {
2491        wire::TaskStatusUpdateEvent {
2492            task_id: self.task_id.into(),
2493            context_id: self.context_id.into(),
2494            status: self.status.into_wire(),
2495            metadata: self.metadata,
2496        }
2497    }
2498
2499    fn try_from_wire(value: wire::TaskStatusUpdateEvent) -> Result<Self, A2aContractError> {
2500        let mut update = Self::new(
2501            value.task_id,
2502            value.context_id,
2503            A2aTaskStatus::try_from_wire(value.status)?,
2504        )?;
2505        if let Some(metadata) = value.metadata {
2506            update = update.with_metadata(metadata)?;
2507        }
2508        Ok(update)
2509    }
2510}
2511
2512/// Artifact update or ordered artifact chunk.
2513#[derive(Clone, Debug, PartialEq)]
2514pub struct A2aArtifactUpdate {
2515    task_id: Box<str>,
2516    context_id: Box<str>,
2517    artifact: A2aArtifact,
2518    append: bool,
2519    last_chunk: bool,
2520    metadata: Option<HashMap<String, Value>>,
2521}
2522
2523impl A2aArtifactUpdate {
2524    /// Constructs an artifact update.
2525    pub fn new(
2526        task_id: impl Into<String>,
2527        context_id: impl Into<String>,
2528        artifact: A2aArtifact,
2529    ) -> Result<Self, A2aContractError> {
2530        let task_id = task_id.into();
2531        let context_id = context_id.into();
2532        validate_required_text("task id", &task_id, MAX_ID_BYTES)?;
2533        validate_required_text("context id", &context_id, MAX_ID_BYTES)?;
2534        Ok(Self {
2535            task_id: task_id.into_boxed_str(),
2536            context_id: context_id.into_boxed_str(),
2537            artifact,
2538            append: false,
2539            last_chunk: true,
2540            metadata: None,
2541        })
2542    }
2543
2544    /// Marks this event as an append chunk and declares whether it is final.
2545    #[must_use]
2546    pub const fn as_chunk(mut self, last_chunk: bool) -> Self {
2547        self.append = true;
2548        self.last_chunk = last_chunk;
2549        self
2550    }
2551
2552    /// Marks this event as the first, non-final chunk of a new or replaced artifact.
2553    /// Subsequent chunks must use [`Self::as_chunk`].
2554    #[must_use]
2555    pub const fn as_initial_chunk(mut self) -> Self {
2556        self.append = false;
2557        self.last_chunk = false;
2558        self
2559    }
2560
2561    /// Adds bounded event metadata.
2562    pub fn with_metadata(
2563        mut self,
2564        metadata: HashMap<String, Value>,
2565    ) -> Result<Self, A2aContractError> {
2566        validate_metadata("artifact update metadata", Some(&metadata))?;
2567        self.metadata = Some(metadata);
2568        Ok(self)
2569    }
2570
2571    /// Returns the task identifier.
2572    #[must_use]
2573    pub fn task_id(&self) -> &str {
2574        &self.task_id
2575    }
2576
2577    /// Returns the context identifier.
2578    #[must_use]
2579    pub fn context_id(&self) -> &str {
2580        &self.context_id
2581    }
2582
2583    /// Returns the artifact projection.
2584    #[must_use]
2585    pub const fn artifact(&self) -> &A2aArtifact {
2586        &self.artifact
2587    }
2588
2589    /// Returns whether this event appends to an existing artifact.
2590    #[must_use]
2591    pub const fn append(&self) -> bool {
2592        self.append
2593    }
2594
2595    /// Returns whether this is the final artifact chunk.
2596    #[must_use]
2597    pub const fn last_chunk(&self) -> bool {
2598        self.last_chunk
2599    }
2600
2601    fn into_wire(self) -> wire::TaskArtifactUpdateEvent {
2602        wire::TaskArtifactUpdateEvent {
2603            task_id: self.task_id.into(),
2604            context_id: self.context_id.into(),
2605            artifact: self.artifact.into_wire(),
2606            append: Some(self.append),
2607            last_chunk: Some(self.last_chunk),
2608            metadata: self.metadata,
2609        }
2610    }
2611
2612    fn try_from_wire(value: wire::TaskArtifactUpdateEvent) -> Result<Self, A2aContractError> {
2613        let append = value.append.unwrap_or(false);
2614        let last_chunk = value.last_chunk.unwrap_or(false);
2615        let mut update = Self::new(
2616            value.task_id,
2617            value.context_id,
2618            A2aArtifact::try_from_wire(value.artifact)?,
2619        )?;
2620        update.append = append;
2621        update.last_chunk = last_chunk;
2622        if let Some(metadata) = value.metadata {
2623            update = update.with_metadata(metadata)?;
2624        }
2625        Ok(update)
2626    }
2627}
2628
2629/// Transport binding supported by the `StateKnot` A2A v1 profile.
2630#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2631#[non_exhaustive]
2632pub enum A2aBinding {
2633    /// HTTP+JSON resource-oriented binding.
2634    HttpJson,
2635    /// JSON-RPC 2.0 over HTTP binding.
2636    JsonRpc,
2637}
2638
2639impl A2aBinding {
2640    /// Returns the exact Agent Card protocol-binding value.
2641    #[must_use]
2642    pub const fn as_str(self) -> &'static str {
2643        match self {
2644            Self::HttpJson => A2A_BINDING_HTTP_JSON,
2645            Self::JsonRpc => A2A_BINDING_JSONRPC,
2646        }
2647    }
2648}
2649
2650impl TryFrom<&str> for A2aBinding {
2651    type Error = A2aContractError;
2652
2653    fn try_from(value: &str) -> Result<Self, Self::Error> {
2654        match value {
2655            A2A_BINDING_HTTP_JSON => Ok(Self::HttpJson),
2656            A2A_BINDING_JSONRPC => Ok(Self::JsonRpc),
2657            other => Err(A2aContractError::Unsupported {
2658                field: "protocol binding",
2659                value: other.to_string(),
2660            }),
2661        }
2662    }
2663}
2664
2665/// One A2A endpoint advertised in preference order.
2666#[derive(Clone, Debug, Eq, PartialEq)]
2667pub struct A2aAgentInterface {
2668    url: Box<str>,
2669    binding: A2aBinding,
2670    tenant: Option<Box<str>>,
2671}
2672
2673impl A2aAgentInterface {
2674    /// Constructs an A2A 1.0 endpoint descriptor.
2675    pub fn new(url: impl Into<String>, binding: A2aBinding) -> Result<Self, A2aContractError> {
2676        let url = url.into();
2677        validate_url("agent interface", &url)?;
2678        Ok(Self {
2679            url: url.into_boxed_str(),
2680            binding,
2681            tenant: None,
2682        })
2683    }
2684
2685    /// Binds the opaque routing tenant required by this interface.
2686    pub fn with_tenant(mut self, tenant: impl Into<String>) -> Result<Self, A2aContractError> {
2687        let tenant = tenant.into();
2688        validate_required_text("interface tenant", &tenant, MAX_ID_BYTES)?;
2689        self.tenant = Some(tenant.into_boxed_str());
2690        Ok(self)
2691    }
2692
2693    /// Returns the endpoint URL.
2694    #[must_use]
2695    pub fn url(&self) -> &str {
2696        &self.url
2697    }
2698
2699    /// Returns the supported binding.
2700    #[must_use]
2701    pub const fn binding(&self) -> A2aBinding {
2702        self.binding
2703    }
2704
2705    /// Returns the opaque routing tenant advertised for this interface.
2706    #[must_use]
2707    pub fn tenant(&self) -> Option<&str> {
2708        self.tenant.as_deref()
2709    }
2710
2711    pub(crate) fn try_from_wire(value: wire::AgentInterface) -> Result<Self, A2aContractError> {
2712        if value.protocol_version != A2A_PROTOCOL_VERSION_1_0 {
2713            return Err(A2aContractError::Unsupported {
2714                field: "protocol version",
2715                value: value.protocol_version,
2716            });
2717        }
2718        let tenant = value.tenant;
2719        let mut interface = Self::new(
2720            value.url,
2721            A2aBinding::try_from(value.protocol_binding.as_str())?,
2722        )?;
2723        if let Some(tenant) = tenant {
2724            interface = interface.with_tenant(tenant)?;
2725        }
2726        Ok(interface)
2727    }
2728
2729    fn into_wire(self) -> wire::AgentInterface {
2730        wire::AgentInterface {
2731            url: self.url.into(),
2732            protocol_binding: self.binding.as_str().to_string(),
2733            protocol_version: A2A_PROTOCOL_VERSION_1_0.to_string(),
2734            tenant: self.tenant.map(Into::into),
2735        }
2736    }
2737}
2738
2739fn validate_wire_interface(value: &wire::AgentInterface) -> Result<(), A2aContractError> {
2740    validate_required_text("agent interface address", &value.url, MAX_URL_BYTES)?;
2741    validate_required_text(
2742        "protocol binding",
2743        value.protocol_binding.as_str(),
2744        MAX_LABEL_BYTES,
2745    )?;
2746    validate_required_text(
2747        "protocol version",
2748        value.protocol_version.as_str(),
2749        MAX_LABEL_BYTES,
2750    )?;
2751    validate_optional_text("interface tenant", value.tenant.as_deref(), MAX_ID_BYTES)?;
2752    if A2aBinding::try_from(value.protocol_binding.as_str()).is_ok() {
2753        validate_url("agent interface", &value.url)?;
2754    }
2755    Ok(())
2756}
2757
2758/// A declared A2A extension.
2759#[derive(Clone, Debug, PartialEq)]
2760pub struct A2aAgentExtension {
2761    uri: Box<str>,
2762    description: Option<Box<str>>,
2763    required: bool,
2764    parameters: Option<HashMap<String, Value>>,
2765}
2766
2767impl A2aAgentExtension {
2768    /// Constructs an extension declaration by absolute URI.
2769    pub fn new(uri: impl Into<String>) -> Result<Self, A2aContractError> {
2770        let uri = uri.into();
2771        validate_url("extension", &uri)?;
2772        Ok(Self {
2773            uri: uri.into_boxed_str(),
2774            description: None,
2775            required: false,
2776            parameters: None,
2777        })
2778    }
2779
2780    /// Adds a public description.
2781    pub fn with_description(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
2782        let value = value.into();
2783        validate_required_text("extension description", &value, MAX_DESCRIPTION_BYTES)?;
2784        self.description = Some(value.into_boxed_str());
2785        Ok(self)
2786    }
2787
2788    /// Marks support for this extension as required for interoperable calls.
2789    #[must_use]
2790    pub const fn required(mut self, value: bool) -> Self {
2791        self.required = value;
2792        self
2793    }
2794
2795    /// Adds bounded extension parameters. Parameters remain inert data.
2796    pub fn with_parameters(
2797        mut self,
2798        value: HashMap<String, Value>,
2799    ) -> Result<Self, A2aContractError> {
2800        validate_metadata("extension parameters", Some(&value))?;
2801        self.parameters = Some(value);
2802        Ok(self)
2803    }
2804
2805    /// Returns the exact extension URI.
2806    #[must_use]
2807    pub fn uri(&self) -> &str {
2808        &self.uri
2809    }
2810
2811    /// Returns whether clients must request this extension.
2812    #[must_use]
2813    pub const fn is_required(&self) -> bool {
2814        self.required
2815    }
2816
2817    fn try_from_wire(value: wire::AgentExtension) -> Result<Self, A2aContractError> {
2818        let mut extension = Self::new(value.uri)?;
2819        if let Some(description) = value.description {
2820            extension = extension.with_description(description)?;
2821        }
2822        extension.required = value.required.unwrap_or(false);
2823        if let Some(parameters) = value.params {
2824            extension = extension.with_parameters(parameters)?;
2825        }
2826        Ok(extension)
2827    }
2828
2829    fn into_wire(self) -> wire::AgentExtension {
2830        wire::AgentExtension {
2831            uri: self.uri.into(),
2832            description: self.description.map(Into::into),
2833            required: self.required.then_some(true),
2834            params: self.parameters,
2835        }
2836    }
2837}
2838
2839/// Honest capability flags advertised by an Agent Card.
2840#[derive(Clone, Debug, Default, PartialEq)]
2841pub struct A2aAgentCapabilities {
2842    streaming: bool,
2843    push_notifications: bool,
2844    extended_agent_card: bool,
2845    extensions: Vec<A2aAgentExtension>,
2846}
2847
2848impl A2aAgentCapabilities {
2849    /// Constructs an empty capability set.
2850    #[must_use]
2851    pub const fn new() -> Self {
2852        Self {
2853            streaming: false,
2854            push_notifications: false,
2855            extended_agent_card: false,
2856            extensions: Vec::new(),
2857        }
2858    }
2859
2860    /// Advertises durable streaming/subscription support.
2861    #[must_use]
2862    pub const fn streaming(mut self, value: bool) -> Self {
2863        self.streaming = value;
2864        self
2865    }
2866
2867    /// Advertises durable push-configuration and delivery support.
2868    #[must_use]
2869    pub const fn push_notifications(mut self, value: bool) -> Self {
2870        self.push_notifications = value;
2871        self
2872    }
2873
2874    /// Advertises an authenticated extended Agent Card.
2875    #[must_use]
2876    pub const fn extended_agent_card(mut self, value: bool) -> Self {
2877        self.extended_agent_card = value;
2878        self
2879    }
2880
2881    /// Adds one declared extension.
2882    pub fn with_extension(
2883        mut self,
2884        extension: A2aAgentExtension,
2885    ) -> Result<Self, A2aContractError> {
2886        if self.extensions.len() == MAX_EXTENSIONS {
2887            return Err(A2aContractError::TooMany {
2888                field: "agent extensions",
2889                maximum: MAX_EXTENSIONS,
2890                actual: self.extensions.len() + 1,
2891            });
2892        }
2893        if self
2894            .extensions
2895            .iter()
2896            .any(|existing| existing.uri == extension.uri)
2897        {
2898            return Err(A2aContractError::InvalidLifecycle(
2899                "duplicate Agent Card extension URI",
2900            ));
2901        }
2902        self.extensions.push(extension);
2903        Ok(self)
2904    }
2905
2906    /// Returns whether streaming is advertised.
2907    #[must_use]
2908    pub const fn supports_streaming(&self) -> bool {
2909        self.streaming
2910    }
2911
2912    /// Returns whether push notifications are advertised.
2913    #[must_use]
2914    pub const fn supports_push_notifications(&self) -> bool {
2915        self.push_notifications
2916    }
2917
2918    /// Returns whether an extended Agent Card is advertised.
2919    #[must_use]
2920    pub const fn supports_extended_agent_card(&self) -> bool {
2921        self.extended_agent_card
2922    }
2923
2924    /// Returns declared extensions in preference order.
2925    #[must_use]
2926    pub fn extensions(&self) -> &[A2aAgentExtension] {
2927        &self.extensions
2928    }
2929
2930    fn try_from_wire(value: wire::AgentCapabilities) -> Result<Self, A2aContractError> {
2931        let extensions = value
2932            .extensions
2933            .unwrap_or_default()
2934            .into_iter()
2935            .map(A2aAgentExtension::try_from_wire)
2936            .collect::<Result<Vec<_>, _>>()?;
2937        validate_count("agent extensions", extensions.len(), MAX_EXTENSIONS)?;
2938        let mut seen = std::collections::HashSet::new();
2939        if extensions
2940            .iter()
2941            .any(|extension| !seen.insert(extension.uri().to_string()))
2942        {
2943            return Err(A2aContractError::InvalidLifecycle(
2944                "duplicate Agent Card extension URI",
2945            ));
2946        }
2947        Ok(Self {
2948            streaming: value.streaming.unwrap_or(false),
2949            push_notifications: value.push_notifications.unwrap_or(false),
2950            extended_agent_card: value.extended_agent_card.unwrap_or(false),
2951            extensions,
2952        })
2953    }
2954
2955    fn into_wire(self) -> wire::AgentCapabilities {
2956        wire::AgentCapabilities {
2957            streaming: Some(self.streaming),
2958            push_notifications: Some(self.push_notifications),
2959            extensions: (!self.extensions.is_empty()).then_some(
2960                self.extensions
2961                    .into_iter()
2962                    .map(A2aAgentExtension::into_wire)
2963                    .collect(),
2964            ),
2965            extended_agent_card: Some(self.extended_agent_card),
2966        }
2967    }
2968}
2969
2970/// One discoverable agent skill. Mapping to a local executable capability is
2971/// an explicit deployment decision; the external ID is never normalized into
2972/// a `StateKnot` capability name.
2973#[derive(Clone, Debug, PartialEq)]
2974pub struct A2aAgentSkill {
2975    inner: wire::AgentSkill,
2976}
2977
2978impl A2aAgentSkill {
2979    /// Constructs a skill descriptor.
2980    pub fn new(
2981        id: impl Into<String>,
2982        name: impl Into<String>,
2983        description: impl Into<String>,
2984        tags: Vec<String>,
2985    ) -> Result<Self, A2aContractError> {
2986        let id = id.into();
2987        let name = name.into();
2988        let description = description.into();
2989        validate_required_text("skill id", &id, MAX_ID_BYTES)?;
2990        validate_required_text("skill name", &name, MAX_LABEL_BYTES)?;
2991        validate_required_text("skill description", &description, MAX_DESCRIPTION_BYTES)?;
2992        validate_string_list("skill tags", &tags, MAX_TAGS, MAX_LABEL_BYTES)?;
2993        Ok(Self {
2994            inner: wire::AgentSkill {
2995                id,
2996                name,
2997                description,
2998                tags,
2999                examples: None,
3000                input_modes: None,
3001                output_modes: None,
3002                security_requirements: None,
3003            },
3004        })
3005    }
3006
3007    /// Adds bounded examples.
3008    pub fn with_examples(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
3009        validate_string_list(
3010            "skill examples",
3011            &values,
3012            MAX_EXAMPLES,
3013            MAX_DESCRIPTION_BYTES,
3014        )?;
3015        self.inner.examples = Some(values);
3016        Ok(self)
3017    }
3018
3019    /// Narrows accepted input media modes.
3020    pub fn with_input_modes(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
3021        validate_modes("skill input modes", &values)?;
3022        self.inner.input_modes = Some(values);
3023        Ok(self)
3024    }
3025
3026    /// Narrows produced output media modes.
3027    pub fn with_output_modes(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
3028        validate_modes("skill output modes", &values)?;
3029        self.inner.output_modes = Some(values);
3030        Ok(self)
3031    }
3032
3033    /// Sets skill-specific security requirements.
3034    pub fn with_security_requirements(
3035        mut self,
3036        values: Vec<HashMap<String, Vec<String>>>,
3037    ) -> Result<Self, A2aContractError> {
3038        validate_security_requirements(&values)?;
3039        self.inner.security_requirements = Some(values);
3040        Ok(self)
3041    }
3042
3043    /// Returns the exact external skill identifier.
3044    #[must_use]
3045    pub fn id(&self) -> &str {
3046        &self.inner.id
3047    }
3048
3049    /// Returns skill-specific input modes; an empty slice means card defaults.
3050    #[must_use]
3051    pub fn input_modes(&self) -> &[String] {
3052        self.inner.input_modes.as_deref().unwrap_or_default()
3053    }
3054
3055    /// Returns skill-specific output modes; an empty slice means card defaults.
3056    #[must_use]
3057    pub fn output_modes(&self) -> &[String] {
3058        self.inner.output_modes.as_deref().unwrap_or_default()
3059    }
3060
3061    pub(crate) fn security_requirements(&self) -> Option<&[wire::SecurityRequirement]> {
3062        self.inner.security_requirements.as_deref()
3063    }
3064
3065    fn try_from_wire(value: wire::AgentSkill) -> Result<Self, A2aContractError> {
3066        let mut skill = Self::new(value.id, value.name, value.description, value.tags)?;
3067        if let Some(examples) = value.examples {
3068            skill = skill.with_examples(examples)?;
3069        }
3070        if let Some(modes) = value.input_modes {
3071            skill = skill.with_input_modes(modes)?;
3072        }
3073        if let Some(modes) = value.output_modes {
3074            skill = skill.with_output_modes(modes)?;
3075        }
3076        if let Some(requirements) = value.security_requirements {
3077            skill = skill.with_security_requirements(requirements)?;
3078        }
3079        Ok(skill)
3080    }
3081
3082    fn into_wire(self) -> wire::AgentSkill {
3083        self.inner
3084    }
3085}
3086
3087/// Bounded A2A security scheme. The inner SDK representation remains private.
3088#[derive(Clone, Debug, PartialEq)]
3089pub struct A2aSecurityScheme {
3090    inner: wire::SecurityScheme,
3091}
3092
3093impl A2aSecurityScheme {
3094    /// Constructs an HTTP Bearer scheme.
3095    pub fn http_bearer(
3096        bearer_format: Option<String>,
3097        description: Option<String>,
3098    ) -> Result<Self, A2aContractError> {
3099        validate_optional_text("bearer format", bearer_format.as_deref(), MAX_LABEL_BYTES)?;
3100        validate_optional_text(
3101            "security description",
3102            description.as_deref(),
3103            MAX_DESCRIPTION_BYTES,
3104        )?;
3105        Ok(Self {
3106            inner: wire::SecurityScheme::HttpAuth(wire::HttpAuthSecurityScheme {
3107                scheme: "Bearer".to_string(),
3108                description,
3109                bearer_format,
3110            }),
3111        })
3112    }
3113
3114    /// Constructs an `OpenID` Connect discovery scheme.
3115    pub fn open_id_connect(
3116        discovery_url: impl Into<String>,
3117        description: Option<String>,
3118    ) -> Result<Self, A2aContractError> {
3119        let discovery_url = discovery_url.into();
3120        validate_url("OpenID Connect discovery", &discovery_url)?;
3121        validate_optional_text(
3122            "security description",
3123            description.as_deref(),
3124            MAX_DESCRIPTION_BYTES,
3125        )?;
3126        Ok(Self {
3127            inner: wire::SecurityScheme::OpenIdConnect(wire::OpenIdConnectSecurityScheme {
3128                open_id_connect_url: discovery_url,
3129                description,
3130            }),
3131        })
3132    }
3133
3134    /// Validates and preserves any standard A2A 1.0 security-scheme JSON.
3135    pub fn from_json(value: Value) -> Result<Self, A2aContractError> {
3136        validate_json("security scheme", &value, MAX_METADATA_BYTES)?;
3137        let inner = serde_json::from_value(value).map_err(|_| A2aContractError::InvalidJson {
3138            field: "security scheme",
3139        })?;
3140        validate_security_scheme(&inner)?;
3141        Ok(Self { inner })
3142    }
3143
3144    /// Returns the standard A2A JSON form without secret material.
3145    pub fn to_json(&self) -> Result<Value, A2aContractError> {
3146        serde_json::to_value(&self.inner).map_err(|_| A2aContractError::InvalidJson {
3147            field: "security scheme",
3148        })
3149    }
3150
3151    fn into_wire(self) -> wire::SecurityScheme {
3152        self.inner
3153    }
3154}
3155
3156fn validate_security_scheme(value: &wire::SecurityScheme) -> Result<(), A2aContractError> {
3157    match value {
3158        wire::SecurityScheme::ApiKey(value) => {
3159            validate_required_text("API key location", &value.location, MAX_LABEL_BYTES)?;
3160            validate_required_text("API key name", &value.name, MAX_LABEL_BYTES)?;
3161            validate_optional_text(
3162                "security description",
3163                value.description.as_deref(),
3164                MAX_DESCRIPTION_BYTES,
3165            )?;
3166        }
3167        wire::SecurityScheme::HttpAuth(value) => {
3168            validate_required_text("HTTP authentication scheme", &value.scheme, MAX_LABEL_BYTES)?;
3169            validate_optional_text(
3170                "security description",
3171                value.description.as_deref(),
3172                MAX_DESCRIPTION_BYTES,
3173            )?;
3174            validate_optional_text(
3175                "bearer format",
3176                value.bearer_format.as_deref(),
3177                MAX_LABEL_BYTES,
3178            )?;
3179        }
3180        wire::SecurityScheme::OAuth2(value) => {
3181            validate_optional_text(
3182                "security description",
3183                value.description.as_deref(),
3184                MAX_DESCRIPTION_BYTES,
3185            )?;
3186            if let Some(url) = value.oauth2_metadata_url.as_deref() {
3187                validate_url("OAuth metadata", url)?;
3188            }
3189            validate_oauth_flow(&value.flows)?;
3190        }
3191        wire::SecurityScheme::OpenIdConnect(value) => {
3192            validate_url("OpenID Connect discovery", &value.open_id_connect_url)?;
3193            validate_optional_text(
3194                "security description",
3195                value.description.as_deref(),
3196                MAX_DESCRIPTION_BYTES,
3197            )?;
3198        }
3199        wire::SecurityScheme::MutualTls(value) => {
3200            validate_optional_text(
3201                "security description",
3202                value.description.as_deref(),
3203                MAX_DESCRIPTION_BYTES,
3204            )?;
3205        }
3206    }
3207    Ok(())
3208}
3209
3210fn validate_oauth_flow(value: &wire::OAuthFlows) -> Result<(), A2aContractError> {
3211    match value {
3212        wire::OAuthFlows::AuthorizationCode(flow) => {
3213            validate_url("OAuth authorization", &flow.authorization_url)?;
3214            validate_url("OAuth token", &flow.token_url)?;
3215            validate_scope_map(&flow.scopes)?;
3216            if let Some(url) = flow.refresh_url.as_deref() {
3217                validate_url("OAuth refresh", url)?;
3218            }
3219        }
3220        wire::OAuthFlows::ClientCredentials(flow) => {
3221            validate_url("OAuth token", &flow.token_url)?;
3222            validate_scope_map(&flow.scopes)?;
3223            if let Some(url) = flow.refresh_url.as_deref() {
3224                validate_url("OAuth refresh", url)?;
3225            }
3226        }
3227        wire::OAuthFlows::DeviceCode(flow) => {
3228            validate_url("OAuth device authorization", &flow.device_authorization_url)?;
3229            validate_url("OAuth token", &flow.token_url)?;
3230            validate_scope_map(&flow.scopes)?;
3231            if let Some(url) = flow.refresh_url.as_deref() {
3232                validate_url("OAuth refresh", url)?;
3233            }
3234        }
3235        wire::OAuthFlows::Implicit(flow) => {
3236            validate_url("OAuth authorization", &flow.authorization_url)?;
3237            validate_scope_map(&flow.scopes)?;
3238            if let Some(url) = flow.refresh_url.as_deref() {
3239                validate_url("OAuth refresh", url)?;
3240            }
3241        }
3242        wire::OAuthFlows::Password(flow) => {
3243            validate_url("OAuth token", &flow.token_url)?;
3244            validate_scope_map(&flow.scopes)?;
3245            if let Some(url) = flow.refresh_url.as_deref() {
3246                validate_url("OAuth refresh", url)?;
3247            }
3248        }
3249    }
3250    Ok(())
3251}
3252
3253fn validate_scope_map(scopes: &HashMap<String, String>) -> Result<(), A2aContractError> {
3254    validate_count("OAuth scopes", scopes.len(), MAX_SCOPES)?;
3255    for (scope, description) in scopes {
3256        validate_required_text("OAuth scope", scope, MAX_LABEL_BYTES)?;
3257        validate_required_text(
3258            "OAuth scope description",
3259            description,
3260            MAX_DESCRIPTION_BYTES,
3261        )?;
3262    }
3263    Ok(())
3264}
3265
3266fn validate_security_requirements(
3267    requirements: &[HashMap<String, Vec<String>>],
3268) -> Result<(), A2aContractError> {
3269    validate_count(
3270        "security requirements",
3271        requirements.len(),
3272        MAX_SECURITY_REQUIREMENTS,
3273    )?;
3274    for requirement in requirements {
3275        validate_count(
3276            "security requirement schemes",
3277            requirement.len(),
3278            MAX_SECURITY_SCHEMES,
3279        )?;
3280        for (name, scopes) in requirement {
3281            validate_required_text("security scheme name", name, MAX_LABEL_BYTES)?;
3282            validate_string_list("security scopes", scopes, MAX_SCOPES, MAX_LABEL_BYTES)?;
3283        }
3284    }
3285    Ok(())
3286}
3287
3288fn validate_security_requirement_references(
3289    requirements: &[HashMap<String, Vec<String>>],
3290    schemes: Option<&HashMap<String, wire::SecurityScheme>>,
3291) -> Result<(), A2aContractError> {
3292    for name in requirements.iter().flat_map(HashMap::keys) {
3293        if schemes.is_none_or(|schemes| !schemes.contains_key(name)) {
3294            return Err(A2aContractError::InvalidLifecycle(
3295                "security requirement references an unknown scheme",
3296            ));
3297        }
3298    }
3299    Ok(())
3300}
3301
3302/// Detached JWS signature declared on an Agent Card.
3303#[derive(Clone, Debug, PartialEq)]
3304pub struct A2aAgentCardSignature {
3305    inner: wire::AgentCardSignature,
3306}
3307
3308impl A2aAgentCardSignature {
3309    /// Constructs a bounded JWS signature record.
3310    pub fn new(
3311        protected: impl Into<String>,
3312        signature: impl Into<String>,
3313        header: Option<HashMap<String, Value>>,
3314    ) -> Result<Self, A2aContractError> {
3315        let protected = protected.into();
3316        let signature = signature.into();
3317        validate_required_text("card protected header", &protected, MAX_PART_BYTES)?;
3318        validate_required_text("card signature", &signature, MAX_PART_BYTES)?;
3319        validate_metadata("card signature header", header.as_ref())?;
3320        Ok(Self {
3321            inner: wire::AgentCardSignature {
3322                protected,
3323                signature,
3324                header,
3325            },
3326        })
3327    }
3328
3329    fn try_from_wire(value: wire::AgentCardSignature) -> Result<Self, A2aContractError> {
3330        Self::new(value.protected, value.signature, value.header)
3331    }
3332
3333    fn into_wire(self) -> wire::AgentCardSignature {
3334        self.inner
3335    }
3336}
3337
3338/// Validated public or extended A2A Agent Card.
3339#[derive(Clone, Debug, PartialEq)]
3340pub struct A2aAgentCard {
3341    inner: wire::AgentCard,
3342}
3343
3344impl A2aAgentCard {
3345    /// Begins an Agent Card with all required scalar fields.
3346    pub fn builder(
3347        name: impl Into<String>,
3348        description: impl Into<String>,
3349        agent_version: impl Into<String>,
3350    ) -> Result<A2aAgentCardBuilder, A2aContractError> {
3351        let name = name.into();
3352        let description = description.into();
3353        let agent_version = agent_version.into();
3354        validate_required_text("agent name", &name, MAX_LABEL_BYTES)?;
3355        validate_required_text("agent description", &description, MAX_DESCRIPTION_BYTES)?;
3356        validate_required_text("agent version", &agent_version, MAX_LABEL_BYTES)?;
3357        Ok(A2aAgentCardBuilder {
3358            card: wire::AgentCard {
3359                name,
3360                description,
3361                version: agent_version,
3362                supported_interfaces: Vec::new(),
3363                capabilities: wire::AgentCapabilities::default(),
3364                default_input_modes: Vec::new(),
3365                default_output_modes: Vec::new(),
3366                skills: Vec::new(),
3367                provider: None,
3368                documentation_url: None,
3369                icon_url: None,
3370                security_schemes: None,
3371                security_requirements: None,
3372                signatures: None,
3373            },
3374        })
3375    }
3376
3377    /// Returns the display name.
3378    #[must_use]
3379    pub fn name(&self) -> &str {
3380        &self.inner.name
3381    }
3382
3383    /// Returns the serving agent's application version.
3384    #[must_use]
3385    pub fn agent_version(&self) -> &str {
3386        &self.inner.version
3387    }
3388
3389    /// Returns capabilities advertised by this exact card snapshot.
3390    #[must_use]
3391    pub fn capabilities(&self) -> A2aAgentCapabilities {
3392        A2aAgentCapabilities::try_from_wire(self.inner.capabilities.clone())
3393            .expect("A2aAgentCard construction validates capabilities")
3394    }
3395
3396    /// Returns StateKnot-supported A2A 1.0 interfaces in preference order.
3397    #[must_use]
3398    pub fn interfaces(&self) -> Vec<A2aAgentInterface> {
3399        self.inner
3400            .supported_interfaces
3401            .iter()
3402            .cloned()
3403            .filter_map(|interface| A2aAgentInterface::try_from_wire(interface).ok())
3404            .collect()
3405    }
3406
3407    /// Returns skill descriptors in declaration order.
3408    #[must_use]
3409    pub fn skills(&self) -> Vec<A2aAgentSkill> {
3410        self.inner
3411            .skills
3412            .iter()
3413            .cloned()
3414            .map(A2aAgentSkill::try_from_wire)
3415            .collect::<Result<Vec<_>, _>>()
3416            .expect("A2aAgentCard construction validates skills")
3417    }
3418
3419    /// Returns the card-wide accepted input modes in preference order.
3420    #[must_use]
3421    pub fn default_input_modes(&self) -> &[String] {
3422        &self.inner.default_input_modes
3423    }
3424
3425    /// Returns the card-wide produced output modes in preference order.
3426    #[must_use]
3427    pub fn default_output_modes(&self) -> &[String] {
3428        &self.inner.default_output_modes
3429    }
3430
3431    /// Returns the number of interfaces advertised, including unknown future
3432    /// bindings that are preserved for signature and digest verification.
3433    #[must_use]
3434    pub fn advertised_interface_count(&self) -> usize {
3435        self.inner.supported_interfaces.len()
3436    }
3437
3438    pub(crate) fn wire(&self) -> &wire::AgentCard {
3439        &self.inner
3440    }
3441
3442    /// Serializes the standard A2A 1.0 JSON representation.
3443    pub fn to_json(&self) -> Result<Value, A2aContractError> {
3444        serde_json::to_value(&self.inner).map_err(|_| A2aContractError::InvalidJson {
3445            field: "Agent Card",
3446        })
3447    }
3448
3449    /// Parses and validates the standard A2A 1.0 JSON representation.
3450    pub fn from_json(value: Value) -> Result<Self, A2aContractError> {
3451        validate_json("Agent Card", &value, MAX_PART_BYTES)?;
3452        let inner = serde_json::from_value(value).map_err(|_| A2aContractError::InvalidJson {
3453            field: "Agent Card",
3454        })?;
3455        Self::try_from_wire(inner)
3456    }
3457
3458    pub(crate) fn try_from_wire(inner: wire::AgentCard) -> Result<Self, A2aContractError> {
3459        validate_required_text("agent name", &inner.name, MAX_LABEL_BYTES)?;
3460        validate_required_text(
3461            "agent description",
3462            &inner.description,
3463            MAX_DESCRIPTION_BYTES,
3464        )?;
3465        validate_required_text("agent version", &inner.version, MAX_LABEL_BYTES)?;
3466        if inner.supported_interfaces.is_empty() {
3467            return Err(A2aContractError::Empty {
3468                field: "supported interfaces",
3469            });
3470        }
3471        validate_count(
3472            "supported interfaces",
3473            inner.supported_interfaces.len(),
3474            MAX_INTERFACES,
3475        )?;
3476        let mut interfaces = HashSet::with_capacity(inner.supported_interfaces.len());
3477        for interface in &inner.supported_interfaces {
3478            validate_wire_interface(interface)?;
3479            if !interfaces.insert((
3480                interface.url.as_str(),
3481                interface.protocol_binding.as_str(),
3482                interface.protocol_version.as_str(),
3483                interface.tenant.as_deref(),
3484            )) {
3485                return Err(A2aContractError::InvalidLifecycle(
3486                    "duplicate Agent Card interface",
3487                ));
3488            }
3489        }
3490        A2aAgentCapabilities::try_from_wire(inner.capabilities.clone())?;
3491        validate_modes("default input modes", &inner.default_input_modes)?;
3492        validate_modes("default output modes", &inner.default_output_modes)?;
3493        if inner.default_input_modes.is_empty() || inner.default_output_modes.is_empty() {
3494            return Err(A2aContractError::Empty {
3495                field: "default media modes",
3496            });
3497        }
3498        validate_count("agent skills", inner.skills.len(), MAX_SKILLS)?;
3499        let mut skill_ids = HashSet::with_capacity(inner.skills.len());
3500        for skill in inner.skills.iter().cloned() {
3501            let skill = A2aAgentSkill::try_from_wire(skill)?;
3502            if !skill_ids.insert(skill.id().to_owned()) {
3503                return Err(A2aContractError::InvalidLifecycle(
3504                    "duplicate Agent Skill identifier",
3505                ));
3506            }
3507        }
3508        if let Some(provider) = inner.provider.as_ref() {
3509            validate_required_text(
3510                "provider organization",
3511                &provider.organization,
3512                MAX_LABEL_BYTES,
3513            )?;
3514            validate_url("provider", &provider.url)?;
3515        }
3516        if let Some(url) = inner.documentation_url.as_deref() {
3517            validate_url("documentation", url)?;
3518        }
3519        if let Some(url) = inner.icon_url.as_deref() {
3520            validate_url("icon", url)?;
3521        }
3522        if let Some(schemes) = inner.security_schemes.as_ref() {
3523            validate_count("security schemes", schemes.len(), MAX_SECURITY_SCHEMES)?;
3524            for (name, scheme) in schemes {
3525                validate_required_text("security scheme name", name, MAX_LABEL_BYTES)?;
3526                validate_security_scheme(scheme)?;
3527            }
3528        }
3529        if let Some(requirements) = inner.security_requirements.as_ref() {
3530            validate_security_requirements(requirements)?;
3531            validate_security_requirement_references(
3532                requirements,
3533                inner.security_schemes.as_ref(),
3534            )?;
3535        }
3536        for skill in &inner.skills {
3537            if let Some(requirements) = skill.security_requirements.as_deref() {
3538                validate_security_requirement_references(
3539                    requirements,
3540                    inner.security_schemes.as_ref(),
3541                )?;
3542            }
3543        }
3544        if let Some(signatures) = inner.signatures.as_ref() {
3545            validate_count(
3546                "Agent Card signatures",
3547                signatures.len(),
3548                MAX_SECURITY_SCHEMES,
3549            )?;
3550            for signature in signatures.iter().cloned() {
3551                A2aAgentCardSignature::try_from_wire(signature)?;
3552            }
3553        }
3554        Ok(Self { inner })
3555    }
3556
3557    pub(crate) fn into_wire(self) -> wire::AgentCard {
3558        self.inner
3559    }
3560}
3561
3562/// Builder that requires at least one interface and one default input/output
3563/// mode before producing an Agent Card.
3564#[derive(Clone, Debug)]
3565pub struct A2aAgentCardBuilder {
3566    card: wire::AgentCard,
3567}
3568
3569impl A2aAgentCardBuilder {
3570    /// Sets capability flags and extension declarations.
3571    #[must_use]
3572    pub fn capabilities(mut self, capabilities: A2aAgentCapabilities) -> Self {
3573        self.card.capabilities = capabilities.into_wire();
3574        self
3575    }
3576
3577    /// Adds an interface at the end of preference order.
3578    pub fn interface(mut self, interface: A2aAgentInterface) -> Result<Self, A2aContractError> {
3579        if self.card.supported_interfaces.len() == MAX_INTERFACES {
3580            return Err(A2aContractError::TooMany {
3581                field: "supported interfaces",
3582                maximum: MAX_INTERFACES,
3583                actual: self.card.supported_interfaces.len() + 1,
3584            });
3585        }
3586        let wire = interface.into_wire();
3587        if self
3588            .card
3589            .supported_interfaces
3590            .iter()
3591            .any(|existing| existing.protocol_binding == wire.protocol_binding)
3592        {
3593            return Err(A2aContractError::InvalidLifecycle(
3594                "only one interface per StateKnot-supported binding is allowed",
3595            ));
3596        }
3597        self.card.supported_interfaces.push(wire);
3598        Ok(self)
3599    }
3600
3601    /// Sets required default input media modes.
3602    pub fn default_input_modes(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
3603        validate_modes("default input modes", &values)?;
3604        if values.is_empty() {
3605            return Err(A2aContractError::Empty {
3606                field: "default input modes",
3607            });
3608        }
3609        self.card.default_input_modes = values;
3610        Ok(self)
3611    }
3612
3613    /// Sets required default output media modes.
3614    pub fn default_output_modes(mut self, values: Vec<String>) -> Result<Self, A2aContractError> {
3615        validate_modes("default output modes", &values)?;
3616        if values.is_empty() {
3617            return Err(A2aContractError::Empty {
3618                field: "default output modes",
3619            });
3620        }
3621        self.card.default_output_modes = values;
3622        Ok(self)
3623    }
3624
3625    /// Adds one discoverable skill.
3626    pub fn skill(mut self, skill: A2aAgentSkill) -> Result<Self, A2aContractError> {
3627        if self.card.skills.len() == MAX_SKILLS {
3628            return Err(A2aContractError::TooMany {
3629                field: "agent skills",
3630                maximum: MAX_SKILLS,
3631                actual: self.card.skills.len() + 1,
3632            });
3633        }
3634        if self
3635            .card
3636            .skills
3637            .iter()
3638            .any(|existing| existing.id == skill.inner.id)
3639        {
3640            return Err(A2aContractError::InvalidLifecycle(
3641                "duplicate Agent Skill identifier",
3642            ));
3643        }
3644        self.card.skills.push(skill.into_wire());
3645        Ok(self)
3646    }
3647
3648    /// Adds provider attribution.
3649    pub fn provider(
3650        mut self,
3651        organization: impl Into<String>,
3652        url: impl Into<String>,
3653    ) -> Result<Self, A2aContractError> {
3654        let organization = organization.into();
3655        let url = url.into();
3656        validate_required_text("provider organization", &organization, MAX_LABEL_BYTES)?;
3657        validate_url("provider", &url)?;
3658        self.card.provider = Some(wire::AgentProvider { organization, url });
3659        Ok(self)
3660    }
3661
3662    /// Adds a documentation URL.
3663    pub fn documentation_url(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
3664        let value = value.into();
3665        validate_url("documentation", &value)?;
3666        self.card.documentation_url = Some(value);
3667        Ok(self)
3668    }
3669
3670    /// Adds an icon URL.
3671    pub fn icon_url(mut self, value: impl Into<String>) -> Result<Self, A2aContractError> {
3672        let value = value.into();
3673        validate_url("icon", &value)?;
3674        self.card.icon_url = Some(value);
3675        Ok(self)
3676    }
3677
3678    /// Adds a named security scheme.
3679    pub fn security_scheme(
3680        mut self,
3681        name: impl Into<String>,
3682        scheme: A2aSecurityScheme,
3683    ) -> Result<Self, A2aContractError> {
3684        let name = name.into();
3685        validate_required_text("security scheme name", &name, MAX_LABEL_BYTES)?;
3686        let schemes = self.card.security_schemes.get_or_insert_with(HashMap::new);
3687        if schemes.len() == MAX_SECURITY_SCHEMES {
3688            return Err(A2aContractError::TooMany {
3689                field: "security schemes",
3690                maximum: MAX_SECURITY_SCHEMES,
3691                actual: schemes.len() + 1,
3692            });
3693        }
3694        if schemes.insert(name, scheme.into_wire()).is_some() {
3695            return Err(A2aContractError::InvalidLifecycle(
3696                "duplicate security scheme name",
3697            ));
3698        }
3699        Ok(self)
3700    }
3701
3702    /// Sets alternative security requirements. Each map is an AND group and
3703    /// the vector is evaluated as OR, following the A2A/OpenAPI model.
3704    pub fn security_requirements(
3705        mut self,
3706        requirements: Vec<HashMap<String, Vec<String>>>,
3707    ) -> Result<Self, A2aContractError> {
3708        validate_security_requirements(&requirements)?;
3709        self.card.security_requirements = Some(requirements);
3710        Ok(self)
3711    }
3712
3713    /// Adds one detached card signature.
3714    pub fn signature(mut self, signature: A2aAgentCardSignature) -> Result<Self, A2aContractError> {
3715        let signatures = self.card.signatures.get_or_insert_with(Vec::new);
3716        if signatures.len() == MAX_SECURITY_SCHEMES {
3717            return Err(A2aContractError::TooMany {
3718                field: "Agent Card signatures",
3719                maximum: MAX_SECURITY_SCHEMES,
3720                actual: signatures.len() + 1,
3721            });
3722        }
3723        signatures.push(signature.into_wire());
3724        Ok(self)
3725    }
3726
3727    /// Validates all cross-field invariants and builds the card.
3728    pub fn build(self) -> Result<A2aAgentCard, A2aContractError> {
3729        A2aAgentCard::try_from_wire(self.card)
3730    }
3731}
3732
3733#[cfg(test)]
3734mod tests {
3735    use super::*;
3736
3737    fn card() -> A2aAgentCard {
3738        A2aAgentCard::builder("StateKnot test", "Bounded test agent", "0.0.0")
3739            .unwrap()
3740            .capabilities(A2aAgentCapabilities::new().streaming(true))
3741            .interface(
3742                A2aAgentInterface::new("https://agent.example/a2a/rest", A2aBinding::HttpJson)
3743                    .unwrap(),
3744            )
3745            .unwrap()
3746            .default_input_modes(vec!["text/plain".to_string()])
3747            .unwrap()
3748            .default_output_modes(vec!["application/json".to_string()])
3749            .unwrap()
3750            .skill(
3751                A2aAgentSkill::new(
3752                    "assess-supplier",
3753                    "Assess supplier",
3754                    "Returns a bounded supplier assessment.",
3755                    vec!["procurement".to_string()],
3756                )
3757                .unwrap(),
3758            )
3759            .unwrap()
3760            .build()
3761            .unwrap()
3762    }
3763
3764    #[test]
3765    fn card_round_trips_without_sdk_types() {
3766        let original = card();
3767        let decoded = A2aAgentCard::from_json(original.to_json().unwrap()).unwrap();
3768        assert_eq!(decoded, original);
3769        assert_eq!(decoded.interfaces()[0].binding(), A2aBinding::HttpJson);
3770    }
3771
3772    #[test]
3773    fn rejects_unspecified_roles_and_states() {
3774        let message = wire::Message {
3775            message_id: "m-1".to_string(),
3776            context_id: None,
3777            task_id: None,
3778            role: wire::Role::Unspecified,
3779            parts: vec![wire::Part::text("hello")],
3780            metadata: None,
3781            extensions: None,
3782            reference_task_ids: None,
3783        };
3784        assert!(A2aMessage::try_from_wire(message).is_err());
3785    }
3786
3787    #[test]
3788    fn secrets_are_redacted() {
3789        let config = A2aPushConfig::new("https://hooks.example/a2a")
3790            .unwrap()
3791            .with_token(A2aSecret::new("top-secret").unwrap())
3792            .with_authentication(
3793                A2aPushAuthentication::new(
3794                    "Bearer",
3795                    Some(A2aSecret::new("super-private").unwrap()),
3796                )
3797                .unwrap(),
3798            );
3799        let formatted = format!("{config:?}");
3800        assert!(!formatted.contains("top-secret"));
3801        assert!(!formatted.contains("super-private"));
3802    }
3803
3804    #[test]
3805    fn auth_required_needs_explanation() {
3806        assert!(A2aTaskStatus::new(A2aTaskState::AuthRequired, None, None).is_err());
3807    }
3808
3809    #[test]
3810    fn blocks_wire_tenant_override() {
3811        let request = wire::GetTaskRequest {
3812            id: "task-1".to_string(),
3813            history_length: None,
3814            tenant: Some("other".to_string()),
3815        };
3816        assert!(A2aGetTaskRequest::try_from_wire(request).is_err());
3817    }
3818
3819    #[test]
3820    fn task_pagination_enforces_a2a_protocol_bounds() {
3821        assert!(A2aListTasksRequest::new().with_page_size(100).is_ok());
3822        assert!(A2aListTasksRequest::new().with_page_size(101).is_err());
3823
3824        let response = wire::ListTasksResponse {
3825            tasks: Vec::new(),
3826            next_page_token: String::new(),
3827            page_size: 101,
3828            total_size: 0,
3829        };
3830        assert!(A2aTaskPage::try_from_wire(response).is_err());
3831    }
3832
3833    #[test]
3834    fn inert_future_interfaces_are_preserved_without_becoming_executable() {
3835        let mut value = card().to_json().unwrap();
3836        value["supportedInterfaces"]
3837            .as_array_mut()
3838            .unwrap()
3839            .push(serde_json::json!({
3840                "url": "grpc.example.test:443",
3841                "protocolBinding": "GRPC",
3842                "protocolVersion": "1.0"
3843            }));
3844
3845        let decoded = A2aAgentCard::from_json(value).unwrap();
3846        assert_eq!(decoded.advertised_interface_count(), 2);
3847        assert_eq!(decoded.interfaces().len(), 1);
3848    }
3849
3850    #[test]
3851    fn duplicate_skill_ids_are_rejected_on_untrusted_cards() {
3852        let mut value = card().to_json().unwrap();
3853        let duplicate = value["skills"][0].clone();
3854        value["skills"].as_array_mut().unwrap().push(duplicate);
3855        assert!(A2aAgentCard::from_json(value).is_err());
3856    }
3857
3858    #[test]
3859    fn card_and_skill_security_requirements_must_reference_declared_schemes() {
3860        let missing = HashMap::from([("missing".to_string(), Vec::new())]);
3861
3862        let mut card_requirement = card().into_wire();
3863        card_requirement.security_requirements = Some(vec![missing.clone()]);
3864        assert!(A2aAgentCard::try_from_wire(card_requirement).is_err());
3865
3866        let mut skill_requirement = card().into_wire();
3867        skill_requirement.skills[0].security_requirements = Some(vec![missing]);
3868        assert!(A2aAgentCard::try_from_wire(skill_requirement).is_err());
3869    }
3870
3871    #[test]
3872    fn artifact_update_wire_flags_are_preserved_exactly() {
3873        let update = wire::TaskArtifactUpdateEvent {
3874            task_id: "task-1".to_string(),
3875            context_id: "context-1".to_string(),
3876            artifact: A2aArtifact::new("artifact-1", vec![A2aPart::text("first chunk").unwrap()])
3877                .unwrap()
3878                .into_wire(),
3879            append: Some(false),
3880            last_chunk: Some(false),
3881            metadata: None,
3882        };
3883
3884        let decoded = A2aArtifactUpdate::try_from_wire(update).unwrap();
3885        assert!(!decoded.append());
3886        assert!(!decoded.last_chunk());
3887    }
3888
3889    #[test]
3890    fn outbound_send_rejects_agent_roles_and_bound_push_tasks() {
3891        let agent_message = A2aMessage::new(
3892            "message-1",
3893            A2aMessageRole::Agent,
3894            vec![A2aPart::text("not a client message").unwrap()],
3895        )
3896        .unwrap();
3897        assert!(
3898            A2aSendMessageRequest::new(agent_message)
3899                .into_wire(None)
3900                .is_err()
3901        );
3902
3903        let push = A2aPushConfig::new("https://hooks.example.test/a2a")
3904            .unwrap()
3905            .with_task_id("task-1")
3906            .unwrap();
3907        let configuration = A2aSendConfiguration::new().with_push_config(push);
3908        let user_message = A2aMessage::new(
3909            "message-2",
3910            A2aMessageRole::User,
3911            vec![A2aPart::text("valid role").unwrap()],
3912        )
3913        .unwrap();
3914        assert!(
3915            A2aSendMessageRequest::new(user_message)
3916                .with_configuration(configuration)
3917                .into_wire(None)
3918                .is_err()
3919        );
3920    }
3921}