Skip to main content

laser_wire/
agent.rs

1// The Agent Data Exchange Protocol (AGDX) wire surface: the versioned on-log envelope that
2// agent traffic rides, its id types, the task-state and error-code
3// dictionaries, the dead-letter capsule, and the per-kind validity matrix.
4// Specified and fixtured like every other surface. The server stays a thin
5// router (no managed commands, no fork delta), so AGDX works on raw Apache Iggy
6// too.
7//
8// Versioning is out of band. A log record is durable and read back for years,
9// so the `agdx.av` header (u32, `AGENT_OP_VERSION`) selects the decoder before
10// any byte of the body is read. The envelope carries no `v` field by design.
11//
12// Identity is a claim, by deliberate and permanent design. `source` is not
13// infrastructure-stamped identity. Per-record authorship comes from topology
14// (write-exclusive topics per principal) and, in a future envelope version,
15// from signatures. `usage` is advisory analytics input, never
16// enforcement-grade accounting.
17
18use crate::error::InvalidError;
19use crate::query::Value;
20use serde::de::{self, Visitor};
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22use std::collections::BTreeMap;
23use std::fmt;
24use std::str::FromStr;
25
26/// Why parsing a Crockford base32 id failed.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
28#[non_exhaustive]
29pub enum IdParseError {
30    #[error("id must be 26 characters, got {got}")]
31    Length { got: usize },
32    #[error("id contains invalid character `{0}`")]
33    Char(char),
34    #[error("id overflows 128 bits")]
35    Overflow,
36}
37
38// Every u128 id rides the CBOR payload as one atomic 16-byte byte string
39// (big-endian), a fixed-width form with no bignum tag. Duplicated routing
40// HEADERS use Iggy's typed Uint128 representation instead (little-endian on the
41// server wire). Fixtures pin both so the two encodings cannot drift silently.
42macro_rules! wire_id {
43    ($(#[$doc:meta])* $name:ident) => {
44        $(#[$doc])*
45        #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46        pub struct $name(u128);
47
48        impl $name {
49            /// Wrap a raw 128-bit id.
50            pub const fn from_u128(value: u128) -> Self {
51                Self(value)
52            }
53
54            /// The raw 128-bit value.
55            pub const fn as_u128(self) -> u128 {
56                self.0
57            }
58
59            /// The big-endian 16 bytes (the payload wire form).
60            pub const fn to_bytes(self) -> [u8; 16] {
61                self.0.to_be_bytes()
62            }
63
64            /// An id from its big-endian 16 bytes.
65            pub const fn from_bytes(payload: [u8; 16]) -> Self {
66                Self(u128::from_be_bytes(payload))
67            }
68        }
69
70        impl std::fmt::Display for $name {
71            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72                let encoded = $crate::agent::crockford_encode(self.0);
73                // The alphabet is ASCII, so the buffer is always valid UTF-8.
74                f.write_str(std::str::from_utf8(&encoded).expect("crockford output is ASCII"))
75            }
76        }
77
78        impl std::fmt::Debug for $name {
79            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80                write!(f, "{}({})", stringify!($name), self)
81            }
82        }
83
84        impl std::str::FromStr for $name {
85            type Err = $crate::agent::IdParseError;
86
87            fn from_str(s: &str) -> Result<Self, Self::Err> {
88                $crate::agent::crockford_decode(s).map(Self)
89            }
90        }
91
92        impl From<u128> for $name {
93            fn from(value: u128) -> Self {
94                Self(value)
95            }
96        }
97
98        impl From<$name> for u128 {
99            fn from(value: $name) -> u128 {
100                value.0
101            }
102        }
103
104        #[cfg(feature = "schemars")]
105        impl schemars::JsonSchema for $name {
106            fn schema_name() -> std::borrow::Cow<'static, str> {
107                stringify!($name).into()
108            }
109
110            fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
111                schemars::json_schema!({
112                    "description": "A 128-bit id as 26-character Crockford base32 text",
113                    "type": "string",
114                    "minLength": 26,
115                    "maxLength": 26
116                })
117            }
118        }
119
120        impl serde::Serialize for $name {
121            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
122                if serializer.is_human_readable() {
123                    serializer.serialize_str(&self.to_string())
124                } else {
125                    serializer.serialize_bytes(&self.to_bytes())
126                }
127            }
128        }
129
130        impl<'de> serde::Deserialize<'de> for $name {
131            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
132                if deserializer.is_human_readable() {
133                    struct TextVisitor;
134
135                    impl<'de> serde::de::Visitor<'de> for TextVisitor {
136                        type Value = $name;
137
138                        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139                            f.write_str("a 26-character Crockford base32 id or 16 id bytes")
140                        }
141
142                        fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
143                            value.parse().map_err(E::custom)
144                        }
145
146                        fn visit_bytes<E: serde::de::Error>(self, value: &[u8]) -> Result<Self::Value, E> {
147                            let payload: [u8; 16] = value
148                                .try_into()
149                                .map_err(|_| E::invalid_length(value.len(), &self))?;
150                            Ok($name::from_bytes(payload))
151                        }
152
153                        fn visit_byte_buf<E: serde::de::Error>(self, value: Vec<u8>) -> Result<Self::Value, E> {
154                            self.visit_bytes(&value)
155                        }
156                    }
157
158                    // Derived enum decoders buffer newtype payloads before replaying
159                    // them. Serde's buffered deserializer reports human-readable mode,
160                    // but preserves the original CBOR byte-string value.
161                    return deserializer.deserialize_any(TextVisitor);
162                }
163
164                struct BytesVisitor;
165
166                impl<'de> serde::de::Visitor<'de> for BytesVisitor {
167                    type Value = $name;
168
169                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170                        f.write_str("16 big-endian id bytes")
171                    }
172
173                    fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
174                        let payload: [u8; 16] = v
175                            .try_into()
176                            .map_err(|_| E::invalid_length(v.len(), &self))?;
177                        Ok($name::from_bytes(payload))
178                    }
179
180                    fn visit_byte_buf<E: serde::de::Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
181                        self.visit_bytes(&v)
182                    }
183
184                    fn visit_seq<A: serde::de::SeqAccess<'de>>(
185                        self,
186                        mut sequence: A,
187                    ) -> Result<Self::Value, A::Error> {
188                        let mut payload = [0_u8; 16];
189                        for (index, byte) in payload.iter_mut().enumerate() {
190                            *byte = sequence
191                                .next_element()?
192                                .ok_or_else(|| serde::de::Error::invalid_length(index, &self))?;
193                        }
194                        if sequence.next_element::<u8>()?.is_some() {
195                            return Err(serde::de::Error::invalid_length(17, &self));
196                        }
197                        Ok($name::from_bytes(payload))
198                    }
199                }
200
201                deserializer.deserialize_bytes(BytesVisitor)
202            }
203        }
204    };
205}
206
207// Reused by the memory and graph modules for their id newtypes (MemoryId,
208// NodeId, EdgeId), so every wire id shares one display, codec, and parse form.
209pub(crate) use wire_id;
210
211wire_id!(
212    /// A record's producer-assigned identity, a ULID minted before publish.
213    ///
214    /// Portable in a way a log position is not. An offset is meaningful only
215    /// within the partition that assigned it, so a copy elsewhere (a re-publish
216    /// into another stream, partition, or DR cluster) gets a fresh position.
217    /// This id rides in the payload and stays the same everywhere.
218    RecordId
219);
220wire_id!(
221    /// The conversation a message belongs to. The unit of ordering and the
222    /// partition key, and the trace id of the causal trace.
223    ConversationId
224);
225wire_id!(
226    /// Request/reply pairing id. A2A task identity and MCP tool-call ids map
227    /// onto it at the bridges.
228    CorrelationId
229);
230wire_id!(
231    /// A chunk stream's grouping id when several streams run under one
232    /// correlation. Named `channel` because `stream` is an iggy topology term.
233    ChannelId
234);
235
236/// The Iggy binding's packing of the causal locator (`cause_at`, and the
237/// dead-letter `source`).
238///
239/// The locator rides the wire as one **opaque byte string**, the substrate-
240/// neutral slot every binding packs its own form into, so the envelope itself
241/// names no server. A consumer that cannot interpret the bytes ignores them and
242/// falls back to the portable `cause` / `record` id. The Iggy packing is the
243/// four-level address as fixed-width big-endian payload: `stream_id`, `topic_id`,
244/// `partition_id` (each u32) then `offset` (u64), 20 bytes. Another binding
245/// packs its own locator (a topic name or id, a partition, an offset) into the
246/// same opaque slot.
247#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
248pub struct LogPosition {
249    pub stream_id: u32,
250    pub topic_id: u32,
251    pub partition_id: u32,
252    pub offset: u64,
253}
254
255const LOG_POSITION_BYTES: usize = 20;
256
257impl LogPosition {
258    /// A locator at `(stream, topic, partition, offset)`.
259    pub const fn new(stream_id: u32, topic_id: u32, partition_id: u32, offset: u64) -> Self {
260        Self {
261            stream_id,
262            topic_id,
263            partition_id,
264            offset,
265        }
266    }
267
268    /// The Iggy locator packed as 20 big-endian bytes (the opaque wire form).
269    pub fn to_bytes(self) -> [u8; LOG_POSITION_BYTES] {
270        let mut out = [0u8; LOG_POSITION_BYTES];
271        out[0..4].copy_from_slice(&self.stream_id.to_be_bytes());
272        out[4..8].copy_from_slice(&self.topic_id.to_be_bytes());
273        out[8..12].copy_from_slice(&self.partition_id.to_be_bytes());
274        out[12..20].copy_from_slice(&self.offset.to_be_bytes());
275        out
276    }
277
278    /// Unpack the Iggy locator from its 20 big-endian bytes.
279    pub fn from_bytes(payload: [u8; LOG_POSITION_BYTES]) -> Self {
280        let u32_at = |start: usize| {
281            u32::from_be_bytes(payload[start..start + 4].try_into().expect("4-byte slice"))
282        };
283        Self {
284            stream_id: u32_at(0),
285            topic_id: u32_at(4),
286            partition_id: u32_at(8),
287            offset: u64::from_be_bytes(payload[12..20].try_into().expect("8-byte slice")),
288        }
289    }
290}
291
292// The locator rides the payload as one opaque CBOR byte string, not a named-field
293// map, so the slot is binding-neutral (an Iggy packing here, another binding's
294// packing elsewhere) and pins smaller than the four labelled fields would.
295#[cfg(feature = "schemars")]
296impl schemars::JsonSchema for LogPosition {
297    fn schema_name() -> std::borrow::Cow<'static, str> {
298        "LogPosition".into()
299    }
300
301    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
302        crate::encoding::fixed_bytes_schema(generator, LOG_POSITION_BYTES)
303    }
304}
305
306impl Serialize for LogPosition {
307    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308        serializer.serialize_bytes(&self.to_bytes())
309    }
310}
311
312impl<'de> Deserialize<'de> for LogPosition {
313    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
314        struct LocatorVisitor;
315
316        impl<'de> Visitor<'de> for LocatorVisitor {
317            type Value = LogPosition;
318
319            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320                f.write_str("20 packed locator bytes")
321            }
322
323            fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
324                let payload: [u8; LOG_POSITION_BYTES] = v
325                    .try_into()
326                    .map_err(|_| E::invalid_length(v.len(), &self))?;
327                Ok(LogPosition::from_bytes(payload))
328            }
329
330            fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
331                self.visit_bytes(&v)
332            }
333
334            fn visit_seq<A: de::SeqAccess<'de>>(
335                self,
336                mut sequence: A,
337            ) -> Result<Self::Value, A::Error> {
338                let mut payload = [0_u8; LOG_POSITION_BYTES];
339                for (index, byte) in payload.iter_mut().enumerate() {
340                    *byte = sequence
341                        .next_element()?
342                        .ok_or_else(|| de::Error::invalid_length(index, &self))?;
343                }
344                if sequence.next_element::<u8>()?.is_some() {
345                    return Err(de::Error::invalid_length(LOG_POSITION_BYTES + 1, &self));
346                }
347                Ok(LogPosition::from_bytes(payload))
348            }
349        }
350
351        deserializer.deserialize_bytes(LocatorVisitor)
352    }
353}
354
355/// A producer-supplied business idempotency key: non-empty, at most 64 bytes.
356///
357/// A readable string by design, often a natural business key like
358/// `job-123-attempt-2`, so consoles and dead-letter capsules stay debuggable.
359/// The reliable consumer's dedup store hashes it internally.
360#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
361#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
362#[serde(try_from = "String", into = "String")]
363pub struct IdempotencyKey(String);
364
365impl IdempotencyKey {
366    /// The key as a string slice.
367    pub fn as_str(&self) -> &str {
368        &self.0
369    }
370}
371
372impl FromStr for IdempotencyKey {
373    type Err = InvalidError;
374
375    fn from_str(s: &str) -> Result<Self, Self::Err> {
376        s.to_owned().try_into()
377    }
378}
379
380impl TryFrom<String> for IdempotencyKey {
381    type Error = InvalidError;
382
383    fn try_from(value: String) -> Result<Self, Self::Error> {
384        if value.is_empty() {
385            return Err(InvalidError::new("idempotency key must not be empty"));
386        }
387        if value.len() > crate::limits::MAX_IDEMPOTENCY_KEY_BYTES {
388            return Err(InvalidError::new(format!(
389                "idempotency key is {}B, exceeds cap {}B",
390                value.len(),
391                crate::limits::MAX_IDEMPOTENCY_KEY_BYTES
392            )));
393        }
394        if value.chars().any(char::is_control) {
395            return Err(InvalidError::new(
396                "idempotency key contains a control character",
397            ));
398        }
399        Ok(Self(value))
400    }
401}
402
403impl From<IdempotencyKey> for String {
404    fn from(value: IdempotencyKey) -> Self {
405        value.0
406    }
407}
408
409impl fmt::Display for IdempotencyKey {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        f.write_str(&self.0)
412    }
413}
414
415/// An agent's identity: a bounded, human-readable name string.
416///
417/// A string rather than an opaque numeric id, because an agent is a named
418/// principal every edge protocol spells out as text (an A2A agent name or URL,
419/// an MCP server name, OTel `gen_ai.agent.id`). The SDK's named agents map
420/// straight onto it with no lossy hash. It is an authorship claim on shared
421/// topics (see the module docs). Non-empty, at most
422/// [`MAX_AGENT_STRING_BYTES`](crate::limits::MAX_AGENT_STRING_BYTES), and free
423/// of ASCII control characters. Every other character is allowed.
424#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
425#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
426#[serde(try_from = "String", into = "String")]
427pub struct AgentId(String);
428
429impl AgentId {
430    /// The id as a string slice.
431    pub fn as_str(&self) -> &str {
432        &self.0
433    }
434}
435
436impl FromStr for AgentId {
437    type Err = InvalidError;
438
439    fn from_str(s: &str) -> Result<Self, Self::Err> {
440        s.to_owned().try_into()
441    }
442}
443
444impl TryFrom<String> for AgentId {
445    type Error = InvalidError;
446
447    fn try_from(value: String) -> Result<Self, Self::Error> {
448        if value.is_empty() {
449            return Err(InvalidError::new("agent id must not be empty"));
450        }
451        if value.len() > crate::limits::MAX_AGENT_STRING_BYTES {
452            return Err(InvalidError::new(format!(
453                "agent id is {}B, exceeds cap {}B",
454                value.len(),
455                crate::limits::MAX_AGENT_STRING_BYTES
456            )));
457        }
458        if let Some(c) = value.chars().find(|c| c.is_control()) {
459            return Err(InvalidError::new(format!(
460                "agent id must not contain control characters (found {c:?})"
461            )));
462        }
463        Ok(Self(value))
464    }
465}
466
467impl TryFrom<&str> for AgentId {
468    type Error = InvalidError;
469
470    fn try_from(value: &str) -> Result<Self, Self::Error> {
471        value.to_owned().try_into()
472    }
473}
474
475impl From<AgentId> for String {
476    fn from(value: AgentId) -> Self {
477        value.0
478    }
479}
480
481impl fmt::Display for AgentId {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        f.write_str(&self.0)
484    }
485}
486
487/// What a message is. A closed vocabulary by design: adding a kind requires an
488/// `AGENT_OP_VERSION` bump and a hello advertisement, because an unknown kind
489/// must fail decode rather than flow misinterpreted.
490#[derive(
491    Clone,
492    Copy,
493    Debug,
494    PartialEq,
495    Eq,
496    Hash,
497    Serialize,
498    Deserialize,
499    strum::Display,
500    strum::EnumString,
501)]
502#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
503#[serde(rename_all = "snake_case")]
504#[strum(serialize_all = "snake_case")]
505pub enum AgentKind {
506    /// Expects a reply or effect. Requires `correlation`. Fire-and-forget
507    /// commands do not exist by definition. Those are events.
508    Command,
509    /// The paired answer to a command.
510    Response,
511    /// Expects nothing.
512    Event,
513    /// One piece of a stream, ordered by `sequence` within a `channel`.
514    Chunk,
515    /// Lifecycle signal, discriminated by `operation`: task or session updates,
516    /// liveness cards, and progress ticks.
517    Status,
518    /// A terminal failure. The body is a structured [`AgentErrorBody`].
519    Error,
520}
521
522/// A2A's task lifecycle with LaserData's `Paused` extension, riding the wire as a u8 code (the
523/// `agdx.ct` dictionary pattern) so a future A2A state takes the next free code
524/// and flows through old consumers as an opaque non-terminal value instead of
525/// forcing a version bump on someone else's release schedule. Codes are
526/// permanent and never renumbered.
527// Display and FromStr are hand-written, not strum-derived, deliberately: the
528// `Unrecognized(u8)` passthrough variant must format its carried code
529// (`unrecognized-42`) and must never parse from text, a combination strum's
530// per-variant attributes cannot express (`disabled` removes the variant from
531// Display too and the derive panics on it). Every pure unit-word vocabulary
532// (`AgentRunState`, `ForkKind`, `ContentType`, ...) derives strum instead.
533#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
534#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
535#[serde(from = "u8", into = "u8")]
536pub enum TaskState {
537    Submitted,
538    Working,
539    InputRequired,
540    Completed,
541    Canceled,
542    Failed,
543    Rejected,
544    AuthRequired,
545    Unknown,
546    /// LaserData's paused session state.
547    Paused,
548    /// A code this build does not know: passed through, treated as non-terminal.
549    Unrecognized(u8),
550}
551
552impl TaskState {
553    /// The pinned wire code.
554    pub const fn code(self) -> u8 {
555        match self {
556            TaskState::Submitted => 1,
557            TaskState::Working => 2,
558            TaskState::InputRequired => 3,
559            TaskState::Completed => 4,
560            TaskState::Canceled => 5,
561            TaskState::Failed => 6,
562            TaskState::Rejected => 7,
563            TaskState::AuthRequired => 8,
564            TaskState::Unknown => 9,
565            TaskState::Paused => 10,
566            TaskState::Unrecognized(code) => code,
567        }
568    }
569
570    /// The state for a wire code (total: unknown codes become
571    /// [`Unrecognized`](Self::Unrecognized)).
572    pub const fn from_code(code: u8) -> Self {
573        match code {
574            1 => TaskState::Submitted,
575            2 => TaskState::Working,
576            3 => TaskState::InputRequired,
577            4 => TaskState::Completed,
578            5 => TaskState::Canceled,
579            6 => TaskState::Failed,
580            7 => TaskState::Rejected,
581            8 => TaskState::AuthRequired,
582            9 => TaskState::Unknown,
583            10 => TaskState::Paused,
584            other => TaskState::Unrecognized(other),
585        }
586    }
587
588    /// Whether this state ends the task (A2A's terminal set). Unrecognized
589    /// codes are non-terminal by rule.
590    pub const fn is_terminal(self) -> bool {
591        matches!(
592            self,
593            TaskState::Completed | TaskState::Canceled | TaskState::Failed | TaskState::Rejected
594        )
595    }
596}
597
598impl From<u8> for TaskState {
599    fn from(code: u8) -> Self {
600        Self::from_code(code)
601    }
602}
603
604impl From<TaskState> for u8 {
605    fn from(state: TaskState) -> u8 {
606        state.code()
607    }
608}
609
610impl fmt::Display for TaskState {
611    // The A2A kebab-case names, for bridges and consoles.
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        match self {
614            TaskState::Submitted => f.write_str("submitted"),
615            TaskState::Working => f.write_str("working"),
616            TaskState::InputRequired => f.write_str("input-required"),
617            TaskState::Completed => f.write_str("completed"),
618            TaskState::Canceled => f.write_str("canceled"),
619            TaskState::Failed => f.write_str("failed"),
620            TaskState::Rejected => f.write_str("rejected"),
621            TaskState::AuthRequired => f.write_str("auth-required"),
622            TaskState::Unknown => f.write_str("unknown"),
623            TaskState::Paused => f.write_str("paused"),
624            TaskState::Unrecognized(code) => write!(f, "unrecognized-{code}"),
625        }
626    }
627}
628
629impl FromStr for TaskState {
630    type Err = InvalidError;
631
632    fn from_str(s: &str) -> Result<Self, Self::Err> {
633        Ok(match s {
634            "submitted" => TaskState::Submitted,
635            "working" => TaskState::Working,
636            "input-required" => TaskState::InputRequired,
637            "completed" => TaskState::Completed,
638            "canceled" => TaskState::Canceled,
639            "failed" => TaskState::Failed,
640            "rejected" => TaskState::Rejected,
641            "auth-required" => TaskState::AuthRequired,
642            "unknown" => TaskState::Unknown,
643            "paused" => TaskState::Paused,
644            other => return Err(InvalidError::new(format!("unknown task state `{other}`"))),
645        })
646    }
647}
648
649/// The session lifecycle exposed by managed reads.
650#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
651#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
652#[serde(rename_all = "snake_case")]
653pub enum SessionStatus {
654    Submitted,
655    Active,
656    Paused,
657    Completed,
658    Failed,
659    Canceled,
660    #[serde(other)]
661    Unrecognized,
662}
663
664/// One session addressed within a stream by name.
665#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
666#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
667pub struct SessionRef {
668    pub stream: String,
669    pub session: ConversationId,
670}
671
672/// The SDK that created a session.
673#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
675pub struct SdkInfo {
676    pub language: String,
677    pub version: String,
678}
679
680/// The optional token and cost ceiling requested for a session.
681#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
682#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
683pub struct Budget {
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub tokens: Option<u64>,
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub cost_micros: Option<u64>,
688}
689
690/// The first status body of a session.
691#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
692#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
693pub struct SessionStart {
694    #[serde(default, skip_serializing_if = "Option::is_none")]
695    pub label: Option<String>,
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub namespace: Option<String>,
698    pub agent: AgentId,
699    pub sdk: SdkInfo,
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    pub parent: Option<ConversationId>,
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    pub root: Option<ConversationId>,
704    #[serde(default, skip_serializing_if = "Option::is_none")]
705    pub idle_timeout_micros: Option<u64>,
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub budget: Option<Budget>,
708    #[serde(default, skip_serializing_if = "Vec::is_empty")]
709    pub tags: Vec<String>,
710}
711
712/// A session status update that can acknowledge a control record.
713#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
714#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
715pub struct SessionTransition {
716    #[serde(default, skip_serializing_if = "Option::is_none")]
717    pub actor: Option<AgentId>,
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub acknowledges: Option<LogPosition>,
720}
721
722/// The JSON body of a `session_pause` request on `agent.control`: the agents
723/// whose acknowledgments complete the pause, frozen when the request is
724/// written. An empty set names no agent, and every agent that receives work
725/// for the session while it is paused acknowledges when it holds that work.
726#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
727#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
728pub struct SessionPauseRequest {
729    #[serde(default, skip_serializing_if = "Vec::is_empty")]
730    pub participants: Vec<AgentId>,
731}
732
733/// One work record an agent held while its session was paused. A
734/// `session_parked` event on the session lane carries it, and a
735/// `session_unparked` event with the same body records that the agent handled
736/// the record after the resume. The source address with its topic generation,
737/// the agent, and the pause request position together identify one parking.
738#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
739#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
740pub struct SessionParking {
741    pub source: crate::graph::SourceRef,
742    pub role: AgentId,
743    pub request: LogPosition,
744}
745
746impl crate::validate::Validate for SessionParking {
747    fn validate(&self) -> Result<(), InvalidError> {
748        match &self.source {
749            crate::graph::SourceRef::Message {
750                generation: Some(_),
751                ..
752            } => Ok(()),
753            crate::graph::SourceRef::Message { .. } => Err(InvalidError::new(
754                "a parked record must name its source topic generation",
755            )),
756            _ => Err(InvalidError::new(
757                "a parked record must point at a log record",
758            )),
759        }
760    }
761}
762
763/// The body of a terminal session status.
764#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
766pub struct SessionEnd {
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub reason: Option<String>,
769    #[serde(default, skip_serializing_if = "Option::is_none")]
770    pub error: Option<AgentErrorBody>,
771}
772
773/// The estimated token count of `bytes` bytes of context: one token per four
774/// bytes, rounded up. Every SDK and the session fold use this one estimate.
775pub const fn estimate_tokens(bytes: usize) -> u64 {
776    bytes.div_ceil(4) as u64
777}
778
779/// The metadata key for a model call's requested model.
780pub const METADATA_REQUEST_MODEL: &str = "gen_ai.request.model";
781/// The metadata key for the model that answered a call.
782pub const METADATA_RESPONSE_MODEL: &str = "gen_ai.response.model";
783/// The metadata key for the provider that served a model call.
784pub const METADATA_PROVIDER_NAME: &str = "gen_ai.provider.name";
785/// The metadata key that marks a command as the first command of a
786/// submitted session. The receiving agent marks the session working when it
787/// picks the command up.
788pub const METADATA_SUBMITTED: &str = "submitted";
789/// The metadata key that marks a command a session recorded for its own model
790/// or tool call. `classify` keeps such a record observational, so it never
791/// reaches a handler as new work.
792pub const METADATA_RECORDED: &str = "recorded";
793/// The metadata key for a call's duration in microseconds, measured by the
794/// application around the provider or tool call.
795pub const METADATA_DURATION_MICROS: &str = "duration_micros";
796
797/// The inputs and source positions used to assemble one model context.
798#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
799#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
800pub struct ContextManifest {
801    pub policy: String,
802    pub policy_version: String,
803    pub fragments: Vec<Fragment>,
804    pub tokens: u64,
805    pub bytes: u64,
806    pub frontier: Vec<(u32, u32, u64)>,
807    #[serde(default, skip_serializing_if = "Option::is_none")]
808    pub correlation: Option<CorrelationId>,
809}
810
811/// One input in the context that a model received.
812#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
813#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
814pub enum Fragment {
815    Message {
816        at: crate::graph::SourceRef,
817        tokens: u32,
818        bytes: u32,
819    },
820    Memory {
821        id: String,
822        #[serde(default, skip_serializing_if = "Option::is_none")]
823        version: Option<u64>,
824        #[serde(default, skip_serializing_if = "Option::is_none")]
825        digest: Option<crate::schema::Digest32>,
826        tokens: u32,
827        bytes: u32,
828    },
829    Kv {
830        namespace: String,
831        key: String,
832        #[serde(default, skip_serializing_if = "Option::is_none")]
833        version: Option<u64>,
834        #[serde(default, skip_serializing_if = "Option::is_none")]
835        digest: Option<crate::schema::Digest32>,
836        tokens: u32,
837        bytes: u32,
838    },
839    State {
840        key: String,
841        revision: u64,
842        tokens: u32,
843        bytes: u32,
844    },
845    Summary {
846        at: crate::graph::SourceRef,
847        tokens: u32,
848        bytes: u32,
849    },
850}
851
852/// A summary that replaces a range of context records.
853#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
855pub struct ContextCompaction {
856    pub summary_at: crate::graph::SourceRef,
857    pub covered: Vec<(u32, u32, u64, u64)>,
858    pub summarizer: crate::graph::ProducerInfo,
859}
860
861/// The items selected by one context retrieval.
862#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
863#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
864pub struct ContextRetrieval {
865    #[serde(default, skip_serializing_if = "Option::is_none")]
866    pub query: Option<String>,
867    pub items: Vec<(String, f32)>,
868}
869
870/// One RFC 6902 operation of a state patch.
871pub use json_patch::PatchOperation;
872
873/// One revision-guarded RFC 6902 state patch.
874#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
875#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
876pub struct StateDelta {
877    pub base_revision: u64,
878    #[cfg_attr(
879        feature = "schemars",
880        schemars(schema_with = "crate::encoding::json_patch_schema")
881    )]
882    pub patch: Vec<json_patch::PatchOperation>,
883    pub op_id: String,
884}
885
886/// The complete state document at its base revision.
887#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
888#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
889pub struct StateSnapshot {
890    pub base_revision: u64,
891    pub document: serde_json::Value,
892}
893
894impl crate::validate::Validate for ContextManifest {
895    fn validate(&self) -> Result<(), InvalidError> {
896        if self.fragments.len() > crate::limits::MAX_MANIFEST_FRAGMENTS {
897            return Err(InvalidError::new("context manifest has too many fragments"));
898        }
899        for fragment in &self.fragments {
900            let digest = match fragment {
901                Fragment::Memory { digest, .. } | Fragment::Kv { digest, .. } => digest.as_ref(),
902                _ => None,
903            };
904            if let Some(digest) = digest {
905                crate::validate::Validate::validate(digest)?;
906            }
907        }
908        Ok(())
909    }
910}
911
912impl crate::validate::Validate for StateDelta {
913    fn validate(&self) -> Result<(), InvalidError> {
914        if self.patch.len() > crate::limits::MAX_STATE_PATCH_OPS {
915            return Err(InvalidError::new("state patch has too many operations"));
916        }
917        if self.op_id.is_empty() {
918            return Err(InvalidError::new(
919                "state patch operation id must not be empty",
920            ));
921        }
922        let bytes = serde_json::to_vec(&self.patch)
923            .map_err(|error| InvalidError::new(error.to_string()))?;
924        if bytes.len() > crate::limits::MAX_STATE_DOCUMENT_BYTES {
925            return Err(InvalidError::new(
926                "state patch exceeds the document byte cap",
927            ));
928        }
929        let patch = serde_json::to_value(&self.patch)
930            .map_err(|error| InvalidError::new(error.to_string()))?;
931        validate_portable_json(&patch)?;
932        Ok(())
933    }
934}
935
936impl crate::validate::Validate for StateSnapshot {
937    fn validate(&self) -> Result<(), InvalidError> {
938        let bytes = serde_json::to_vec(&self.document)
939            .map_err(|error| InvalidError::new(error.to_string()))?;
940        if bytes.len() > crate::limits::MAX_STATE_DOCUMENT_BYTES {
941            return Err(InvalidError::new("state document exceeds its byte cap"));
942        }
943        validate_portable_json(&self.document)?;
944        Ok(())
945    }
946}
947
948const MAX_EXACT_JSON_INTEGER: i128 = 9_007_199_254_740_991;
949
950fn validate_portable_json(value: &serde_json::Value) -> Result<(), InvalidError> {
951    match value {
952        serde_json::Value::Number(number) => {
953            let exact = if let Some(integer) = number.as_i64() {
954                i128::from(integer).abs() <= MAX_EXACT_JSON_INTEGER
955            } else if let Some(integer) = number.as_u64() {
956                i128::from(integer) <= MAX_EXACT_JSON_INTEGER
957            } else {
958                number.as_f64().is_some_and(|float| {
959                    float.is_finite()
960                        && (float.fract() != 0.0 || float.abs() <= MAX_EXACT_JSON_INTEGER as f64)
961                })
962            };
963            if !exact {
964                return Err(InvalidError::new(
965                    "state JSON integer exceeds the exact number range",
966                ));
967            }
968        }
969        serde_json::Value::Array(items) => {
970            for item in items {
971                validate_portable_json(item)?;
972            }
973        }
974        serde_json::Value::Object(fields) => {
975            for item in fields.values() {
976                validate_portable_json(item)?;
977            }
978        }
979        _ => {}
980    }
981    Ok(())
982}
983
984/// Apply a JSON Patch to a copy of a state document and check the shared limits.
985pub fn apply_json_patch(
986    document: &serde_json::Value,
987    patch: &[json_patch::PatchOperation],
988) -> Result<serde_json::Value, InvalidError> {
989    if patch.len() > crate::limits::MAX_STATE_PATCH_OPS {
990        return Err(InvalidError::new("state patch has too many operations"));
991    }
992    let patch_bytes =
993        serde_json::to_vec(patch).map_err(|error| InvalidError::new(error.to_string()))?;
994    if patch_bytes.len() > crate::limits::MAX_STATE_DOCUMENT_BYTES {
995        return Err(InvalidError::new(
996            "state patch exceeds the document byte cap",
997        ));
998    }
999    validate_portable_json(document)?;
1000    let patch_value =
1001        serde_json::to_value(patch).map_err(|error| InvalidError::new(error.to_string()))?;
1002    validate_portable_json(&patch_value)?;
1003    let mut result = document.clone();
1004    for (index, operation) in patch.iter().enumerate() {
1005        // RFC 6902 tests a number by value, the patch crate by its type.
1006        if let json_patch::PatchOperation::Test(test) = operation {
1007            let kind = match result.pointer(test.path.as_str()) {
1008                Some(target) if equal_json(target, &test.value) => continue,
1009                Some(_) => "value did not match",
1010                None => "path is invalid",
1011            };
1012            return Err(InvalidError::new(format!(
1013                "operation '/{index}' failed at path '{}': {kind}",
1014                test.path
1015            )));
1016        }
1017        json_patch::patch(&mut result, std::slice::from_ref(operation)).map_err(|mut error| {
1018            error.operation = index;
1019            InvalidError::new(error.to_string())
1020        })?;
1021    }
1022    crate::validate::Validate::validate(&StateSnapshot {
1023        base_revision: 0,
1024        document: result.clone(),
1025    })?;
1026    Ok(result)
1027}
1028
1029/// Whether two state documents hold the same JSON, with numbers compared by value.
1030pub fn equal_json(left: &serde_json::Value, right: &serde_json::Value) -> bool {
1031    match (left, right) {
1032        (serde_json::Value::Number(left), serde_json::Value::Number(right)) => {
1033            equal_json_number(left, right)
1034        }
1035        (serde_json::Value::Array(left), serde_json::Value::Array(right)) => {
1036            left.len() == right.len()
1037                && left
1038                    .iter()
1039                    .zip(right)
1040                    .all(|(left, right)| equal_json(left, right))
1041        }
1042        (serde_json::Value::Object(left), serde_json::Value::Object(right)) => {
1043            left.len() == right.len()
1044                && left.iter().all(|(key, value)| {
1045                    right.get(key).is_some_and(|other| equal_json(value, other))
1046                })
1047        }
1048        _ => left == right,
1049    }
1050}
1051
1052// A whole float is an exact integer, so a float meets an integer on the integer side.
1053fn equal_json_number(left: &serde_json::Number, right: &serde_json::Number) -> bool {
1054    let integer = |number: &serde_json::Number| {
1055        number
1056            .as_i64()
1057            .map(i128::from)
1058            .or_else(|| number.as_u64().map(i128::from))
1059    };
1060    let whole = |number: &serde_json::Number| {
1061        number
1062            .as_f64()
1063            .filter(|float| float.fract() == 0.0)
1064            .map(|float| float as i128)
1065    };
1066    match (integer(left), integer(right)) {
1067        (Some(left), Some(right)) => left == right,
1068        (Some(integer), None) => whole(right) == Some(integer),
1069        (None, Some(integer)) => whole(left) == Some(integer),
1070        (None, None) => left.as_f64() == right.as_f64(),
1071    }
1072}
1073
1074impl crate::validate::Validate for SessionStart {
1075    fn validate(&self) -> Result<(), InvalidError> {
1076        if let Some(label) = &self.label
1077            && (label.len() > crate::limits::MAX_SESSION_LABEL_BYTES
1078                || label.chars().any(char::is_control))
1079        {
1080            return Err(InvalidError::new(
1081                "session label exceeds its cap or contains a control character",
1082            ));
1083        }
1084        if let Some(namespace) = &self.namespace {
1085            crate::kv::validate_namespace(namespace)?;
1086        }
1087        if self.root.is_some() && self.parent.is_none() {
1088            return Err(InvalidError::new("session root requires a parent"));
1089        }
1090        if self.tags.len() > crate::limits::MAX_MEMORY_TAGS {
1091            return Err(InvalidError::new("session has too many tags"));
1092        }
1093        if self
1094            .tags
1095            .iter()
1096            .any(|tag| tag.len() > crate::limits::MAX_MEMORY_TAG_BYTES)
1097        {
1098            return Err(InvalidError::new("session tag exceeds its byte cap"));
1099        }
1100        Ok(())
1101    }
1102}
1103
1104/// Typed token accounting, OTel-aligned (`gen_ai.usage.*`, the current
1105/// `input_tokens` and `output_tokens` names, never the deprecated
1106/// prompt/completion pair).
1107///
1108/// Advisory analytics input. It is agent-written, so budgets enforce where the
1109/// LLM call executes, never on this field.
1110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1111#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1112pub struct TokenUsage {
1113    pub input_tokens: u64,
1114    pub output_tokens: u64,
1115    #[serde(default, skip_serializing_if = "Option::is_none")]
1116    pub reasoning_output_tokens: Option<u64>,
1117    #[serde(default, skip_serializing_if = "Option::is_none")]
1118    pub cache_read_input_tokens: Option<u64>,
1119    #[serde(default, skip_serializing_if = "Option::is_none")]
1120    pub cache_creation_input_tokens: Option<u64>,
1121    /// Cost in integer micro-units of the deployment's configured currency.
1122    #[serde(default, skip_serializing_if = "Option::is_none")]
1123    pub cost_micros: Option<u64>,
1124}
1125
1126/// Why an agent operation failed, as a pinned u8 dictionary (the
1127/// [`TaskState`] pattern: unknown codes decode and pass through).
1128#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1129#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1130#[serde(from = "u8", into = "u8")]
1131pub enum AgentErrorCode {
1132    InvalidRequest,
1133    Unauthorized,
1134    Unsupported,
1135    DeadlineExceeded,
1136    Cancelled,
1137    ToolFailure,
1138    Internal,
1139    /// A code this build does not know: pass it through.
1140    Unrecognized(u8),
1141}
1142
1143impl AgentErrorCode {
1144    /// The pinned wire code.
1145    pub const fn code(self) -> u8 {
1146        match self {
1147            AgentErrorCode::InvalidRequest => 1,
1148            AgentErrorCode::Unauthorized => 2,
1149            AgentErrorCode::Unsupported => 3,
1150            AgentErrorCode::DeadlineExceeded => 4,
1151            AgentErrorCode::Cancelled => 5,
1152            AgentErrorCode::ToolFailure => 6,
1153            AgentErrorCode::Internal => 7,
1154            AgentErrorCode::Unrecognized(code) => code,
1155        }
1156    }
1157
1158    /// The error code for a wire code (total).
1159    pub const fn from_code(code: u8) -> Self {
1160        match code {
1161            1 => AgentErrorCode::InvalidRequest,
1162            2 => AgentErrorCode::Unauthorized,
1163            3 => AgentErrorCode::Unsupported,
1164            4 => AgentErrorCode::DeadlineExceeded,
1165            5 => AgentErrorCode::Cancelled,
1166            6 => AgentErrorCode::ToolFailure,
1167            7 => AgentErrorCode::Internal,
1168            other => AgentErrorCode::Unrecognized(other),
1169        }
1170    }
1171}
1172
1173impl From<u8> for AgentErrorCode {
1174    fn from(code: u8) -> Self {
1175        Self::from_code(code)
1176    }
1177}
1178
1179impl From<AgentErrorCode> for u8 {
1180    fn from(code: AgentErrorCode) -> u8 {
1181        code.code()
1182    }
1183}
1184
1185/// The structured body of a `kind = error` envelope, mirroring the wire error
1186/// enums of the other surfaces. The `code` is the machine discriminator, the
1187/// optional `message` is human detail.
1188#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1190pub struct AgentErrorBody {
1191    pub code: AgentErrorCode,
1192    #[serde(default, skip_serializing_if = "Option::is_none")]
1193    pub message: Option<String>,
1194    #[serde(default)]
1195    pub retryable: bool,
1196    #[serde(default, skip_serializing_if = "Option::is_none")]
1197    pub detail: Option<BTreeMap<String, Value>>,
1198}
1199
1200/// Why a message was dead-lettered, as a pinned u8 dictionary.
1201#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1203#[serde(from = "u8", into = "u8")]
1204pub enum DeadLetterReason {
1205    RetryExhausted,
1206    Rejected,
1207    DecodeFailed,
1208    DeadlineExceeded,
1209    /// A code this build does not know: pass it through.
1210    Unrecognized(u8),
1211}
1212
1213impl DeadLetterReason {
1214    /// The pinned wire code.
1215    pub const fn code(self) -> u8 {
1216        match self {
1217            DeadLetterReason::RetryExhausted => 1,
1218            DeadLetterReason::Rejected => 2,
1219            DeadLetterReason::DecodeFailed => 3,
1220            DeadLetterReason::DeadlineExceeded => 4,
1221            DeadLetterReason::Unrecognized(code) => code,
1222        }
1223    }
1224
1225    /// The reason for a wire code (total).
1226    pub const fn from_code(code: u8) -> Self {
1227        match code {
1228            1 => DeadLetterReason::RetryExhausted,
1229            2 => DeadLetterReason::Rejected,
1230            3 => DeadLetterReason::DecodeFailed,
1231            4 => DeadLetterReason::DeadlineExceeded,
1232            other => DeadLetterReason::Unrecognized(other),
1233        }
1234    }
1235}
1236
1237impl From<u8> for DeadLetterReason {
1238    fn from(code: u8) -> Self {
1239        Self::from_code(code)
1240    }
1241}
1242
1243impl From<DeadLetterReason> for u8 {
1244    fn from(reason: DeadLetterReason) -> u8 {
1245        reason.code()
1246    }
1247}
1248
1249/// The agent-level dead-letter capsule: the poison message's log position, the
1250/// reason, and the original payload verbatim.
1251///
1252/// The payload is the encoded [`AgentEnvelope`], byte-identical, so redrive is
1253/// trivially correct. Republish it to the source topic, or inspect it by
1254/// decoding the inner envelope. The capsule rides a dedicated dead-letter topic
1255/// in the agent stream, CBOR like everything else in AGDX. LaserData Cloud's own
1256/// dead-letter capsules stay operator-facing JSON on a different topic, for a
1257/// different audience.
1258#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1259#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1260pub struct AgentDeadLetter {
1261    pub source: LogPosition,
1262    pub reason: DeadLetterReason,
1263    pub attempts: u32,
1264    #[serde(default, skip_serializing_if = "Option::is_none")]
1265    pub detail: Option<String>,
1266    #[cfg_attr(
1267        feature = "schemars",
1268        schemars(schema_with = "crate::encoding::bytes_schema")
1269    )]
1270    #[serde(with = "crate::encoding::bin_bytes")]
1271    pub payload: Vec<u8>,
1272}
1273
1274/// An advertised skill's health, a pinned u8 dictionary (the [`TaskState`]
1275/// pattern: unknown codes pass through as [`Unrecognized`](Self::Unrecognized)).
1276#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1277#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1278#[serde(from = "u8", into = "u8")]
1279pub enum Health {
1280    Healthy,
1281    Degraded,
1282    Unavailable,
1283    /// A code this build does not know.
1284    Unrecognized(u8),
1285}
1286
1287impl Health {
1288    /// The pinned wire code.
1289    pub const fn code(self) -> u8 {
1290        match self {
1291            Health::Healthy => 1,
1292            Health::Degraded => 2,
1293            Health::Unavailable => 3,
1294            Health::Unrecognized(code) => code,
1295        }
1296    }
1297
1298    /// The health for a wire code (unknown codes become
1299    /// [`Unrecognized`](Self::Unrecognized)).
1300    pub const fn from_code(code: u8) -> Self {
1301        match code {
1302            1 => Health::Healthy,
1303            2 => Health::Degraded,
1304            3 => Health::Unavailable,
1305            other => Health::Unrecognized(other),
1306        }
1307    }
1308}
1309
1310impl From<u8> for Health {
1311    fn from(code: u8) -> Self {
1312        Self::from_code(code)
1313    }
1314}
1315
1316impl From<Health> for u8 {
1317    fn from(health: Health) -> u8 {
1318        health.code()
1319    }
1320}
1321
1322/// The content shape on a capability's input or output: either a content-type
1323/// or a registered writer-schema id. Externally tagged (`content_type` /
1324/// `schema_id`) rather than untagged: a content-type name and a schema id are
1325/// both strings, so an untagged encoding would decode a schema id literally named
1326/// `json` as [`ContentType::Json`](crate::content::ContentType::Json), and a
1327/// content-type name from a newer peer as a schema id. The tag makes the two
1328/// unambiguous and forward-safe.
1329#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1330#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1331#[serde(rename_all = "snake_case")]
1332pub enum ContentRef {
1333    ContentType(crate::content::ContentType),
1334    SchemaId(String),
1335}
1336
1337/// A structured capability on an [`AgentCard`]: which skill, its I/O content
1338/// shape, advisory cost and latency classes, concurrency, health, and load.
1339/// Mirrors the SDK A2A `AgentSkill` so the bridge maps one to the other.
1340#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1342pub struct CapabilityDescriptor {
1343    /// The skill identifier, capped like every vocabulary string.
1344    pub skill_id: String,
1345    #[serde(default, skip_serializing_if = "Option::is_none")]
1346    pub input: Option<ContentRef>,
1347    #[serde(default, skip_serializing_if = "Option::is_none")]
1348    pub output: Option<ContentRef>,
1349    /// Advisory cost class (lower is cheaper), opaque to the protocol.
1350    #[serde(default, skip_serializing_if = "Option::is_none")]
1351    pub cost_class: Option<u8>,
1352    /// Advisory latency class (lower is faster), opaque to the protocol.
1353    #[serde(default, skip_serializing_if = "Option::is_none")]
1354    pub latency_class: Option<u8>,
1355    #[serde(default, skip_serializing_if = "Option::is_none")]
1356    pub max_concurrency: Option<u32>,
1357    #[serde(default, skip_serializing_if = "Option::is_none")]
1358    pub health: Option<Health>,
1359    /// Current load, per-mille of advertised capacity.
1360    #[serde(default, skip_serializing_if = "Option::is_none")]
1361    pub load: Option<u16>,
1362}
1363
1364/// The pinned minimal body of a liveness or capability card (`status` with
1365/// `operation = card`).
1366///
1367/// Without a pinned shape every bridge and viewer invents its own card variant.
1368/// The publishing agent rides the envelope's `source`, so the card carries only
1369/// what discovery needs. Anything richer is application data in `metadata` or a
1370/// follow-up body, never new card fields by convention.
1371#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1372#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1373pub struct AgentCard {
1374    /// Human-readable display label (a viewer shows the base32 id without
1375    /// it). Capped like every vocabulary string.
1376    #[serde(default, skip_serializing_if = "Option::is_none")]
1377    pub name: Option<String>,
1378    /// The agent's own version label, opaque to the protocol.
1379    #[serde(default, skip_serializing_if = "Option::is_none")]
1380    pub version: Option<String>,
1381    /// What the agent serves: structured capability descriptors, capped in both
1382    /// count and per-entry skill-id size.
1383    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1384    pub capabilities: Vec<CapabilityDescriptor>,
1385    /// How long this card stays fresh. A card older than its ttl means a dead
1386    /// agent, the convention that makes cards liveness and not just discovery.
1387    #[serde(default, skip_serializing_if = "Option::is_none")]
1388    pub ttl_micros: Option<u64>,
1389    /// The topic the agent consumes its work on, the durable inbox a route
1390    /// resolves to when no live presence advertises one.
1391    #[serde(default, skip_serializing_if = "Option::is_none")]
1392    pub inbox: Option<String>,
1393}
1394
1395impl AgentCard {
1396    /// Check a decoded card against the caps.
1397    pub fn validate(&self) -> Result<(), ValidateError> {
1398        cap_str(self.name.as_deref(), "name")?;
1399        cap_str(self.version.as_deref(), "version")?;
1400        cap_str(self.inbox.as_deref(), "inbox")?;
1401        if self.capabilities.len() > crate::limits::MAX_CARD_CAPABILITIES {
1402            return Err(ValidateError::TooLarge {
1403                field: "capabilities",
1404                size: self.capabilities.len(),
1405                cap: crate::limits::MAX_CARD_CAPABILITIES,
1406            });
1407        }
1408        for capability in &self.capabilities {
1409            cap_str(Some(&capability.skill_id), "capability skill_id")?;
1410        }
1411        Ok(())
1412    }
1413}
1414
1415/// The live presence an agent advertises in its connection metadata
1416/// (`AGDX_SET_CLIENT_METADATA`), the body the discovery read surfaces per
1417/// connection.
1418///
1419/// Distinct from [`AgentCard`] on purpose. The card is durable, replayable
1420/// capability that outlives a brief disconnect (folded from the registry topic).
1421/// Presence is live transport truth: it vanishes on disconnect and
1422/// answers "where do I send this agent work right now," carrying the `inbox`
1423/// topic the agent is currently consuming, which may be a topic it created for
1424/// one workflow and drops when done. Routing resolves a capable agent to its
1425/// inbox through this, never through a hard-coded shared topic name, which does
1426/// not scale across users that each own their own streams and topics.
1427///
1428/// The body rides the opaque connection-metadata bytes with no envelope header,
1429/// so it carries its own version `v` ([`PRESENCE_OP_VERSION`](crate::codes::PRESENCE_OP_VERSION)).
1430/// The metadata channel stays opaque: a non-agent client advertises whatever blob
1431/// its own consumers interpret, and only an AGDX agent advertises this shape.
1432#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1433#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1434pub struct AgentPresence {
1435    /// The presence body version, carried in-band (the metadata bytes have no
1436    /// out-of-band version header).
1437    pub v: u32,
1438    /// Which agent this connection is, the link from a connection (keyed by
1439    /// `client_id`/`user_id`) to its [`AgentCard`] (keyed by agent id). A claim
1440    /// like every agent-written field, cross-checked against the verified
1441    /// `user_id` the connection authenticated as.
1442    pub agent: AgentId,
1443    /// The topic this agent currently consumes its work on, within the stream its
1444    /// connection is scoped to. Absent means liveness-only presence with no
1445    /// declared inbox, so routing falls through to another signal.
1446    #[serde(default, skip_serializing_if = "Option::is_none")]
1447    pub inbox: Option<String>,
1448}
1449
1450impl AgentPresence {
1451    /// Presence for `agent` at the current [`PRESENCE_OP_VERSION`](crate::codes::PRESENCE_OP_VERSION),
1452    /// with no declared inbox yet.
1453    pub fn new(agent: AgentId) -> Self {
1454        Self {
1455            v: crate::codes::PRESENCE_OP_VERSION,
1456            agent,
1457            inbox: None,
1458        }
1459    }
1460
1461    /// Declare the `inbox` topic this agent consumes its work on.
1462    pub fn with_inbox(mut self, inbox: impl Into<String>) -> Self {
1463        self.inbox = Some(inbox.into());
1464        self
1465    }
1466
1467    /// Check a decoded presence body against the caps: the inbox topic is bounded
1468    /// like every vocabulary string.
1469    pub fn validate(&self) -> Result<(), ValidateError> {
1470        cap_str(self.inbox.as_deref(), "inbox")?;
1471        Ok(())
1472    }
1473}
1474
1475/// The claim-check capsule a `agdx.ct = ref` body carries.
1476///
1477/// The content lives elsewhere (object storage, the KV store, another topic).
1478/// The record carries where it lives, how big it is, and a digest, so any
1479/// consumer verifies the fetched bytes against the log without trusting the
1480/// store. The envelope and the validity matrix are untouched: a referenced
1481/// body is still a `body`, just one whose bytes are a `BodyRef` instead of the
1482/// content itself.
1483#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1485pub struct BodyRef {
1486    /// Where the bytes live: a URI, object key, or KV key. Bounded by
1487    /// [`MAX_BODY_REFERENCE_BYTES`](crate::limits::MAX_BODY_REFERENCE_BYTES).
1488    pub reference: String,
1489    /// The externalized content's size in bytes.
1490    pub size_bytes: u64,
1491    /// SHA-256 of the externalized content, exactly 32 bytes as a CBOR byte string.
1492    #[cfg_attr(
1493        feature = "schemars",
1494        schemars(schema_with = "crate::encoding::bytes_schema")
1495    )]
1496    #[serde(with = "crate::encoding::bin_bytes")]
1497    pub sha256: Vec<u8>,
1498    /// Encryption scheme code, dormant like [`Signature::scheme`]. Absent means
1499    /// plaintext. Codes are assigned when the key registry (the same registry
1500    /// signatures verify against) lands.
1501    #[serde(default, skip_serializing_if = "Option::is_none")]
1502    pub encryption: Option<u8>,
1503}
1504
1505const SHA256_BYTES: usize = 32;
1506
1507impl BodyRef {
1508    /// A plaintext reference to externalized content.
1509    pub fn new(reference: impl Into<String>, size_bytes: u64, sha256: [u8; 32]) -> Self {
1510        Self {
1511            reference: reference.into(),
1512            size_bytes,
1513            sha256: sha256.to_vec(),
1514            encryption: None,
1515        }
1516    }
1517
1518    /// Check a decoded capsule: non-empty bounded `reference`, 32-byte digest.
1519    ///
1520    /// Receivers run it after decode. [`new`](Self::new) is valid by construction.
1521    pub fn validate(&self) -> Result<(), ValidateError> {
1522        if self.reference.is_empty() {
1523            return Err(ValidateError::Invalid {
1524                field: "reference",
1525                reason: "reference must not be empty".to_owned(),
1526            });
1527        }
1528        if self.reference.len() > crate::limits::MAX_BODY_REFERENCE_BYTES {
1529            return Err(ValidateError::TooLarge {
1530                field: "reference",
1531                size: self.reference.len(),
1532                cap: crate::limits::MAX_BODY_REFERENCE_BYTES,
1533            });
1534        }
1535        if self.sha256.len() != SHA256_BYTES {
1536            return Err(ValidateError::Invalid {
1537                field: "sha256",
1538                reason: format!(
1539                    "digest must be {SHA256_BYTES} bytes, got {}",
1540                    self.sha256.len()
1541                ),
1542            });
1543        }
1544        Ok(())
1545    }
1546}
1547
1548/// A detached envelope signature: designed but dormant.
1549///
1550/// The type exists so the future opt-in (per-agent keys, consumer-side
1551/// verification against a key registry) is an additive
1552/// `signature: Option<Signature>` envelope field, not a redesign. No crypto
1553/// dependency enters this crate. Signing and verification live SDK-side.
1554///
1555/// Field sizes are scheme-discriminated, so the `scheme` byte exists precisely
1556/// to keep the type from welding to one algorithm. The wire fields are bounded
1557/// bytes, [`validate`](Self::validate) enforces the registered per-scheme
1558/// lengths, and unknown schemes pass through.
1559#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1560#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1561pub struct Signature {
1562    /// The signing scheme code ([`SIGNATURE_SCHEME_ED25519`] = 1). Codes are
1563    /// permanent, and unknown codes pass through like every open dictionary.
1564    pub scheme: u8,
1565    /// Which of the agent's registered keys signed (8 bytes for Ed25519).
1566    #[cfg_attr(
1567        feature = "schemars",
1568        schemars(schema_with = "crate::encoding::bytes_schema")
1569    )]
1570    #[serde(with = "crate::encoding::bin_bytes")]
1571    pub key_id: Vec<u8>,
1572    /// The signature over the canonical envelope encoding (signature field
1573    /// absent), domain-separated (64 bytes for Ed25519).
1574    #[cfg_attr(
1575        feature = "schemars",
1576        schemars(schema_with = "crate::encoding::bytes_schema")
1577    )]
1578    #[serde(with = "crate::encoding::bin_bytes")]
1579    pub bytes: Vec<u8>,
1580    /// Out-of-band interpretation attributes the signature also covers, so an
1581    /// intermediary cannot flip the codec (`agdx.ct`) or wire version (`agdx.av`)
1582    /// on a signed record without invalidating it. Folded into the signed preimage
1583    /// when present. Skip-none, so a context-less signature stays byte-identical to
1584    /// a pre-context one (an older signer, or a body whose interpretation is fixed).
1585    #[serde(default, skip_serializing_if = "Option::is_none")]
1586    pub context: Option<SignatureContext>,
1587}
1588
1589/// The interpretation-bearing attributes a [`Signature`] binds beyond the
1590/// envelope body: the content-type code (`agdx.ct`) and wire version (`agdx.av`)
1591/// a consumer reads to select its codec and decoder. Riding unsigned headers,
1592/// these would let an intermediary reinterpret a signed record. Folded into the
1593/// preimage here, a change invalidates the signature.
1594#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1595#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1596pub struct SignatureContext {
1597    /// The `agdx.ct` content-type code the body is encoded with.
1598    #[serde(default, skip_serializing_if = "Option::is_none")]
1599    pub content_type: Option<u8>,
1600    /// The `agdx.av` wire version the envelope is stamped with.
1601    #[serde(default, skip_serializing_if = "Option::is_none")]
1602    pub agent_version: Option<u32>,
1603}
1604
1605/// The Ed25519 signing scheme code.
1606pub const SIGNATURE_SCHEME_ED25519: u8 = 1;
1607
1608/// The domain separator prefixed to the canonical envelope encoding before
1609/// signing, so an AGDX signature can never be replayed into another protocol.
1610/// The canonical encoding is this crate's own: named-field CBOR, fields in
1611/// declaration order, absent optionals skipped, the signature field absent.
1612pub const SIGNATURE_DOMAIN: &[u8] = b"agdx.signature.v1";
1613
1614const ED25519_KEY_ID_BYTES: usize = 8;
1615const ED25519_SIGNATURE_BYTES: usize = 64;
1616
1617impl Signature {
1618    /// Check a signature capsule against its scheme's registered lengths.
1619    ///
1620    /// Unknown scheme codes validate, so future schemes flow through old
1621    /// consumers. Verification itself is SDK-side and scheme-aware.
1622    pub fn validate(&self) -> Result<(), ValidateError> {
1623        if self.scheme != SIGNATURE_SCHEME_ED25519 {
1624            return Ok(());
1625        }
1626        if self.key_id.len() != ED25519_KEY_ID_BYTES {
1627            return Err(ValidateError::Invalid {
1628                field: "key_id",
1629                reason: format!(
1630                    "Ed25519 key id must be {ED25519_KEY_ID_BYTES} bytes, got {}",
1631                    self.key_id.len()
1632                ),
1633            });
1634        }
1635        if self.bytes.len() != ED25519_SIGNATURE_BYTES {
1636            return Err(ValidateError::Invalid {
1637                field: "bytes",
1638                reason: format!(
1639                    "Ed25519 signature must be {ED25519_SIGNATURE_BYTES} bytes, got {}",
1640                    self.bytes.len()
1641                ),
1642            });
1643        }
1644        Ok(())
1645    }
1646}
1647
1648/// The AGDX envelope: one CBOR named-field decode unit per agent message.
1649///
1650/// Field semantics, the per-kind validity matrix, and the caps are enforced by
1651/// [`validate`], and the per-kind constructors stamp the required shape. Routing
1652/// fields (`conversation`, `target`, content type) are also stamped as typed
1653/// headers so projections and plain Iggy consumers work without decoding
1654/// bodies. The envelope is the typed, versioned form of what the headers say.
1655///
1656/// `metadata` is the AGDX-native extension slot, distinct from headers (the
1657/// substrate and observability dictionary) and `body` (the content). Foreign
1658/// metadata (A2A `metadata`, MCP `_meta`) never maps into it. It tunnels whole
1659/// inside `body`, keeping bridge round trips byte-identical.
1660#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1662pub struct AgentEnvelope {
1663    pub kind: AgentKind,
1664    /// Producer-assigned record identity, required on every kind except
1665    /// `chunk` (chunks are identified by `channel` + `sequence`, saving the
1666    /// id bytes and a clock-and-entropy call per token).
1667    #[serde(default, skip_serializing_if = "Option::is_none")]
1668    pub record: Option<RecordId>,
1669    /// Also the partition key.
1670    pub conversation: ConversationId,
1671    /// The session this conversation was spawned from.
1672    #[serde(default, skip_serializing_if = "Option::is_none")]
1673    pub parent: Option<ConversationId>,
1674    /// The first conversation in this session tree.
1675    #[serde(default, skip_serializing_if = "Option::is_none")]
1676    pub root: Option<ConversationId>,
1677    /// Agent-authorship claim (see the module docs).
1678    pub source: AgentId,
1679    /// Routing refinement within a shared topic. The topic itself is the
1680    /// primary address. Consumer-side filtering by `target` is a convenience,
1681    /// not a confidentiality control. The topic is the boundary.
1682    #[serde(default, skip_serializing_if = "Option::is_none")]
1683    pub target: Option<AgentId>,
1684    /// The causal parent's record id: the identity half of the causal pointer,
1685    /// stable across replication.
1686    #[serde(default, skip_serializing_if = "Option::is_none")]
1687    pub cause: Option<RecordId>,
1688    /// The causal parent's log position: the locator half, an O(1) dereference
1689    /// for raw log walkers, deployment-local.
1690    #[serde(default, skip_serializing_if = "Option::is_none")]
1691    pub cause_at: Option<LogPosition>,
1692    /// Request/reply pairing. A2A task identity maps onto it.
1693    #[serde(default, skip_serializing_if = "Option::is_none")]
1694    pub correlation: Option<CorrelationId>,
1695    /// Chunk grouping when many streams run under one correlation.
1696    #[serde(default, skip_serializing_if = "Option::is_none")]
1697    pub channel: Option<ChannelId>,
1698    #[serde(default, skip_serializing_if = "Option::is_none")]
1699    pub idempotency_key: Option<IdempotencyKey>,
1700    /// Drop-dead time, epoch micros. On a stream-opening message it is also
1701    /// the reader-local abandonment bound: the producer knows its own model
1702    /// timeout, the consumer would be guessing.
1703    #[serde(default, skip_serializing_if = "Option::is_none")]
1704    pub deadline_micros: Option<u64>,
1705    /// Chunk ordering within a channel.
1706    #[serde(default, skip_serializing_if = "Option::is_none")]
1707    pub sequence: Option<u64>,
1708    /// Terminal flag: the final chunk of a stream / the final task update.
1709    /// `false` is equivalent to absence and is skipped on encode, so only `true`
1710    /// has protocol meaning. Maps one-to-one onto A2A's `final`.
1711    #[serde(default, skip_serializing_if = "is_false")]
1712    pub last: bool,
1713    /// Why a stream or response ended (OTel finish-reason vocabulary: stop,
1714    /// length, content_filter, tool_call, ...). A string deliberately: that
1715    /// vocabulary belongs to OTel and the providers, not to us.
1716    #[serde(default, skip_serializing_if = "Option::is_none")]
1717    pub finish_reason: Option<String>,
1718    #[serde(default, skip_serializing_if = "Option::is_none")]
1719    pub task_state: Option<TaskState>,
1720    /// OTel `gen_ai.operation.name` value (`chat`, `execute_tool`, ...). On
1721    /// `status` it is the required discriminator (`task`, `card`, `progress`).
1722    #[serde(default, skip_serializing_if = "Option::is_none")]
1723    pub operation: Option<String>,
1724    /// OTel `gen_ai.tool.name`, for tool commands and results.
1725    #[serde(default, skip_serializing_if = "Option::is_none")]
1726    pub tool: Option<String>,
1727    #[serde(default, skip_serializing_if = "Option::is_none")]
1728    pub usage: Option<TokenUsage>,
1729    /// AGDX-native scalar extension context. Never foreign metadata.
1730    #[serde(default, skip_serializing_if = "Option::is_none")]
1731    pub metadata: Option<BTreeMap<String, Value>>,
1732    /// Must-understand marker: a bitset of feature bits a receiver MUST
1733    /// understand to process this message correctly (see [`features`]). A
1734    /// receiver that sees a set bit it does not implement MUST reject or
1735    /// dead-letter the message rather than mis-handle it ([`unmet_requirements`]).
1736    /// `0` (the default, skipped on the wire so pre-marker records stay
1737    /// byte-identical) means "ignore anything you don't understand", the
1738    /// open-world default. This lets one message demand strict handling of a new
1739    /// feature without a whole-envelope version bump (a `must_understand` marker).
1740    ///
1741    /// [`features`]: crate::agent::features
1742    /// [`unmet_requirements`]: AgentEnvelope::unmet_requirements
1743    #[serde(default, skip_serializing_if = "is_zero_u64")]
1744    pub must_understand: u64,
1745    /// The content, codec per the `agdx.ct` header. Default-empty and skipped
1746    /// when empty. The validity matrix says which kinds require it.
1747    #[cfg_attr(
1748        feature = "schemars",
1749        schemars(schema_with = "crate::encoding::bytes_schema")
1750    )]
1751    #[serde(
1752        default,
1753        skip_serializing_if = "Vec::is_empty",
1754        with = "crate::encoding::bin_bytes"
1755    )]
1756    pub body: Vec<u8>,
1757    /// A detached signature over the canonical encoding of this envelope with the
1758    /// signature field absent, domain-separated by [`SIGNATURE_DOMAIN`]. Opt-in:
1759    /// absent (the open-world default, skipped on the wire so an unsigned record
1760    /// stays byte-identical) means an unsigned record. Verification is SDK-side
1761    /// against a per-agent key registry, so the wire crate stays crypto-free. A
1762    /// signature may ride any kind (no matrix row, like `metadata`).
1763    #[serde(default, skip_serializing_if = "Option::is_none")]
1764    pub signature: Option<Signature>,
1765}
1766
1767fn is_false(value: &bool) -> bool {
1768    !*value
1769}
1770
1771fn is_zero_u64(value: &u64) -> bool {
1772    *value == 0
1773}
1774
1775/// Must-understand feature bits for [`AgentEnvelope::must_understand`]. Each
1776/// constant names one capability a message may demand a receiver implement.
1777/// Defined additively as features land: a newer producer sets a bit an older
1778/// receiver does not know, and that receiver rejects rather than mis-handling
1779/// the message. No bits are defined yet, so today the marker is the mechanism
1780/// in place for the first feature that needs strict handling.
1781pub mod features {
1782    /// A receiver's full understood set is the OR of the bits it implements.
1783    /// With no feature bits defined yet, a current build understands none and
1784    /// only ever sees `must_understand == 0`.
1785    pub const NONE: u64 = 0;
1786}
1787
1788impl AgentEnvelope {
1789    fn base(kind: AgentKind, conversation: ConversationId, source: AgentId) -> Self {
1790        Self {
1791            kind,
1792            record: None,
1793            conversation,
1794            parent: None,
1795            root: None,
1796            source,
1797            target: None,
1798            cause: None,
1799            cause_at: None,
1800            correlation: None,
1801            channel: None,
1802            idempotency_key: None,
1803            deadline_micros: None,
1804            sequence: None,
1805            last: false,
1806            finish_reason: None,
1807            task_state: None,
1808            operation: None,
1809            tool: None,
1810            usage: None,
1811            metadata: None,
1812            must_understand: 0,
1813            body: Vec::new(),
1814            signature: None,
1815        }
1816    }
1817
1818    /// Declare that a receiver MUST understand the feature `bits` to process this
1819    /// message. Bits a receiver lacks make it reject the message
1820    /// ([`unmet_requirements`](Self::unmet_requirements)). Absent bits are
1821    /// ignore-if-unknown. Additive builder method.
1822    #[must_use]
1823    pub fn requiring(mut self, bits: u64) -> Self {
1824        self.must_understand = bits;
1825        self
1826    }
1827
1828    /// The subset of this message's [`must_understand`](Self::must_understand)
1829    /// bits NOT present in the receiver's `understood` set. Non-zero means the
1830    /// receiver cannot safely process the message and must reject or
1831    /// dead-letter it rather than mis-handle a feature it does not implement.
1832    pub fn unmet_requirements(&self, understood: u64) -> u64 {
1833        self.must_understand & !understood
1834    }
1835
1836    /// A `command`: expects a reply or effect, so `correlation` is required.
1837    pub fn command(
1838        record: RecordId,
1839        conversation: ConversationId,
1840        source: AgentId,
1841        correlation: CorrelationId,
1842        body: Vec<u8>,
1843    ) -> Self {
1844        let mut envelope = Self::base(AgentKind::Command, conversation, source);
1845        envelope.record = Some(record);
1846        envelope.correlation = Some(correlation);
1847        envelope.body = body;
1848        envelope
1849    }
1850
1851    /// A `response`: the paired answer to a command (same `correlation`).
1852    pub fn response(
1853        record: RecordId,
1854        conversation: ConversationId,
1855        source: AgentId,
1856        correlation: CorrelationId,
1857        body: Vec<u8>,
1858    ) -> Self {
1859        let mut envelope = Self::base(AgentKind::Response, conversation, source);
1860        envelope.record = Some(record);
1861        envelope.correlation = Some(correlation);
1862        envelope.body = body;
1863        envelope
1864    }
1865
1866    /// An `event`: expects nothing.
1867    pub fn event(
1868        record: RecordId,
1869        conversation: ConversationId,
1870        source: AgentId,
1871        body: Vec<u8>,
1872    ) -> Self {
1873        let mut envelope = Self::base(AgentKind::Event, conversation, source);
1874        envelope.record = Some(record);
1875        envelope.body = body;
1876        envelope
1877    }
1878
1879    /// A `chunk` of the stream `channel`, ordered by `sequence`. Mark the
1880    /// final one with [`terminal`](Self::terminal).
1881    pub fn chunk(
1882        conversation: ConversationId,
1883        source: AgentId,
1884        correlation: CorrelationId,
1885        channel: ChannelId,
1886        sequence: u64,
1887        body: Vec<u8>,
1888    ) -> Self {
1889        let mut envelope = Self::base(AgentKind::Chunk, conversation, source);
1890        envelope.correlation = Some(correlation);
1891        envelope.channel = Some(channel);
1892        envelope.sequence = Some(sequence);
1893        envelope.body = body;
1894        envelope
1895    }
1896
1897    /// A `status` signal discriminated by `operation` (`task`, `card`,
1898    /// `progress`). Task updates additionally require `correlation` and
1899    /// `task_state` (use the with-setters).
1900    pub fn status(
1901        record: RecordId,
1902        conversation: ConversationId,
1903        source: AgentId,
1904        operation: impl Into<String>,
1905    ) -> Self {
1906        let mut envelope = Self::base(AgentKind::Status, conversation, source);
1907        envelope.record = Some(record);
1908        envelope.operation = Some(operation.into());
1909        envelope
1910    }
1911
1912    /// An `error` terminal for `correlation`. `body` is the encoded
1913    /// [`AgentErrorBody`].
1914    pub fn error(
1915        record: RecordId,
1916        conversation: ConversationId,
1917        source: AgentId,
1918        correlation: CorrelationId,
1919        body: Vec<u8>,
1920    ) -> Self {
1921        let mut envelope = Self::base(AgentKind::Error, conversation, source);
1922        envelope.record = Some(record);
1923        envelope.correlation = Some(correlation);
1924        envelope.body = body;
1925        envelope
1926    }
1927
1928    /// Narrow delivery to one agent within a shared topic.
1929    pub fn with_target(mut self, target: AgentId) -> Self {
1930        self.target = Some(target);
1931        self
1932    }
1933
1934    /// Stamp the causal parent: its record id (identity) and, when known, its
1935    /// log position (locator). A handler has both for free from the message it
1936    /// is replying to.
1937    pub fn with_cause(mut self, cause: RecordId, cause_at: Option<LogPosition>) -> Self {
1938        self.cause = Some(cause);
1939        self.cause_at = cause_at;
1940        self
1941    }
1942
1943    /// Pair this message with a correlation id. Required on `command`,
1944    /// `response`, `error`, and `chunk`. Optional on `event` and non-task
1945    /// `status`.
1946    pub fn with_correlation(mut self, correlation: CorrelationId) -> Self {
1947        self.correlation = Some(correlation);
1948        self
1949    }
1950
1951    /// Attach a business idempotency key (commands, responses, events only).
1952    pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
1953        self.idempotency_key = Some(key);
1954        self
1955    }
1956
1957    /// Declare the drop-dead time (and, on a stream-opening message, the
1958    /// abandonment bound).
1959    pub fn with_deadline_micros(mut self, deadline_micros: u64) -> Self {
1960        self.deadline_micros = Some(deadline_micros);
1961        self
1962    }
1963
1964    /// Mark this message terminal (`last = true`), with the reason the stream
1965    /// or response ended.
1966    pub fn terminal(mut self, finish_reason: impl Into<String>) -> Self {
1967        self.last = true;
1968        self.finish_reason = Some(finish_reason.into());
1969        self
1970    }
1971
1972    /// Attach a task state. Status task updates require it. Responses and
1973    /// errors may carry it as the one-message terminal convenience.
1974    pub fn with_task_state(mut self, state: TaskState) -> Self {
1975        self.task_state = Some(state);
1976        self
1977    }
1978
1979    /// Set the OTel operation name.
1980    pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
1981        self.operation = Some(operation.into());
1982        self
1983    }
1984
1985    /// Set the OTel tool name.
1986    pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
1987        self.tool = Some(tool.into());
1988        self
1989    }
1990
1991    /// Attach token accounting (advisory).
1992    pub fn with_usage(mut self, usage: TokenUsage) -> Self {
1993        self.usage = Some(usage);
1994        self
1995    }
1996
1997    /// Add one AGDX-native metadata entry.
1998    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
1999        self.metadata
2000            .get_or_insert_with(BTreeMap::new)
2001            .insert(key.into(), value.into());
2002        self
2003    }
2004
2005    /// Attach a detached [`Signature`] over this envelope. The SDK signs the
2006    /// canonical encoding with the signature absent and domain separator
2007    /// [`SIGNATURE_DOMAIN`], so the field is set last. A signature may ride any
2008    /// kind.
2009    pub fn with_signature(mut self, signature: Signature) -> Self {
2010        self.signature = Some(signature);
2011        self
2012    }
2013}
2014
2015/// A validity-matrix or cap violation. Receivers treat these as protocol
2016/// errors rather than guessing, and the SDK rejects them at publish time.
2017#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2018#[non_exhaustive]
2019pub enum ValidateError {
2020    #[error("{kind} requires `{field}`")]
2021    Missing {
2022        kind: AgentKind,
2023        field: &'static str,
2024    },
2025    #[error("`{field}` is invalid on {kind}")]
2026    Forbidden {
2027        kind: AgentKind,
2028        field: &'static str,
2029    },
2030    #[error("`{field}` is {size}B, exceeds cap {cap}B")]
2031    TooLarge {
2032        field: &'static str,
2033        size: usize,
2034        cap: usize,
2035    },
2036    #[error("`{field}`: {reason}")]
2037    Invalid { field: &'static str, reason: String },
2038}
2039
2040// The per-kind validity matrix, mechanical. R = required, O = optional,
2041// X = invalid:
2042//
2043// | field            | command | response | event | chunk | status | error |
2044// |------------------|---------|----------|-------|-------|--------|-------|
2045// | record           | R       | R        | R     | O     | R      | R     |
2046// | conversation     | R       | R        | R     | R     | R      | R     |
2047// | source           | R       | R        | R     | R     | R      | R     |
2048// | target           | O       | O        | O     | O     | O      | O     |
2049// | cause / cause_at | O       | O        | O     | O     | O      | O     |
2050// | correlation      | R       | R        | O     | R     | O (R task) | R |
2051// | channel          | X       | X        | X     | R     | X      | O     |
2052// | sequence         | X       | X        | X     | R     | X      | O (with channel) |
2053// | last             | X       | X        | X     | O     | O      | X (always terminal) |
2054// | finish_reason    | X       | O        | X     | O (with last) | X | X  |
2055// | idempotency_key  | O       | O        | O     | X     | X      | X     |
2056// | deadline_micros  | O       | X        | X     | O     | R quarantine|unquarantine, X otherwise | X |
2057// | task_state       | X       | O        | X     | X     | R (task|session) | O |
2058// | operation        | O       | O        | O     | R seq 0 (chat|reasoning|tool_args), X after | R (task|session|card|progress|quarantine|unquarantine) | O |
2059// | tool             | O       | O        | O     | O     | X      | O     |
2060// | usage            | X       | O        | O     | O (terminal) | O | O  |
2061// | metadata         | O       | O        | O     | O     | O      | O     |
2062// | body             | R       | R        | R     | R (may be empty with last) | R session, O otherwise | R |
2063/// Check an envelope against the per-kind validity matrix and the caps.
2064pub fn validate(envelope: &AgentEnvelope) -> Result<(), ValidateError> {
2065    use AgentKind::*;
2066    let kind = envelope.kind;
2067
2068    let require = |present: bool, field: &'static str| {
2069        if present {
2070            Ok(())
2071        } else {
2072            Err(ValidateError::Missing { kind, field })
2073        }
2074    };
2075    let forbid = |absent: bool, field: &'static str| {
2076        if absent {
2077            Ok(())
2078        } else {
2079            Err(ValidateError::Forbidden { kind, field })
2080        }
2081    };
2082
2083    // record: required everywhere except chunk (where it is optional).
2084    if kind != Chunk {
2085        require(envelope.record.is_some(), "record")?;
2086    }
2087
2088    if envelope.root.is_some() && envelope.parent.is_none() {
2089        return Err(ValidateError::Invalid {
2090            field: "root",
2091            reason: "root requires parent".to_owned(),
2092        });
2093    }
2094    if envelope.parent == Some(envelope.conversation)
2095        || envelope.root == Some(envelope.conversation)
2096    {
2097        return Err(ValidateError::Invalid {
2098            field: "parent",
2099            reason: "parent and root must differ from conversation".to_owned(),
2100        });
2101    }
2102
2103    // correlation.
2104    match kind {
2105        Command | Response | Chunk | Error => {
2106            require(envelope.correlation.is_some(), "correlation")?
2107        }
2108        Status => {
2109            if envelope.operation.as_deref() == Some(OPERATION_TASK) {
2110                require(envelope.correlation.is_some(), "correlation")?;
2111            }
2112        }
2113        Event => {}
2114    }
2115
2116    // channel + sequence: the chunk identity, allowed on error as a stream
2117    // terminal, sequence only alongside channel.
2118    match kind {
2119        Chunk => {
2120            require(envelope.channel.is_some(), "channel")?;
2121            require(envelope.sequence.is_some(), "sequence")?;
2122        }
2123        Error => {
2124            if envelope.sequence.is_some() && envelope.channel.is_none() {
2125                return Err(ValidateError::Invalid {
2126                    field: "sequence",
2127                    reason: "sequence requires channel".to_owned(),
2128                });
2129            }
2130        }
2131        _ => {
2132            forbid(envelope.channel.is_none(), "channel")?;
2133            forbid(envelope.sequence.is_none(), "sequence")?;
2134        }
2135    }
2136
2137    // last: chunk and status only (error is always terminal, so the flag
2138    // would be redundant noise there).
2139    if envelope.last && !matches!(kind, Chunk | Status) {
2140        return Err(ValidateError::Forbidden {
2141            kind,
2142            field: "last",
2143        });
2144    }
2145
2146    // finish_reason: responses, and terminal chunks.
2147    match kind {
2148        Response => {}
2149        Chunk => {
2150            if envelope.finish_reason.is_some() && !envelope.last {
2151                return Err(ValidateError::Invalid {
2152                    field: "finish_reason",
2153                    reason: "finish_reason rides only the terminal chunk".to_owned(),
2154                });
2155            }
2156        }
2157        _ => forbid(envelope.finish_reason.is_none(), "finish_reason")?,
2158    }
2159
2160    // idempotency_key: business idempotency for command/response/event.
2161    // Chunks and signals carry no dedup semantics.
2162    if matches!(kind, Chunk | Status | Error) {
2163        forbid(envelope.idempotency_key.is_none(), "idempotency_key")?;
2164    }
2165
2166    // deadline_micros: commands, stream-opening chunks (the abandonment bound
2167    // rides sequence 0, and a mid-stream deadline would be ambiguous), and
2168    // registry facts, where it is the signed expiry that bounds a replay.
2169    let registry_fact = kind == Status
2170        && matches!(
2171            envelope.operation.as_deref(),
2172            Some(OPERATION_QUARANTINE | OPERATION_UNQUARANTINE)
2173        );
2174    if registry_fact {
2175        require(envelope.deadline_micros.is_some(), "deadline_micros")?;
2176    } else if matches!(kind, Response | Event | Status | Error) {
2177        forbid(envelope.deadline_micros.is_none(), "deadline_micros")?;
2178    }
2179    if kind == Chunk && envelope.deadline_micros.is_some() && envelope.sequence != Some(0) {
2180        return Err(ValidateError::Invalid {
2181            field: "deadline_micros",
2182            reason: "the stream bound rides the opening chunk (sequence 0)".to_owned(),
2183        });
2184    }
2185
2186    // task_state.
2187    match kind {
2188        Status => {
2189            if matches!(
2190                envelope.operation.as_deref(),
2191                Some(OPERATION_TASK | OPERATION_SESSION)
2192            ) {
2193                require(envelope.task_state.is_some(), "task_state")?;
2194            }
2195        }
2196        Response | Error => {}
2197        _ => forbid(envelope.task_state.is_none(), "task_state")?,
2198    }
2199
2200    // operation: two CLOSED vocabularies (protocol machinery, version-gated
2201    // like AgentKind), open OTel values everywhere else. The status
2202    // discriminator must be task | session | card | progress, and the chunk-stream purpose
2203    // must be chat | reasoning | tool_args and rides ONLY the opening chunk
2204    // (sequence 0), where it is required.
2205    match kind {
2206        Status => {
2207            require(envelope.operation.is_some(), "operation")?;
2208            if let Some(operation) = envelope.operation.as_deref()
2209                && !matches!(
2210                    operation,
2211                    OPERATION_TASK
2212                        | OPERATION_SESSION
2213                        | OPERATION_CARD
2214                        | OPERATION_PROGRESS
2215                        | OPERATION_QUARANTINE
2216                        | OPERATION_UNQUARANTINE
2217                )
2218            {
2219                return Err(ValidateError::Invalid {
2220                    field: "operation",
2221                    reason: format!(
2222                        "status operation must be `{OPERATION_TASK}`, `{OPERATION_SESSION}`, `{OPERATION_CARD}`, \
2223                         `{OPERATION_PROGRESS}`, `{OPERATION_QUARANTINE}`, or \
2224                         `{OPERATION_UNQUARANTINE}`, got `{operation}`"
2225                    ),
2226                });
2227            }
2228        }
2229        Chunk => {
2230            if envelope.sequence == Some(0) {
2231                require(envelope.operation.is_some(), "operation")?;
2232            }
2233            if let Some(operation) = envelope.operation.as_deref() {
2234                if envelope.sequence != Some(0) {
2235                    return Err(ValidateError::Invalid {
2236                        field: "operation",
2237                        reason: "the stream purpose rides the opening chunk (sequence 0)"
2238                            .to_owned(),
2239                    });
2240                }
2241                if !matches!(
2242                    operation,
2243                    OPERATION_CHAT | OPERATION_REASONING | OPERATION_TOOL_ARGS
2244                ) {
2245                    return Err(ValidateError::Invalid {
2246                        field: "operation",
2247                        reason: format!(
2248                            "chunk-stream purpose must be `{OPERATION_CHAT}`, \
2249                             `{OPERATION_REASONING}`, or `{OPERATION_TOOL_ARGS}`, \
2250                             got `{operation}`"
2251                        ),
2252                    });
2253                }
2254            }
2255        }
2256        Command | Response | Event | Error => {}
2257    }
2258
2259    // tool: meaningless on status signals.
2260    if kind == Status {
2261        forbid(envelope.tool.is_none(), "tool")?;
2262    }
2263
2264    // usage: terminal-chunk accounting, never on commands.
2265    match kind {
2266        Command => forbid(envelope.usage.is_none(), "usage")?,
2267        Chunk if envelope.usage.is_some() && !envelope.last => {
2268            return Err(ValidateError::Invalid {
2269                field: "usage",
2270                reason: "whole-stream accounting rides the terminal chunk".to_owned(),
2271            });
2272        }
2273        _ => {}
2274    }
2275
2276    // body.
2277    match kind {
2278        Status if envelope.operation.as_deref() == Some(OPERATION_SESSION) => {
2279            require(!envelope.body.is_empty(), "body")?;
2280            let state = envelope
2281                .task_state
2282                .expect("session state was required above");
2283            if envelope.last != state.is_terminal() {
2284                return Err(ValidateError::Invalid {
2285                    field: "last",
2286                    reason: "session last must match terminal task state".to_owned(),
2287                });
2288            }
2289            // The body shape is checked where the CBOR codec is built in.
2290            #[cfg(feature = "cbor")]
2291            {
2292                let invalid_body = |reason: String| ValidateError::Invalid {
2293                    field: "body",
2294                    reason,
2295                };
2296                let validate_start = |start: &SessionStart| {
2297                    crate::validate::Validate::validate(start)
2298                        .map_err(|error| invalid_body(error.to_string()))?;
2299                    if start.parent != envelope.parent || start.root != envelope.root {
2300                        return Err(invalid_body(
2301                            "session ancestry must match envelope parent and root".to_owned(),
2302                        ));
2303                    }
2304                    Ok(())
2305                };
2306                match state {
2307                    TaskState::Submitted => {
2308                        let start: SessionStart = crate::framing::decode_named(&envelope.body)
2309                            .map_err(|error| invalid_body(error.to_string()))?;
2310                        validate_start(&start)?;
2311                    }
2312                    TaskState::Working => {
2313                        let body: ciborium::value::Value =
2314                            crate::framing::decode_named(&envelope.body)
2315                                .map_err(|error| invalid_body(error.to_string()))?;
2316                        let is_start = matches!(
2317                            body,
2318                            ciborium::value::Value::Map(ref entries)
2319                                if entries.iter().any(|(key, _)| {
2320                                    matches!(key, ciborium::value::Value::Text(name) if name == "agent" || name == "sdk")
2321                                })
2322                        );
2323                        if is_start {
2324                            let start: SessionStart = crate::framing::decode_named(&envelope.body)
2325                                .map_err(|error| invalid_body(error.to_string()))?;
2326                            validate_start(&start)?;
2327                        } else {
2328                            crate::framing::decode_named::<SessionTransition>(&envelope.body)
2329                                .map_err(|error| invalid_body(error.to_string()))?;
2330                        }
2331                    }
2332                    state if state.is_terminal() => {
2333                        crate::framing::decode_named::<SessionEnd>(&envelope.body)
2334                            .map_err(|error| invalid_body(error.to_string()))?;
2335                    }
2336                    _ => {
2337                        crate::framing::decode_named::<SessionTransition>(&envelope.body)
2338                            .map_err(|error| invalid_body(error.to_string()))?;
2339                    }
2340                }
2341            }
2342        }
2343        Status => {}
2344        Chunk => {
2345            if envelope.body.is_empty() && !envelope.last {
2346                return Err(ValidateError::Missing {
2347                    kind,
2348                    field: "body",
2349                });
2350            }
2351        }
2352        _ => require(!envelope.body.is_empty(), "body")?,
2353    }
2354
2355    // Caps. The metadata caps are the load-bearing ones: that field is
2356    // bridge-injected and foreign-influenced, so a hostile edge gets a
2357    // publish-time rejection instead of inflating every record on a topic.
2358    cap_str(envelope.operation.as_deref(), "operation")?;
2359    cap_str(envelope.tool.as_deref(), "tool")?;
2360    cap_str(envelope.finish_reason.as_deref(), "finish_reason")?;
2361    if let Some(metadata) = &envelope.metadata {
2362        if metadata.len() > crate::limits::MAX_METADATA_ENTRIES {
2363            return Err(ValidateError::TooLarge {
2364                field: "metadata",
2365                size: metadata.len(),
2366                cap: crate::limits::MAX_METADATA_ENTRIES,
2367            });
2368        }
2369        let mut total = 0usize;
2370        for (key, value) in metadata {
2371            if key.len() > crate::limits::MAX_METADATA_KEY_BYTES {
2372                return Err(ValidateError::TooLarge {
2373                    field: "metadata key",
2374                    size: key.len(),
2375                    cap: crate::limits::MAX_METADATA_KEY_BYTES,
2376                });
2377            }
2378            let value_size = value_size(value);
2379            if value_size > crate::limits::MAX_METADATA_VALUE_BYTES {
2380                return Err(ValidateError::TooLarge {
2381                    field: "metadata value",
2382                    size: value_size,
2383                    cap: crate::limits::MAX_METADATA_VALUE_BYTES,
2384                });
2385            }
2386            total += key.len() + value_size;
2387        }
2388        if total > crate::limits::MAX_METADATA_TOTAL_BYTES {
2389            return Err(ValidateError::TooLarge {
2390                field: "metadata",
2391                size: total,
2392                cap: crate::limits::MAX_METADATA_TOTAL_BYTES,
2393            });
2394        }
2395    }
2396    // A signature may ride any kind (no matrix row, like metadata). When present
2397    // its capsule must hold its scheme's registered lengths.
2398    if let Some(signature) = &envelope.signature {
2399        signature.validate()?;
2400    }
2401    Ok(())
2402}
2403
2404/// The `status` operation value for task lifecycle updates.
2405pub const OPERATION_TASK: &str = "task";
2406/// The `status` operation value for session lifecycle updates.
2407pub const OPERATION_SESSION: &str = "session";
2408/// The `status` operation value for liveness/capability cards.
2409pub const OPERATION_CARD: &str = "card";
2410/// The `status` operation value for progress ticks.
2411pub const OPERATION_PROGRESS: &str = "progress";
2412/// The `status` operation value for a quarantine fact: an operator marks an agent
2413/// out of routing. The body is the quarantined agent id. Authorized by the
2414/// registry topic's write access control (only an operator may append it), and
2415/// optionally signed for defense in depth.
2416pub const OPERATION_QUARANTINE: &str = "quarantine";
2417/// The `status` operation value for an un-quarantine fact: an operator lifts a
2418/// prior quarantine, returning the agent to routing. The body is the agent id.
2419/// Same authorization as [`OPERATION_QUARANTINE`], so quarantine is not a
2420/// one-way door that only retention expiry can undo.
2421pub const OPERATION_UNQUARANTINE: &str = "unquarantine";
2422
2423// The chunk-stream purpose vocabulary: `operation` on the stream-opening
2424// chunk says what the channel IS, so a consumer reassembling several channels
2425// under one correlation (answer text next to reasoning next to streamed tool
2426// arguments) tells them apart without decoding bodies. Pinned here because
2427// every bridge and viewer would otherwise invent its own spelling.
2428/// The chunk-stream `operation` value for answer/content text (OTel's `chat`).
2429pub const OPERATION_CHAT: &str = "chat";
2430/// The chunk-stream `operation` value for a model's reasoning stream.
2431pub const OPERATION_REASONING: &str = "reasoning";
2432/// The chunk-stream `operation` value for streamed tool-call arguments.
2433pub const OPERATION_TOOL_ARGS: &str = "tool_args";
2434
2435// The state-sync convention: UI/shared state rides `event` envelopes
2436// discriminated by `operation`, never a new kind. Replaying snapshot + deltas
2437// reconstructs the state at any historical offset.
2438/// The `event` operation value for a full state snapshot (the body is the
2439/// state, codec per `agdx.ct`).
2440pub const OPERATION_STATE_SNAPSHOT: &str = "state_snapshot";
2441/// The `event` operation value for a state delta (the body is an RFC 6902
2442/// JSON Patch document).
2443pub const OPERATION_STATE_DELTA: &str = "state_delta";
2444/// The `event` operation value for a work record an agent held while its
2445/// session was paused. The body is a [`SessionParking`].
2446pub const OPERATION_SESSION_PARKED: &str = "session_parked";
2447/// The `event` operation value that records a held work record handled after
2448/// the resume. The body is the [`SessionParking`] of the held record.
2449pub const OPERATION_SESSION_UNPARKED: &str = "session_unparked";
2450
2451// Pinned AGDX-native metadata keys. Values stay strings or scalars per the
2452// metadata rules. The keys are pinned so transcripts, bridges, and projections
2453// agree without per-app conventions.
2454/// Metadata key: the message's chat role. Recommended values: `user`,
2455/// `assistant`, `system`, `tool`. A string because that vocabulary belongs to
2456/// the model providers and the edge protocols, not to us.
2457pub const METADATA_ROLE: &str = "role";
2458/// Metadata key: the bridge hop list, a `Value::List` of bridge id strings.
2459/// A bridge republishing a message appends its own id, and drops a message
2460/// whose hop list already contains it: the loop guard for multi-bridge
2461/// deployments (A2A in, AG-UI out, A2A out again). Bounded by the metadata
2462/// caps like every other entry.
2463pub const METADATA_BRIDGE_HOPS: &str = "bridge_hops";
2464/// Metadata key: the user an agent acts on behalf of. It rides `metadata` (not a
2465/// header) so it falls inside the signed envelope span, so the signer cannot
2466/// forge whom it claims to act for.
2467pub const METADATA_DELEGATED_BY: &str = "on_behalf_of";
2468/// Metadata key: the declared purpose of the operation, a stable input for a
2469/// policy engine at the effect boundary. Advisory unless the envelope is signed.
2470pub const METADATA_PURPOSE: &str = "purpose";
2471/// Metadata key: the declared classification of the data the operation touches.
2472/// Advisory unless the envelope is signed.
2473pub const METADATA_DATA_CLASSIFICATION: &str = "data_classification";
2474/// Metadata key: the task this operation serves. Advisory unless the envelope
2475/// is signed.
2476pub const METADATA_TASK_CONTEXT: &str = "task_context";
2477/// Metadata key: the session's declared intent. Advisory unless the envelope
2478/// is signed.
2479pub const METADATA_SESSION_INTENT: &str = "session_intent";
2480
2481// Crockford base32, the canonical display form of every u128 id (26
2482// characters, the same rendering ULIDs use). Hand-rolled so the crate stays
2483// dependency-free. Generation (entropy and clock) lives SDK-side.
2484const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2485
2486pub(crate) fn crockford_encode(value: u128) -> [u8; 26] {
2487    let mut out = [0u8; 26];
2488    let mut v = value;
2489    for slot in out.iter_mut().rev() {
2490        *slot = CROCKFORD[(v & 0x1f) as usize];
2491        v >>= 5;
2492    }
2493    out
2494}
2495
2496pub(crate) fn crockford_decode(s: &str) -> Result<u128, IdParseError> {
2497    let bytes = s.as_bytes();
2498    if bytes.len() != 26 {
2499        return Err(IdParseError::Length { got: bytes.len() });
2500    }
2501    let mut value: u128 = 0;
2502    for (i, byte) in bytes.iter().enumerate() {
2503        let digit = CROCKFORD
2504            .iter()
2505            .position(|c| *c == byte.to_ascii_uppercase())
2506            .ok_or(IdParseError::Char(*byte as char))?;
2507        // 26 chars carry 130 bits. The top character may only use 3 of its 5
2508        // (the ULID overflow rule), so a first digit past 7 cannot fit u128.
2509        if i == 0 && digit > 7 {
2510            return Err(IdParseError::Overflow);
2511        }
2512        value = (value << 5) | digit as u128;
2513    }
2514    Ok(value)
2515}
2516
2517fn cap_str(value: Option<&str>, field: &'static str) -> Result<(), ValidateError> {
2518    if let Some(value) = value
2519        && value.len() > crate::limits::MAX_AGENT_STRING_BYTES
2520    {
2521        return Err(ValidateError::TooLarge {
2522            field,
2523            size: value.len(),
2524            cap: crate::limits::MAX_AGENT_STRING_BYTES,
2525        });
2526    }
2527    Ok(())
2528}
2529
2530// Approximate scalar size in bytes for the metadata caps: text by length,
2531// scalars by their widest encoding, lists by the sum of their elements.
2532fn value_size(value: &Value) -> usize {
2533    match value {
2534        Value::Str(s) => s.len(),
2535        Value::List(items) => items.iter().map(|item| 1 + value_size(item)).sum(),
2536        _ => 9,
2537    }
2538}
2539
2540#[cfg(test)]
2541mod tests {
2542    use super::*;
2543    use crate::validate::Validate;
2544
2545    fn session_start() -> SessionStart {
2546        SessionStart {
2547            label: Some("Research".to_owned()),
2548            namespace: Some("agents".to_owned()),
2549            agent: "planner".parse().expect("valid agent id"),
2550            sdk: SdkInfo {
2551                language: "rust".to_owned(),
2552                version: "0.8.0".to_owned(),
2553            },
2554            parent: None,
2555            root: None,
2556            idle_timeout_micros: Some(300_000_000),
2557            budget: Some(Budget {
2558                tokens: Some(1000),
2559                cost_micros: None,
2560            }),
2561            tags: vec!["demo".to_owned()],
2562        }
2563    }
2564
2565    #[test]
2566    fn given_session_status_when_decoded_then_should_keep_known_and_unknown_values() {
2567        assert_eq!(
2568            serde_json::from_str::<SessionStatus>("\"paused\"").expect("paused"),
2569            SessionStatus::Paused
2570        );
2571        assert_eq!(
2572            serde_json::from_str::<SessionStatus>("\"future\"").expect("unknown"),
2573            SessionStatus::Unrecognized
2574        );
2575    }
2576
2577    #[test]
2578    fn given_session_start_when_validated_then_should_enforce_label_and_tag_caps() {
2579        let mut start = session_start();
2580        start.validate().expect("valid start");
2581        start.label = Some("bad\nlabel".to_owned());
2582        assert!(start.validate().is_err());
2583        start.label = Some("x".repeat(crate::limits::MAX_SESSION_LABEL_BYTES + 1));
2584        assert!(start.validate().is_err());
2585        start.label = None;
2586        start.tags = vec!["tag".to_owned(); crate::limits::MAX_MEMORY_TAGS + 1];
2587        assert!(start.validate().is_err());
2588    }
2589
2590    #[cfg(feature = "cbor")]
2591    #[test]
2592    fn given_session_status_bodies_when_validated_then_should_match_the_lifecycle() {
2593        let mut status = AgentEnvelope::status(
2594            RecordId::from_u128(1),
2595            ConversationId::from_u128(2),
2596            "planner".parse().expect("valid agent id"),
2597            OPERATION_SESSION,
2598        );
2599        status.task_state = Some(TaskState::Submitted);
2600        status.body = crate::framing::encode_named(&session_start()).expect("start encodes");
2601        validate(&status).expect("submitted start");
2602        status.parent = Some(ConversationId::from_u128(8));
2603        assert!(
2604            validate(&status).is_err(),
2605            "start and envelope ancestry must match"
2606        );
2607        status.parent = None;
2608
2609        status.task_state = Some(TaskState::Paused);
2610        status.body = crate::framing::encode_named(&SessionTransition::default())
2611            .expect("transition encodes");
2612        validate(&status).expect("paused transition");
2613
2614        status.task_state = Some(TaskState::Completed);
2615        status.body = crate::framing::encode_named(&SessionEnd::default()).expect("end encodes");
2616        assert!(validate(&status).is_err(), "terminal status needs last");
2617        status.last = true;
2618        validate(&status).expect("completed end");
2619    }
2620
2621    #[cfg(feature = "cbor")]
2622    #[test]
2623    fn given_a_parked_record_when_encoded_then_should_round_trip_and_require_a_generation() {
2624        use crate::validate::Validate;
2625        let source = |generation| crate::graph::SourceRef::Message {
2626            stream: 1,
2627            topic: 2,
2628            partition: 3,
2629            offset: 4,
2630            generation,
2631            conversation: Some(ConversationId::from_u128(5).to_string()),
2632        };
2633        let parking = SessionParking {
2634            source: source(Some(6)),
2635            role: "worker".parse().expect("valid agent id"),
2636            request: LogPosition::new(1, 7, 0, 8),
2637        };
2638        parking.validate().expect("a complete parking is valid");
2639        let bytes = crate::framing::encode_named(&parking).expect("parking encodes");
2640        let decoded: SessionParking = crate::framing::decode_named(&bytes).expect("decodes");
2641        assert_eq!(decoded, parking);
2642        let unproven = SessionParking {
2643            source: source(None),
2644            ..parking.clone()
2645        };
2646        assert!(unproven.validate().is_err());
2647        let not_a_record = SessionParking {
2648            source: crate::graph::SourceRef::Memory { id: "m".to_owned() },
2649            ..parking
2650        };
2651        assert!(not_a_record.validate().is_err());
2652    }
2653
2654    #[test]
2655    fn given_a_pause_request_body_when_decoded_then_should_read_an_empty_body_as_no_participants() {
2656        let empty: SessionPauseRequest = serde_json::from_slice(b"{}").expect("empty decodes");
2657        assert!(empty.participants.is_empty());
2658        let named = SessionPauseRequest {
2659            participants: vec!["worker".parse().expect("valid agent id")],
2660        };
2661        let json = serde_json::to_string(&named).expect("request encodes");
2662        assert_eq!(json, r#"{"participants":["worker"]}"#);
2663        assert_eq!(
2664            serde_json::from_str::<SessionPauseRequest>(&json).expect("decodes"),
2665            named
2666        );
2667    }
2668
2669    #[test]
2670    fn given_an_id_when_displayed_then_should_round_trip_through_crockford_base32() {
2671        let id = RecordId::from_u128(0x0123_4567_89ab_cdef_0123_4567_89ab_cdef);
2672        let text = id.to_string();
2673        assert_eq!(text.len(), 26);
2674        assert_eq!(text.parse::<RecordId>().expect("parses"), id);
2675        // Lowercase parses too (Crockford is case-insensitive).
2676        assert_eq!(text.to_lowercase().parse::<RecordId>().expect("parses"), id);
2677        assert_eq!(
2678            RecordId::from_u128(0).to_string(),
2679            "00000000000000000000000000"
2680        );
2681        assert_eq!(
2682            RecordId::from_u128(u128::MAX).to_string(),
2683            "7ZZZZZZZZZZZZZZZZZZZZZZZZZ"
2684        );
2685    }
2686
2687    #[test]
2688    fn given_an_id_in_json_when_encoded_then_should_use_readable_text() {
2689        let id = RecordId::from_u128(0x0123_4567_89ab_cdef_0123_4567_89ab_cdef);
2690        let json = serde_json::to_string(&id).expect("serializes");
2691        assert_eq!(json, format!("\"{id}\""));
2692        assert_eq!(
2693            serde_json::from_str::<RecordId>(&json).expect("deserializes"),
2694            id
2695        );
2696        let byte_array = serde_json::to_string(&[0_u8; 16]).expect("serializes byte array");
2697        assert!(serde_json::from_str::<RecordId>(&byte_array).is_err());
2698    }
2699
2700    #[cfg(feature = "cbor")]
2701    #[test]
2702    fn given_an_id_in_named_cbor_when_encoded_then_should_use_fixed_width_bytes() {
2703        let id = RecordId::from_u128(0x0123_4567_89ab_cdef_0123_4567_89ab_cdef);
2704        let encoded = crate::framing::encode_named(&id).expect("serializes");
2705        let decoded = crate::framing::decode_named::<RecordId>(&encoded).expect("deserializes");
2706        assert_eq!(decoded, id);
2707    }
2708
2709    #[test]
2710    fn given_invalid_id_strings_when_parsed_then_should_reject_with_the_right_error() {
2711        assert_eq!(
2712            "short".parse::<RecordId>(),
2713            Err(IdParseError::Length { got: 5 })
2714        );
2715        assert_eq!(
2716            "8ZZZZZZZZZZZZZZZZZZZZZZZZZ".parse::<RecordId>(),
2717            Err(IdParseError::Overflow)
2718        );
2719        assert!(matches!(
2720            "UUUUUUUUUUUUUUUUUUUUUUUUUU".parse::<RecordId>(),
2721            Err(IdParseError::Char('U'))
2722        ));
2723    }
2724
2725    #[test]
2726    fn given_agent_id_strings_when_parsed_then_should_accept_printable_and_reject_control() {
2727        for s in ["planner", "planner@acme.example", "team/planner", "a:b"] {
2728            assert_eq!(
2729                s.parse::<AgentId>()
2730                    .expect("a printable agent id is valid")
2731                    .as_str(),
2732                s
2733            );
2734        }
2735        assert!("".parse::<AgentId>().is_err());
2736        assert!("bad\nid".parse::<AgentId>().is_err());
2737    }
2738
2739    #[test]
2740    fn given_task_state_codes_when_mapped_then_should_match_the_pinned_dictionary() {
2741        let expected = [
2742            (TaskState::Submitted, 1u8),
2743            (TaskState::Working, 2),
2744            (TaskState::InputRequired, 3),
2745            (TaskState::Completed, 4),
2746            (TaskState::Canceled, 5),
2747            (TaskState::Failed, 6),
2748            (TaskState::Rejected, 7),
2749            (TaskState::AuthRequired, 8),
2750            (TaskState::Unknown, 9),
2751            (TaskState::Paused, 10),
2752        ];
2753        for (state, code) in expected {
2754            assert_eq!(state.code(), code);
2755            assert_eq!(TaskState::from_code(code), state);
2756        }
2757        // An unknown code decodes and passes through as non-terminal.
2758        let future = TaskState::from_code(42);
2759        assert_eq!(future, TaskState::Unrecognized(42));
2760        assert_eq!(future.code(), 42);
2761        assert!(!future.is_terminal());
2762        assert!(TaskState::Completed.is_terminal());
2763        assert!(!TaskState::Working.is_terminal());
2764        assert!(!TaskState::Paused.is_terminal());
2765        assert_eq!(TaskState::Paused.to_string(), "paused");
2766        assert_eq!("paused".parse::<TaskState>(), Ok(TaskState::Paused));
2767    }
2768
2769    #[test]
2770    fn given_task_state_names_when_round_tripped_then_should_match_the_a2a_vocabulary() {
2771        assert_eq!(TaskState::InputRequired.to_string(), "input-required");
2772        assert_eq!(
2773            "auth-required".parse::<TaskState>().expect("parses"),
2774            TaskState::AuthRequired
2775        );
2776        assert!("nope".parse::<TaskState>().is_err());
2777    }
2778
2779    #[test]
2780    fn given_error_and_dead_letter_codes_when_mapped_then_should_match_the_dictionaries() {
2781        assert_eq!(AgentErrorCode::InvalidRequest.code(), 1);
2782        assert_eq!(AgentErrorCode::Internal.code(), 7);
2783        assert_eq!(
2784            AgentErrorCode::from_code(99),
2785            AgentErrorCode::Unrecognized(99)
2786        );
2787        assert_eq!(DeadLetterReason::RetryExhausted.code(), 1);
2788        assert_eq!(DeadLetterReason::DeadlineExceeded.code(), 4);
2789        assert_eq!(
2790            DeadLetterReason::from_code(77),
2791            DeadLetterReason::Unrecognized(77)
2792        );
2793    }
2794
2795    #[test]
2796    fn given_every_u8_when_mapped_through_the_dictionaries_then_the_code_should_round_trip() {
2797        // Totality: from_code is defined on the whole u8 space (unknown codes
2798        // become Unrecognized), and code() is its left inverse, so no byte can
2799        // panic or be lost on decode.
2800        for code in 0u8..=u8::MAX {
2801            assert_eq!(TaskState::from_code(code).code(), code);
2802            assert_eq!(AgentErrorCode::from_code(code).code(), code);
2803            assert_eq!(DeadLetterReason::from_code(code).code(), code);
2804        }
2805    }
2806
2807    #[test]
2808    fn given_an_idempotency_key_when_validated_then_should_enforce_the_cap() {
2809        assert!("job-123-attempt-2".parse::<IdempotencyKey>().is_ok());
2810        assert!("".parse::<IdempotencyKey>().is_err());
2811        assert!("x".repeat(65).parse::<IdempotencyKey>().is_err());
2812    }
2813
2814    #[test]
2815    fn given_an_idempotency_key_with_a_control_character_when_parsed_then_should_refuse_it() {
2816        assert!("job-123\nattempt-2".parse::<IdempotencyKey>().is_err());
2817        assert!("job-123\u{7f}".parse::<IdempotencyKey>().is_err());
2818        assert!(
2819            serde_json::from_str::<IdempotencyKey>("\"job\\u0000\"").is_err(),
2820            "a decoded key is checked too"
2821        );
2822    }
2823
2824    #[test]
2825    fn given_a_command_when_validated_then_should_pass_and_enforce_the_matrix() {
2826        let (record, conversation, source, correlation) = ids();
2827        let command =
2828            AgentEnvelope::command(record, conversation, source, correlation, b"do".to_vec());
2829        validate(&command).expect("a well-formed command validates");
2830
2831        // A command without correlation is an event wearing the wrong kind.
2832        let mut missing = command.clone();
2833        missing.correlation = None;
2834        assert_eq!(
2835            validate(&missing),
2836            Err(ValidateError::Missing {
2837                kind: AgentKind::Command,
2838                field: "correlation"
2839            })
2840        );
2841
2842        // usage is X on commands (accounting rides replies and terminals).
2843        let with_usage = command.clone().with_usage(TokenUsage::default());
2844        assert!(matches!(
2845            validate(&with_usage),
2846            Err(ValidateError::Forbidden { field: "usage", .. })
2847        ));
2848
2849        // channel is chunk identity, invalid elsewhere.
2850        let mut with_channel = command;
2851        with_channel.channel = Some(ChannelId::from_u128(1));
2852        assert!(matches!(
2853            validate(&with_channel),
2854            Err(ValidateError::Forbidden {
2855                field: "channel",
2856                ..
2857            })
2858        ));
2859    }
2860
2861    #[test]
2862    fn given_chunks_when_validated_then_should_enforce_stream_semantics() {
2863        let (_, conversation, source, correlation) = ids();
2864        let channel = ChannelId::from_u128(23);
2865        let chunk = AgentEnvelope::chunk(
2866            conversation,
2867            source.clone(),
2868            correlation,
2869            channel,
2870            0,
2871            b"tok".to_vec(),
2872        )
2873        .with_operation(OPERATION_CHAT);
2874        validate(&chunk).expect("a stream chunk validates");
2875
2876        // The opening chunk REQUIRES its purpose, from the pinned vocabulary.
2877        let mut undeclared = chunk.clone();
2878        undeclared.operation = None;
2879        assert!(matches!(
2880            validate(&undeclared),
2881            Err(ValidateError::Missing {
2882                field: "operation",
2883                ..
2884            })
2885        ));
2886        let mut off_vocabulary = chunk.clone();
2887        off_vocabulary.operation = Some("telemetry".to_owned());
2888        assert!(matches!(
2889            validate(&off_vocabulary),
2890            Err(ValidateError::Invalid {
2891                field: "operation",
2892                ..
2893            })
2894        ));
2895
2896        // The purpose rides ONLY the opening chunk.
2897        let redeclared = AgentEnvelope::chunk(
2898            conversation,
2899            source.clone(),
2900            correlation,
2901            channel,
2902            3,
2903            b"tok".to_vec(),
2904        )
2905        .with_operation(OPERATION_REASONING);
2906        assert!(matches!(
2907            validate(&redeclared),
2908            Err(ValidateError::Invalid {
2909                field: "operation",
2910                ..
2911            })
2912        ));
2913
2914        // The terminal chunk may be empty and carries finish_reason + usage.
2915        let terminal = AgentEnvelope::chunk(
2916            conversation,
2917            source.clone(),
2918            correlation,
2919            channel,
2920            41,
2921            Vec::new(),
2922        )
2923        .terminal("stop")
2924        .with_usage(TokenUsage {
2925            input_tokens: 100,
2926            output_tokens: 42,
2927            ..Default::default()
2928        });
2929        validate(&terminal).expect("a terminal chunk validates");
2930
2931        // A non-terminal chunk cannot carry finish_reason or usage.
2932        let mut early_finish = chunk.clone();
2933        early_finish.finish_reason = Some("stop".to_owned());
2934        assert!(matches!(
2935            validate(&early_finish),
2936            Err(ValidateError::Invalid {
2937                field: "finish_reason",
2938                ..
2939            })
2940        ));
2941
2942        // An empty non-terminal chunk carries nothing.
2943        let empty = AgentEnvelope::chunk(
2944            conversation,
2945            source.clone(),
2946            correlation,
2947            channel,
2948            1,
2949            Vec::new(),
2950        );
2951        assert!(matches!(
2952            validate(&empty),
2953            Err(ValidateError::Missing { field: "body", .. })
2954        ));
2955
2956        // Chunks carry no dedup semantics.
2957        let mut keyed = chunk.clone();
2958        keyed.idempotency_key = Some("k".parse().expect("valid key"));
2959        assert!(matches!(
2960            validate(&keyed),
2961            Err(ValidateError::Forbidden {
2962                field: "idempotency_key",
2963                ..
2964            })
2965        ));
2966
2967        // The abandonment bound rides only the opening chunk (sequence 0).
2968        let opening = chunk.with_deadline_micros(1);
2969        validate(&opening).expect("an opening chunk may declare the bound");
2970        let late = AgentEnvelope::chunk(
2971            conversation,
2972            source.clone(),
2973            correlation,
2974            channel,
2975            5,
2976            b"tok".to_vec(),
2977        )
2978        .with_deadline_micros(1);
2979        assert!(matches!(
2980            validate(&late),
2981            Err(ValidateError::Invalid {
2982                field: "deadline_micros",
2983                ..
2984            })
2985        ));
2986    }
2987
2988    #[test]
2989    fn given_status_signals_when_validated_then_task_updates_should_require_state() {
2990        let (record, conversation, source, correlation) = ids();
2991        // A liveness card: no correlation, no task_state.
2992        let card = AgentEnvelope::status(record, conversation, source.clone(), OPERATION_CARD);
2993        validate(&card).expect("a card validates");
2994
2995        // A task update requires correlation + task_state.
2996        let bare_task = AgentEnvelope::status(record, conversation, source.clone(), OPERATION_TASK);
2997        assert!(matches!(
2998            validate(&bare_task),
2999            Err(ValidateError::Missing {
3000                field: "correlation",
3001                ..
3002            })
3003        ));
3004        let task = AgentEnvelope::status(record, conversation, source.clone(), OPERATION_TASK)
3005            .with_correlation(correlation)
3006            .with_task_state(TaskState::Working);
3007        validate(&task).expect("a task update validates");
3008
3009        // The discriminator is a CLOSED vocabulary: task | card | progress.
3010        let off_vocabulary =
3011            AgentEnvelope::status(record, conversation, source.clone(), "telemetry");
3012        assert!(matches!(
3013            validate(&off_vocabulary),
3014            Err(ValidateError::Invalid {
3015                field: "operation",
3016                ..
3017            })
3018        ));
3019    }
3020
3021    #[test]
3022    fn given_registry_facts_when_validated_then_should_require_the_signed_deadline() {
3023        let (record, conversation, source, _) = ids();
3024        for operation in [OPERATION_QUARANTINE, OPERATION_UNQUARANTINE] {
3025            let mut fact = AgentEnvelope::status(record, conversation, source.clone(), operation);
3026            fact.body = b"worker".to_vec();
3027            assert!(matches!(
3028                validate(&fact),
3029                Err(ValidateError::Missing {
3030                    field: "deadline_micros",
3031                    ..
3032                })
3033            ));
3034            validate(&fact.with_deadline_micros(1)).expect("a fact with its deadline validates");
3035        }
3036        let card = AgentEnvelope::status(record, conversation, source, OPERATION_CARD)
3037            .with_deadline_micros(1);
3038        assert!(matches!(
3039            validate(&card),
3040            Err(ValidateError::Forbidden {
3041                field: "deadline_micros",
3042                ..
3043            })
3044        ));
3045    }
3046
3047    #[test]
3048    fn given_an_error_when_validated_then_last_should_be_forbidden() {
3049        let (record, conversation, source, correlation) = ids();
3050        let error =
3051            AgentEnvelope::error(record, conversation, source, correlation, b"boom".to_vec());
3052        validate(&error).expect("an error validates");
3053
3054        // error is ALWAYS terminal, so the flag would be redundant.
3055        let mut flagged = error.clone();
3056        flagged.last = true;
3057        assert!(matches!(
3058            validate(&flagged),
3059            Err(ValidateError::Forbidden { field: "last", .. })
3060        ));
3061
3062        // sequence without channel is incoherent.
3063        let mut dangling = error;
3064        dangling.sequence = Some(3);
3065        assert!(matches!(
3066            validate(&dangling),
3067            Err(ValidateError::Invalid {
3068                field: "sequence",
3069                ..
3070            })
3071        ));
3072    }
3073
3074    fn descriptor(skill_id: &str) -> CapabilityDescriptor {
3075        CapabilityDescriptor {
3076            skill_id: skill_id.to_owned(),
3077            input: None,
3078            output: None,
3079            cost_class: None,
3080            latency_class: None,
3081            max_concurrency: None,
3082            health: None,
3083            load: None,
3084        }
3085    }
3086
3087    #[test]
3088    fn given_an_agent_card_when_validated_then_should_enforce_the_caps() {
3089        let card = AgentCard {
3090            name: Some("rollout-planner".to_owned()),
3091            version: Some("1.4.2".to_owned()),
3092            capabilities: vec![
3093                CapabilityDescriptor {
3094                    skill_id: "chat".to_owned(),
3095                    input: Some(ContentRef::ContentType(crate::content::ContentType::Json)),
3096                    output: Some(ContentRef::ContentType(crate::content::ContentType::Json)),
3097                    cost_class: Some(2),
3098                    latency_class: Some(1),
3099                    max_concurrency: Some(8),
3100                    health: Some(Health::Healthy),
3101                    load: Some(250),
3102                },
3103                descriptor("plan_rollout"),
3104            ],
3105            ttl_micros: Some(30_000_000),
3106            inbox: Some("rollout-planner.work".to_owned()),
3107        };
3108        card.validate().expect("a well-formed card validates");
3109
3110        let mut crowded = card.clone();
3111        crowded.capabilities = vec![descriptor("x"); crate::limits::MAX_CARD_CAPABILITIES + 1];
3112        assert!(matches!(
3113            crowded.validate(),
3114            Err(ValidateError::TooLarge {
3115                field: "capabilities",
3116                ..
3117            })
3118        ));
3119
3120        let mut oversized = card.clone();
3121        oversized.name = Some("n".repeat(crate::limits::MAX_AGENT_STRING_BYTES + 1));
3122        assert!(matches!(
3123            oversized.validate(),
3124            Err(ValidateError::TooLarge { field: "name", .. })
3125        ));
3126
3127        let mut long_inbox = card;
3128        long_inbox.inbox = Some("i".repeat(crate::limits::MAX_AGENT_STRING_BYTES + 1));
3129        assert!(matches!(
3130            long_inbox.validate(),
3131            Err(ValidateError::TooLarge { field: "inbox", .. })
3132        ));
3133    }
3134
3135    #[cfg(feature = "cbor")]
3136    #[test]
3137    fn given_a_schema_id_named_like_a_content_type_when_round_tripped_then_should_stay_a_schema_id()
3138    {
3139        use crate::framing::{decode_named, encode_named};
3140        // The tag disambiguates a schema id that happens to be a content-type
3141        // name: an untagged encoding would decode this as ContentType::Json.
3142        let reference = ContentRef::SchemaId("json".to_owned());
3143        let bytes = encode_named(&reference).expect("encodes");
3144        let back: ContentRef = decode_named(&bytes).expect("decodes");
3145        assert_eq!(back, ContentRef::SchemaId("json".to_owned()));
3146        // A genuine content-type still round-trips as one.
3147        let ct = ContentRef::ContentType(crate::content::ContentType::Json);
3148        let back: ContentRef = decode_named(&encode_named(&ct).expect("encodes")).expect("decodes");
3149        assert_eq!(back, ct);
3150    }
3151
3152    #[test]
3153    fn given_a_signature_when_validated_then_should_enforce_per_scheme_lengths() {
3154        let valid = Signature {
3155            scheme: SIGNATURE_SCHEME_ED25519,
3156            key_id: vec![1u8; 8],
3157            bytes: vec![2u8; 64],
3158            context: None,
3159        };
3160        valid
3161            .validate()
3162            .expect("a well-formed Ed25519 signature validates");
3163
3164        let mut short_key = valid.clone();
3165        short_key.key_id = vec![1u8; 4];
3166        assert!(matches!(
3167            short_key.validate(),
3168            Err(ValidateError::Invalid {
3169                field: "key_id",
3170                ..
3171            })
3172        ));
3173
3174        let mut short_signature = valid.clone();
3175        short_signature.bytes = vec![2u8; 32];
3176        assert!(matches!(
3177            short_signature.validate(),
3178            Err(ValidateError::Invalid { field: "bytes", .. })
3179        ));
3180
3181        // Unknown scheme codes pass through (the open-dictionary rule).
3182        // Verification is SDK-side and scheme-aware.
3183        let future = Signature {
3184            scheme: 42,
3185            key_id: vec![1u8; 3],
3186            bytes: vec![2u8; 99],
3187            context: None,
3188        };
3189        future.validate().expect("an unknown scheme flows through");
3190    }
3191
3192    #[test]
3193    fn given_a_body_ref_when_validated_then_should_enforce_reference_and_digest() {
3194        let valid = BodyRef::new("s3://transcripts/conv-1/msg-9", 4_194_304, [7u8; 32]);
3195        valid.validate().expect("a well-formed reference validates");
3196
3197        let mut empty = valid.clone();
3198        empty.reference = String::new();
3199        assert!(matches!(
3200            empty.validate(),
3201            Err(ValidateError::Invalid {
3202                field: "reference",
3203                ..
3204            })
3205        ));
3206
3207        let mut oversized = valid.clone();
3208        oversized.reference = "x".repeat(crate::limits::MAX_BODY_REFERENCE_BYTES + 1);
3209        assert!(matches!(
3210            oversized.validate(),
3211            Err(ValidateError::TooLarge {
3212                field: "reference",
3213                ..
3214            })
3215        ));
3216
3217        let mut truncated = valid;
3218        truncated.sha256 = vec![7u8; 16];
3219        assert!(matches!(
3220            truncated.validate(),
3221            Err(ValidateError::Invalid {
3222                field: "sha256",
3223                ..
3224            })
3225        ));
3226    }
3227
3228    #[test]
3229    fn given_oversized_metadata_when_validated_then_should_reject() {
3230        let (record, conversation, source, correlation) = ids();
3231        let mut command =
3232            AgentEnvelope::command(record, conversation, source, correlation, b"x".to_vec());
3233        for i in 0..crate::limits::MAX_METADATA_ENTRIES + 1 {
3234            command = command.with_metadata(format!("k{i}"), i as i64);
3235        }
3236        assert!(matches!(
3237            validate(&command),
3238            Err(ValidateError::TooLarge {
3239                field: "metadata",
3240                ..
3241            })
3242        ));
3243    }
3244
3245    fn ids() -> (RecordId, ConversationId, AgentId, CorrelationId) {
3246        (
3247            RecordId::from_u128(7),
3248            ConversationId::from_u128(11),
3249            "test-agent".parse().expect("valid agent id"),
3250            CorrelationId::from_u128(17),
3251        )
3252    }
3253}
3254
3255#[cfg(all(test, feature = "cbor"))]
3256mod wire_tests {
3257    use super::*;
3258    use crate::framing::{decode_named, encode_named};
3259
3260    #[test]
3261    fn given_a_wrong_length_locator_when_decoded_then_should_error_not_panic() {
3262        // CBOR byte string: 0x40 | len for lengths below 24. Exactly 20 bytes
3263        // is the only valid locator. Anything else is a clean decode error.
3264        let mut valid = vec![0x40 | 20];
3265        valid.extend_from_slice(&[0u8; 20]);
3266        decode_named::<LogPosition>(&valid).expect("20 packed bytes decode");
3267
3268        for bad_len in [0u8, 19, 21, 23] {
3269            let mut bytes = vec![0x40 | bad_len];
3270            bytes.extend_from_slice(&vec![0u8; bad_len as usize]);
3271            assert!(
3272                decode_named::<LogPosition>(&bytes).is_err(),
3273                "a {bad_len}-byte locator must error, not panic"
3274            );
3275        }
3276    }
3277
3278    #[test]
3279    fn given_a_locator_when_round_tripped_then_should_preserve_every_field() {
3280        let pos = LogPosition::new(0x0102_0304, 0x0506_0708, 0x090A_0B0C, 0x0D0E_0F10_1112_1314);
3281        let bytes = encode_named(&pos).expect("encodes");
3282        let back: LogPosition = decode_named(&bytes).expect("decodes");
3283        assert_eq!(back, pos);
3284    }
3285
3286    #[test]
3287    fn given_an_envelope_when_round_tripped_then_should_preserve_every_field() {
3288        let envelope = AgentEnvelope::command(
3289            RecordId::from_u128(1),
3290            ConversationId::from_u128(2),
3291            "source-agent".parse().expect("valid agent id"),
3292            CorrelationId::from_u128(4),
3293            b"payload".to_vec(),
3294        )
3295        .with_target("target-agent".parse().expect("valid agent id"))
3296        .with_cause(RecordId::from_u128(6), Some(LogPosition::new(1, 2, 3, 44)))
3297        .with_idempotency_key("job-1".parse().expect("valid key"))
3298        .with_deadline_micros(1_700_000_000_000_000)
3299        .with_operation("chat")
3300        .with_tool("search")
3301        .with_metadata("pool", "eu-west");
3302        let bytes = encode_named(&envelope).expect("encodes");
3303        let back: AgentEnvelope = decode_named(&bytes).expect("decodes");
3304        assert_eq!(back, envelope);
3305    }
3306
3307    #[test]
3308    fn given_a_must_understand_marker_when_round_tripped_then_should_preserve_bits_and_skip_zero() {
3309        // A receiver lacking a required bit must see it as unmet, and the
3310        // default-zero marker is omitted on the wire so pre-marker records stay
3311        // byte-identical.
3312        let envelope = AgentEnvelope::event(
3313            RecordId::from_u128(1),
3314            ConversationId::from_u128(2),
3315            "source-agent".parse().expect("valid agent id"),
3316            b"e".to_vec(),
3317        )
3318        .requiring(0b101);
3319        let bytes = encode_named(&envelope).expect("encodes");
3320        let back: AgentEnvelope = decode_named(&bytes).expect("decodes");
3321        assert_eq!(back.must_understand, 0b101);
3322        // A receiver that understands bit 0 but not bit 2 has bit 2 unmet.
3323        assert_eq!(back.unmet_requirements(0b001), 0b100);
3324        // A receiver that understands both has nothing unmet.
3325        assert_eq!(back.unmet_requirements(0b111), 0);
3326        // The zero marker (open-world default) is unmet by nobody and omitted.
3327        let plain = AgentEnvelope::event(
3328            RecordId::from_u128(1),
3329            ConversationId::from_u128(2),
3330            "source-agent".parse().expect("valid agent id"),
3331            b"e".to_vec(),
3332        );
3333        assert_eq!(plain.unmet_requirements(features::NONE), 0);
3334        let json = serde_json::to_string(&plain).expect("json");
3335        assert!(
3336            !json.contains("must_understand"),
3337            "zero marker must be omitted: {json}"
3338        );
3339    }
3340
3341    #[test]
3342    fn given_absent_options_when_encoded_then_should_cost_zero_bytes() {
3343        // The skip-serializing discipline: a minimal event encodes only its
3344        // five present fields (kind, record, conversation, source, body).
3345        let envelope = AgentEnvelope::event(
3346            RecordId::from_u128(1),
3347            ConversationId::from_u128(2),
3348            "source-agent".parse().expect("valid agent id"),
3349            b"e".to_vec(),
3350        );
3351        let bytes = encode_named(&envelope).expect("encodes");
3352        // A CBOR map with at most 15 fields encodes its count in the head byte's
3353        // low nibble (major type 5, `0xa0 | count`).
3354        assert_eq!(bytes[0] & 0x0f, 5, "absent optionals must not be encoded");
3355        let back: AgentEnvelope = decode_named(&bytes).expect("decodes");
3356        assert!(!back.last);
3357        assert!(back.metadata.is_none());
3358    }
3359
3360    #[test]
3361    fn given_an_id_when_encoded_then_should_ride_as_one_fixed_width_byte_string() {
3362        let bytes = encode_named(&RecordId::from_u128(0x0102)).expect("encodes");
3363        // CBOR byte-string head `0x50` (major type 2, length 16), then the 16
3364        // big-endian bytes, fixed width, no bignum tag. 17 bytes total.
3365        assert_eq!(bytes.len(), 17);
3366        assert_eq!(bytes[0], 0x50);
3367        assert_eq!(bytes[16], 0x02);
3368        assert_eq!(bytes[15], 0x01);
3369    }
3370
3371    #[test]
3372    fn given_a_task_state_when_encoded_then_should_ride_as_a_bare_u8() {
3373        let bytes = encode_named(&TaskState::Completed).expect("encodes");
3374        assert_eq!(bytes, vec![4]);
3375        let unknown = encode_named(&42u8).expect("encodes a raw code");
3376        let back: TaskState = decode_named(&unknown).expect("unknown code decodes");
3377        assert_eq!(back, TaskState::Unrecognized(42));
3378    }
3379
3380    #[test]
3381    fn given_an_error_body_when_round_tripped_then_should_preserve_the_dictionary_code() {
3382        let body = AgentErrorBody {
3383            code: AgentErrorCode::ToolFailure,
3384            message: Some("search timed out".to_owned()),
3385            retryable: true,
3386            detail: Some(BTreeMap::from([("attempt".to_owned(), Value::Int(3))])),
3387        };
3388        let bytes = encode_named(&body).expect("encodes");
3389        let back: AgentErrorBody = decode_named(&bytes).expect("decodes");
3390        assert_eq!(back, body);
3391    }
3392
3393    #[test]
3394    fn given_a_body_ref_when_round_tripped_then_should_preserve_the_digest_as_a_byte_string() {
3395        let capsule = BodyRef::new("kv://bodies/abc", 1024, [9u8; 32]);
3396        let bytes = encode_named(&capsule).expect("encodes");
3397        let back: BodyRef = decode_named(&bytes).expect("decodes");
3398        assert_eq!(back, capsule);
3399        assert!(back.encryption.is_none(), "absent encryption costs nothing");
3400        back.validate().expect("decoded capsule validates");
3401    }
3402
3403    #[test]
3404    fn given_a_dead_letter_when_round_tripped_then_payload_should_stay_byte_identical() {
3405        let inner = AgentEnvelope::command(
3406            RecordId::from_u128(9),
3407            ConversationId::from_u128(8),
3408            "source-agent".parse().expect("valid agent id"),
3409            CorrelationId::from_u128(6),
3410            b"poison".to_vec(),
3411        );
3412        let payload = encode_named(&inner).expect("inner encodes");
3413        let capsule = AgentDeadLetter {
3414            source: LogPosition::new(1, 2, 3, 99),
3415            reason: DeadLetterReason::RetryExhausted,
3416            attempts: 5,
3417            detail: Some("handler kept failing".to_owned()),
3418            payload: payload.clone(),
3419        };
3420        let bytes = encode_named(&capsule).expect("encodes");
3421        let back: AgentDeadLetter = decode_named(&bytes).expect("decodes");
3422        assert_eq!(back.payload, payload, "redrive needs the original bytes");
3423        let redrive: AgentEnvelope = decode_named(&back.payload).expect("inner decodes");
3424        assert_eq!(redrive, inner);
3425    }
3426    #[test]
3427    fn given_a_task_status_when_validated_then_should_require_the_correlation() {
3428        // A task status must carry a correlation.
3429        let base = AgentEnvelope::status(
3430            RecordId::from_u128(1),
3431            ConversationId::from_u128(2),
3432            "runner".parse().expect("valid agent id"),
3433            OPERATION_TASK,
3434        )
3435        .with_task_state(TaskState::Working);
3436        assert!(
3437            matches!(
3438                validate(&base),
3439                Err(ValidateError::Missing {
3440                    kind: AgentKind::Status,
3441                    field: "correlation"
3442                })
3443            ),
3444            "a task status without a correlation is rejected"
3445        );
3446        let correlated = base.with_correlation(CorrelationId::from_u128(2));
3447        validate(&correlated)
3448            .expect("the run-lifecycle status validates once it correlates on the run");
3449    }
3450
3451    #[test]
3452    fn given_task_states_when_displayed_and_parsed_then_should_use_the_pinned_kebab_words() {
3453        assert_eq!(TaskState::InputRequired.to_string(), "input-required");
3454        assert_eq!(TaskState::AuthRequired.to_string(), "auth-required");
3455        assert_eq!(TaskState::Unrecognized(42).to_string(), "unrecognized-42");
3456        assert_eq!(
3457            "input-required".parse::<TaskState>().expect("parses"),
3458            TaskState::InputRequired
3459        );
3460        assert!("bogus".parse::<TaskState>().is_err());
3461    }
3462}