1use 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#[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
38macro_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 pub const fn from_u128(value: u128) -> Self {
51 Self(value)
52 }
53
54 pub const fn as_u128(self) -> u128 {
56 self.0
57 }
58
59 pub const fn to_bytes(self) -> [u8; 16] {
61 self.0.to_be_bytes()
62 }
63
64 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 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 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
207pub(crate) use wire_id;
210
211wire_id!(
212 RecordId
219);
220wire_id!(
221 ConversationId
224);
225wire_id!(
226 CorrelationId
229);
230wire_id!(
231 ChannelId
234);
235
236#[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 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 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 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#[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#[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 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#[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 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#[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 Command,
509 Response,
511 Event,
513 Chunk,
515 Status,
518 Error,
520}
521
522#[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 Paused,
548 Unrecognized(u8),
550}
551
552impl TaskState {
553 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 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 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 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#[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#[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#[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#[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#[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#[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#[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#[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#[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
773pub const fn estimate_tokens(bytes: usize) -> u64 {
776 bytes.div_ceil(4) as u64
777}
778
779pub const METADATA_REQUEST_MODEL: &str = "gen_ai.request.model";
781pub const METADATA_RESPONSE_MODEL: &str = "gen_ai.response.model";
783pub const METADATA_PROVIDER_NAME: &str = "gen_ai.provider.name";
785pub const METADATA_SUBMITTED: &str = "submitted";
789pub const METADATA_RECORDED: &str = "recorded";
793pub const METADATA_DURATION_MICROS: &str = "duration_micros";
796
797#[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#[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#[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#[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
870pub use json_patch::PatchOperation;
872
873#[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#[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
984pub 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 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
1029pub 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
1052fn 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1123 pub cost_micros: Option<u64>,
1124}
1125
1126#[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 Unrecognized(u8),
1141}
1142
1143impl AgentErrorCode {
1144 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 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#[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#[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 Unrecognized(u8),
1211}
1212
1213impl DeadLetterReason {
1214 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 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#[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#[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 Unrecognized(u8),
1285}
1286
1287impl Health {
1288 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 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#[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1342pub struct CapabilityDescriptor {
1343 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 #[serde(default, skip_serializing_if = "Option::is_none")]
1351 pub cost_class: Option<u8>,
1352 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1361 pub load: Option<u16>,
1362}
1363
1364#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1372#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1373pub struct AgentCard {
1374 #[serde(default, skip_serializing_if = "Option::is_none")]
1377 pub name: Option<String>,
1378 #[serde(default, skip_serializing_if = "Option::is_none")]
1380 pub version: Option<String>,
1381 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1384 pub capabilities: Vec<CapabilityDescriptor>,
1385 #[serde(default, skip_serializing_if = "Option::is_none")]
1388 pub ttl_micros: Option<u64>,
1389 #[serde(default, skip_serializing_if = "Option::is_none")]
1392 pub inbox: Option<String>,
1393}
1394
1395impl AgentCard {
1396 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1433#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1434pub struct AgentPresence {
1435 pub v: u32,
1438 pub agent: AgentId,
1443 #[serde(default, skip_serializing_if = "Option::is_none")]
1447 pub inbox: Option<String>,
1448}
1449
1450impl AgentPresence {
1451 pub fn new(agent: AgentId) -> Self {
1454 Self {
1455 v: crate::codes::PRESENCE_OP_VERSION,
1456 agent,
1457 inbox: None,
1458 }
1459 }
1460
1461 pub fn with_inbox(mut self, inbox: impl Into<String>) -> Self {
1463 self.inbox = Some(inbox.into());
1464 self
1465 }
1466
1467 pub fn validate(&self) -> Result<(), ValidateError> {
1470 cap_str(self.inbox.as_deref(), "inbox")?;
1471 Ok(())
1472 }
1473}
1474
1475#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1485pub struct BodyRef {
1486 pub reference: String,
1489 pub size_bytes: u64,
1491 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1502 pub encryption: Option<u8>,
1503}
1504
1505const SHA256_BYTES: usize = 32;
1506
1507impl BodyRef {
1508 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1560#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1561pub struct Signature {
1562 pub scheme: u8,
1565 #[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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1586 pub context: Option<SignatureContext>,
1587}
1588
1589#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1595#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1596pub struct SignatureContext {
1597 #[serde(default, skip_serializing_if = "Option::is_none")]
1599 pub content_type: Option<u8>,
1600 #[serde(default, skip_serializing_if = "Option::is_none")]
1602 pub agent_version: Option<u32>,
1603}
1604
1605pub const SIGNATURE_SCHEME_ED25519: u8 = 1;
1607
1608pub 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 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1662pub struct AgentEnvelope {
1663 pub kind: AgentKind,
1664 #[serde(default, skip_serializing_if = "Option::is_none")]
1668 pub record: Option<RecordId>,
1669 pub conversation: ConversationId,
1671 #[serde(default, skip_serializing_if = "Option::is_none")]
1673 pub parent: Option<ConversationId>,
1674 #[serde(default, skip_serializing_if = "Option::is_none")]
1676 pub root: Option<ConversationId>,
1677 pub source: AgentId,
1679 #[serde(default, skip_serializing_if = "Option::is_none")]
1683 pub target: Option<AgentId>,
1684 #[serde(default, skip_serializing_if = "Option::is_none")]
1687 pub cause: Option<RecordId>,
1688 #[serde(default, skip_serializing_if = "Option::is_none")]
1691 pub cause_at: Option<LogPosition>,
1692 #[serde(default, skip_serializing_if = "Option::is_none")]
1694 pub correlation: Option<CorrelationId>,
1695 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1704 pub deadline_micros: Option<u64>,
1705 #[serde(default, skip_serializing_if = "Option::is_none")]
1707 pub sequence: Option<u64>,
1708 #[serde(default, skip_serializing_if = "is_false")]
1712 pub last: bool,
1713 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1723 pub operation: Option<String>,
1724 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1731 pub metadata: Option<BTreeMap<String, Value>>,
1732 #[serde(default, skip_serializing_if = "is_zero_u64")]
1744 pub must_understand: u64,
1745 #[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 #[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
1775pub mod features {
1782 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 #[must_use]
1823 pub fn requiring(mut self, bits: u64) -> Self {
1824 self.must_understand = bits;
1825 self
1826 }
1827
1828 pub fn unmet_requirements(&self, understood: u64) -> u64 {
1833 self.must_understand & !understood
1834 }
1835
1836 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 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 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 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 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 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 pub fn with_target(mut self, target: AgentId) -> Self {
1930 self.target = Some(target);
1931 self
1932 }
1933
1934 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 pub fn with_correlation(mut self, correlation: CorrelationId) -> Self {
1947 self.correlation = Some(correlation);
1948 self
1949 }
1950
1951 pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
1953 self.idempotency_key = Some(key);
1954 self
1955 }
1956
1957 pub fn with_deadline_micros(mut self, deadline_micros: u64) -> Self {
1960 self.deadline_micros = Some(deadline_micros);
1961 self
1962 }
1963
1964 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 pub fn with_task_state(mut self, state: TaskState) -> Self {
1975 self.task_state = Some(state);
1976 self
1977 }
1978
1979 pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
1981 self.operation = Some(operation.into());
1982 self
1983 }
1984
1985 pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
1987 self.tool = Some(tool.into());
1988 self
1989 }
1990
1991 pub fn with_usage(mut self, usage: TokenUsage) -> Self {
1993 self.usage = Some(usage);
1994 self
1995 }
1996
1997 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 pub fn with_signature(mut self, signature: Signature) -> Self {
2010 self.signature = Some(signature);
2011 self
2012 }
2013}
2014
2015#[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
2040pub 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 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 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 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 if envelope.last && !matches!(kind, Chunk | Status) {
2140 return Err(ValidateError::Forbidden {
2141 kind,
2142 field: "last",
2143 });
2144 }
2145
2146 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 if matches!(kind, Chunk | Status | Error) {
2163 forbid(envelope.idempotency_key.is_none(), "idempotency_key")?;
2164 }
2165
2166 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 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 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 if kind == Status {
2261 forbid(envelope.tool.is_none(), "tool")?;
2262 }
2263
2264 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 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 #[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 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 if let Some(signature) = &envelope.signature {
2399 signature.validate()?;
2400 }
2401 Ok(())
2402}
2403
2404pub const OPERATION_TASK: &str = "task";
2406pub const OPERATION_SESSION: &str = "session";
2408pub const OPERATION_CARD: &str = "card";
2410pub const OPERATION_PROGRESS: &str = "progress";
2412pub const OPERATION_QUARANTINE: &str = "quarantine";
2417pub const OPERATION_UNQUARANTINE: &str = "unquarantine";
2422
2423pub const OPERATION_CHAT: &str = "chat";
2430pub const OPERATION_REASONING: &str = "reasoning";
2432pub const OPERATION_TOOL_ARGS: &str = "tool_args";
2434
2435pub const OPERATION_STATE_SNAPSHOT: &str = "state_snapshot";
2441pub const OPERATION_STATE_DELTA: &str = "state_delta";
2444pub const OPERATION_SESSION_PARKED: &str = "session_parked";
2447pub const OPERATION_SESSION_UNPARKED: &str = "session_unparked";
2450
2451pub const METADATA_ROLE: &str = "role";
2458pub const METADATA_BRIDGE_HOPS: &str = "bridge_hops";
2464pub const METADATA_DELEGATED_BY: &str = "on_behalf_of";
2468pub const METADATA_PURPOSE: &str = "purpose";
2471pub const METADATA_DATA_CLASSIFICATION: &str = "data_classification";
2474pub const METADATA_TASK_CONTEXT: &str = "task_context";
2477pub const METADATA_SESSION_INTENT: &str = "session_intent";
2480
2481const 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 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
2530fn 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let card = AgentEnvelope::status(record, conversation, source.clone(), OPERATION_CARD);
2993 validate(&card).expect("a card validates");
2994
2995 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 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 let mut flagged = error.clone();
3056 flagged.last = true;
3057 assert!(matches!(
3058 validate(&flagged),
3059 Err(ValidateError::Forbidden { field: "last", .. })
3060 ));
3061
3062 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 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 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 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 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 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 assert_eq!(back.unmet_requirements(0b001), 0b100);
3324 assert_eq!(back.unmet_requirements(0b111), 0);
3326 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 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 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 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 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}