返回 CodeWhale
agent_mail.rs
根目录 / crates / protocol / src / agent_mail.rs
1 //! Canonical protocol contract for durable communication between Codewhale tasks.
2 //!
3 //! Agent Mail is distinct from same-session subagent control messages. An envelope
4 //! is persisted by the runtime, scoped to an owner and workspace, and projected
5 //! into a destination turn only at an explicit safe boundary. The summary is the
6 //! complete model-visible payload: runtimes must sanitize it before constructing
7 //! an envelope, and this module enforces the wire-size and control-character
8 //! boundary.
9
10 use std::error::Error;
11 use std::fmt;
12
13 use chrono::{DateTime, Utc};
14 use serde::{Deserialize, Deserializer, Serialize};
15 use uuid::Uuid;
16
17 pub const AGENT_MAIL_SCHEMA_VERSION: u32 = 1;
18
19 pub const AGENT_MAIL_EVENT_QUEUED: &str = "agent_mail.queued";
20 pub const AGENT_MAIL_EVENT_DELIVERING: &str = "agent_mail.delivering";
21 pub const AGENT_MAIL_EVENT_DELIVERED: &str = "agent_mail.delivered";
22 pub const AGENT_MAIL_EVENT_READ: &str = "agent_mail.read";
23 pub const AGENT_MAIL_EVENT_DELIVERY_FAILED: &str = "agent_mail.delivery_failed";
24 pub const AGENT_MAIL_EVENT_CANCELED: &str = "agent_mail.canceled";
25
26 pub const MAX_AGENT_MAIL_MESSAGE_ID_BYTES: usize = 80;
27 pub const MAX_AGENT_MAIL_OPAQUE_ID_BYTES: usize = 128;
28 pub const MAX_AGENT_MAIL_DISPLAY_LABEL_BYTES: usize = 64;
29 pub const MAX_AGENT_MAIL_SUMMARY_BYTES: usize = 2_048;
30 pub const MAX_AGENT_MAIL_EVIDENCE_REFS: usize = 8;
31 pub const MAX_AGENT_MAIL_EVIDENCE_LABEL_BYTES: usize = 96;
32 pub const MAX_AGENT_MAIL_HOPS: u8 = 4;
33 pub const MAX_AGENT_MAIL_DELIVERY_ATTEMPTS: u8 = 8;
34 pub const MAX_AGENT_MAIL_FAILURE_MESSAGE_BYTES: usize = 256;
35
36 #[derive(Debug, Clone, PartialEq, Eq)]
37 pub struct AgentMailValidationError {
38 pub field: &'static str,
39 pub message: String,
40 }
41
42 impl AgentMailValidationError {
43 fn new(field: &'static str, message: impl Into<String>) -> Self {
44 Self {
45 field,
46 message: message.into(),
47 }
48 }
49 }
50
51 impl fmt::Display for AgentMailValidationError {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 write!(f, "invalid Agent Mail {}: {}", self.field, self.message)
54 }
55 }
56
57 impl Error for AgentMailValidationError {}
58
59 /// Stable, caller-supplied idempotency key for an Agent Mail envelope.
60 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
61 #[serde(transparent)]
62 pub struct AgentMailMessageId(String);
63
64 impl AgentMailMessageId {
65 #[must_use]
66 pub fn new() -> Self {
67 Self(format!("mail_{}", Uuid::new_v4().simple()))
68 }
69
70 pub fn parse(value: impl Into<String>) -> Result<Self, AgentMailValidationError> {
71 let value = value.into();
72 validate_message_id(&value)?;
73 Ok(Self(value))
74 }
75
76 #[must_use]
77 pub fn as_str(&self) -> &str {
78 &self.0
79 }
80
81 #[must_use]
82 pub fn into_string(self) -> String {
83 self.0
84 }
85 }
86
87 impl Default for AgentMailMessageId {
88 fn default() -> Self {
89 Self::new()
90 }
91 }
92
93 impl fmt::Display for AgentMailMessageId {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str(&self.0)
96 }
97 }
98
99 impl TryFrom<String> for AgentMailMessageId {
100 type Error = AgentMailValidationError;
101
102 fn try_from(value: String) -> Result<Self, Self::Error> {
103 Self::parse(value)
104 }
105 }
106
107 impl TryFrom<&str> for AgentMailMessageId {
108 type Error = AgentMailValidationError;
109
110 fn try_from(value: &str) -> Result<Self, Self::Error> {
111 Self::parse(value)
112 }
113 }
114
115 impl<'de> Deserialize<'de> for AgentMailMessageId {
116 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117 where
118 D: Deserializer<'de>,
119 {
120 let value = String::deserialize(deserializer)?;
121 Self::parse(value).map_err(serde::de::Error::custom)
122 }
123 }
124
125 /// Durable ownership and routing scope resolved by the receiving runtime.
126 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
127 pub struct AgentMailAddress {
128 pub owner_id: String,
129 pub workspace_id: String,
130 pub thread_id: String,
131 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
132 pub thread_only: bool,
133 #[serde(skip_serializing_if = "Option::is_none")]
134 pub task_id: Option<String>,
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub session_id: Option<String>,
137 }
138
139 impl AgentMailAddress {
140 pub fn matches_current_thread(&self, current: &Self) -> bool {
141 self == current
142 || (self.thread_only
143 && self.owner_id == current.owner_id
144 && self.workspace_id == current.workspace_id
145 && self.thread_id == current.thread_id)
146 }
147
148 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
149 validate_opaque_id("address.owner_id", &self.owner_id)?;
150 validate_opaque_id("address.workspace_id", &self.workspace_id)?;
151 validate_opaque_id("address.thread_id", &self.thread_id)?;
152 if let Some(task_id) = &self.task_id {
153 validate_opaque_id("address.task_id", task_id)?;
154 }
155 if let Some(session_id) = &self.session_id {
156 validate_opaque_id("address.session_id", session_id)?;
157 }
158 if self.thread_only && (self.task_id.is_some() || self.session_id.is_some()) {
159 return Err(AgentMailValidationError::new(
160 "address",
161 "a thread-only address cannot name a task or session",
162 ));
163 }
164 if !self.thread_only && self.task_id.is_none() && self.session_id.is_none() {
165 return Err(AgentMailValidationError::new(
166 "address",
167 "task_id or session_id is required",
168 ));
169 }
170 Ok(())
171 }
172 }
173
174 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
175 pub struct AgentMailSender {
176 /// Runtime-authorized stable identity; never a free-form transcript name.
177 pub identity: String,
178 pub display_label: String,
179 }
180
181 impl AgentMailSender {
182 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
183 validate_opaque_id("sender.identity", &self.identity)?;
184 validate_bounded_text(
185 "sender.display_label",
186 &self.display_label,
187 MAX_AGENT_MAIL_DISPLAY_LABEL_BYTES,
188 false,
189 )
190 }
191 }
192
193 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
194 #[serde(rename_all = "snake_case")]
195 pub enum AgentMailDeliveryMode {
196 QueueOnly,
197 WakeAtSafeBoundary,
198 }
199
200 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
201 #[serde(rename_all = "snake_case")]
202 pub enum AgentMailEvidenceKind {
203 RuntimeEvent,
204 TurnItem,
205 ArtifactReceipt,
206 }
207
208 /// Bounded pointer to evidence already authorized by the destination runtime.
209 ///
210 /// `reference_id` is deliberately opaque: paths and URLs are not valid evidence
211 /// references and must not be smuggled through this contract.
212 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
213 pub struct AgentMailEvidenceRef {
214 pub kind: AgentMailEvidenceKind,
215 pub reference_id: String,
216 #[serde(skip_serializing_if = "Option::is_none")]
217 pub label: Option<String>,
218 }
219
220 impl AgentMailEvidenceRef {
221 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
222 validate_opaque_id("evidence.reference_id", &self.reference_id)?;
223 if let Some(label) = &self.label {
224 validate_bounded_text(
225 "evidence.label",
226 label,
227 MAX_AGENT_MAIL_EVIDENCE_LABEL_BYTES,
228 false,
229 )?;
230 }
231 Ok(())
232 }
233 }
234
235 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
236 #[serde(rename_all = "snake_case")]
237 pub enum AgentMailStatus {
238 Queued,
239 Delivering,
240 Delivered,
241 Read,
242 Failed,
243 /// Explicitly withdrawn while queued (#6176). Terminal: delivery and the
244 /// wake pump never claim it, and re-cancel is an idempotent no-op.
245 Canceled,
246 }
247
248 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
249 #[serde(rename_all = "snake_case")]
250 pub enum AgentMailFailureCode {
251 AuthorizationDenied,
252 DestinationUnavailable,
253 DeliveryRejected,
254 Persistence,
255 AttemptLimit,
256 InvalidEnvelope,
257 }
258
259 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
260 pub struct AgentMailFailureReceipt {
261 pub code: AgentMailFailureCode,
262 pub message: String,
263 pub retryable: bool,
264 pub failed_at: DateTime<Utc>,
265 }
266
267 impl AgentMailFailureReceipt {
268 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
269 validate_bounded_text(
270 "failure.message",
271 &self.message,
272 MAX_AGENT_MAIL_FAILURE_MESSAGE_BYTES,
273 false,
274 )
275 }
276 }
277
278 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
279 pub struct AgentMailEnvelope {
280 #[serde(default = "default_agent_mail_schema_version")]
281 pub schema_version: u32,
282 pub message_id: AgentMailMessageId,
283 pub source: AgentMailAddress,
284 pub destination: AgentMailAddress,
285 pub sender: AgentMailSender,
286 /// Sanitized, bounded content presented to the destination task and UI.
287 pub summary: String,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub evidence: Vec<AgentMailEvidenceRef>,
290 pub delivery_mode: AgentMailDeliveryMode,
291 /// Explicit loop-breaking decision. It must agree with `delivery_mode`.
292 pub trigger_turn: bool,
293 pub hop_count: u8,
294 pub status: AgentMailStatus,
295 pub created_at: DateTime<Utc>,
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub delivered_at: Option<DateTime<Utc>>,
298 #[serde(skip_serializing_if = "Option::is_none")]
299 pub read_at: Option<DateTime<Utc>>,
300 #[serde(default)]
301 pub attempt_count: u8,
302 #[serde(skip_serializing_if = "Option::is_none")]
303 pub failure: Option<AgentMailFailureReceipt>,
304 #[serde(skip_serializing_if = "Option::is_none")]
305 pub delivery_turn_id: Option<String>,
306 }
307
308 impl AgentMailEnvelope {
309 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
310 if self.schema_version != AGENT_MAIL_SCHEMA_VERSION {
311 return Err(AgentMailValidationError::new(
312 "schema_version",
313 format!("expected {AGENT_MAIL_SCHEMA_VERSION}"),
314 ));
315 }
316 self.source.validate()?;
317 self.destination.validate()?;
318 self.sender.validate()?;
319 validate_summary_and_delivery(
320 &self.summary,
321 &self.evidence,
322 self.delivery_mode,
323 self.trigger_turn,
324 self.hop_count,
325 )?;
326 if self.attempt_count > MAX_AGENT_MAIL_DELIVERY_ATTEMPTS {
327 return Err(AgentMailValidationError::new(
328 "attempt_count",
329 format!("must be at most {MAX_AGENT_MAIL_DELIVERY_ATTEMPTS}"),
330 ));
331 }
332 if let Some(turn_id) = &self.delivery_turn_id {
333 validate_opaque_id("delivery_turn_id", turn_id)?;
334 }
335
336 match self.status {
337 AgentMailStatus::Queued => {
338 require_absent(self.delivered_at.is_some(), "delivered_at", "queued")?;
339 require_absent(self.read_at.is_some(), "read_at", "queued")?;
340 require_absent(self.failure.is_some(), "failure", "queued")?;
341 require_absent(
342 self.delivery_turn_id.is_some(),
343 "delivery_turn_id",
344 "queued",
345 )?;
346 }
347 AgentMailStatus::Delivering => {
348 if self.attempt_count == 0 {
349 return Err(AgentMailValidationError::new(
350 "attempt_count",
351 "delivering mail requires at least one attempt",
352 ));
353 }
354 require_absent(self.delivered_at.is_some(), "delivered_at", "delivering")?;
355 require_absent(self.read_at.is_some(), "read_at", "delivering")?;
356 require_absent(self.failure.is_some(), "failure", "delivering")?;
357 }
358 AgentMailStatus::Delivered => self.validate_delivered(false)?,
359 AgentMailStatus::Read => self.validate_delivered(true)?,
360 AgentMailStatus::Canceled => {
361 // Canceled mail never started delivery: same absences as
362 // queued. Attempts stay 0 — cancel is only accepted while
363 // queued, before any delivery claim.
364 require_absent(self.delivered_at.is_some(), "delivered_at", "canceled")?;
365 require_absent(self.read_at.is_some(), "read_at", "canceled")?;
366 require_absent(self.failure.is_some(), "failure", "canceled")?;
367 require_absent(
368 self.delivery_turn_id.is_some(),
369 "delivery_turn_id",
370 "canceled",
371 )?;
372 }
373 AgentMailStatus::Failed => {
374 if self.attempt_count == 0 {
375 return Err(AgentMailValidationError::new(
376 "attempt_count",
377 "failed mail requires at least one attempt",
378 ));
379 }
380 let failure = self.failure.as_ref().ok_or_else(|| {
381 AgentMailValidationError::new("failure", "failed mail requires a receipt")
382 })?;
383 failure.validate()?;
384 if failure.failed_at < self.created_at {
385 return Err(AgentMailValidationError::new(
386 "failure.failed_at",
387 "cannot precede created_at",
388 ));
389 }
390 require_absent(self.delivered_at.is_some(), "delivered_at", "failed")?;
391 require_absent(self.read_at.is_some(), "read_at", "failed")?;
392 }
393 }
394 Ok(())
395 }
396
397 fn validate_delivered(&self, read: bool) -> Result<(), AgentMailValidationError> {
398 let delivered_at = self.delivered_at.as_ref().ok_or_else(|| {
399 AgentMailValidationError::new("delivered_at", "delivered mail requires a timestamp")
400 })?;
401 if delivered_at < &self.created_at {
402 return Err(AgentMailValidationError::new(
403 "delivered_at",
404 "cannot precede created_at",
405 ));
406 }
407 if self.delivery_turn_id.is_none() {
408 return Err(AgentMailValidationError::new(
409 "delivery_turn_id",
410 "delivered mail requires a destination turn",
411 ));
412 }
413 if self.attempt_count == 0 {
414 return Err(AgentMailValidationError::new(
415 "attempt_count",
416 "delivered mail requires at least one attempt",
417 ));
418 }
419 require_absent(self.failure.is_some(), "failure", "delivered")?;
420 match (read, self.read_at.as_ref()) {
421 (true, Some(read_at)) if read_at >= delivered_at => Ok(()),
422 (true, Some(_)) => Err(AgentMailValidationError::new(
423 "read_at",
424 "cannot precede delivered_at",
425 )),
426 (true, None) => Err(AgentMailValidationError::new(
427 "read_at",
428 "read mail requires a timestamp",
429 )),
430 (false, Some(_)) => Err(AgentMailValidationError::new(
431 "read_at",
432 "delivered mail cannot have read_at before entering read status",
433 )),
434 (false, None) => Ok(()),
435 }
436 }
437
438 /// Compares only immutable delivery intent, ignoring lifecycle state.
439 #[must_use]
440 pub fn is_idempotent_replay_of(&self, other: &Self) -> bool {
441 self.schema_version == other.schema_version
442 && self.message_id == other.message_id
443 && self.source == other.source
444 && self.destination == other.destination
445 && self.sender == other.sender
446 && self.summary == other.summary
447 && self.evidence == other.evidence
448 && self.delivery_mode == other.delivery_mode
449 && self.trigger_turn == other.trigger_turn
450 && self.hop_count == other.hop_count
451 }
452
453 /// Checks whether a replayed API request describes this persisted message.
454 #[must_use]
455 pub fn matches_send_request(&self, request: &AgentMailSendRequest) -> bool {
456 self.message_id == request.message_id
457 && self.source.thread_id == request.source_thread_id
458 && self.destination.thread_id == request.destination_thread_id
459 && self.sender == request.sender
460 && self.summary == request.summary
461 && self.evidence == request.evidence
462 && self.delivery_mode == request.delivery_mode
463 && self.trigger_turn == request.trigger_turn
464 && self.hop_count == request.hop_count
465 }
466 }
467
468 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
469 pub struct AgentMailSendRequest {
470 pub message_id: AgentMailMessageId,
471 pub source_thread_id: String,
472 pub destination_thread_id: String,
473 pub sender: AgentMailSender,
474 /// Runtime-sanitized before the request becomes a persisted envelope.
475 pub summary: String,
476 #[serde(default, skip_serializing_if = "Vec::is_empty")]
477 pub evidence: Vec<AgentMailEvidenceRef>,
478 pub delivery_mode: AgentMailDeliveryMode,
479 pub trigger_turn: bool,
480 #[serde(default)]
481 pub hop_count: u8,
482 }
483
484 impl AgentMailSendRequest {
485 pub fn validate(&self) -> Result<(), AgentMailValidationError> {
486 validate_opaque_id("source_thread_id", &self.source_thread_id)?;
487 validate_opaque_id("destination_thread_id", &self.destination_thread_id)?;
488 self.sender.validate()?;
489 validate_summary_and_delivery(
490 &self.summary,
491 &self.evidence,
492 self.delivery_mode,
493 self.trigger_turn,
494 self.hop_count,
495 )
496 }
497 }
498
499 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500 pub struct AgentMailSendResponse {
501 pub envelope: AgentMailEnvelope,
502 /// True when the message id and immutable intent already existed.
503 pub idempotent_replay: bool,
504 }
505
506 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
507 pub struct MissionMailEvent {
508 pub sequence: u64,
509 pub envelope: AgentMailEnvelope,
510 }
511
512 /// Canonical payload placed in every Agent Mail runtime event.
513 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
514 pub struct AgentMailEventPayload {
515 pub mail: AgentMailEnvelope,
516 }
517
518 fn default_agent_mail_schema_version() -> u32 {
519 AGENT_MAIL_SCHEMA_VERSION
520 }
521
522 fn validate_message_id(value: &str) -> Result<(), AgentMailValidationError> {
523 if !value.starts_with("mail_") {
524 return Err(AgentMailValidationError::new(
525 "message_id",
526 "must start with mail_",
527 ));
528 }
529 if value.len() > MAX_AGENT_MAIL_MESSAGE_ID_BYTES {
530 return Err(AgentMailValidationError::new(
531 "message_id",
532 format!("must be at most {MAX_AGENT_MAIL_MESSAGE_ID_BYTES} bytes"),
533 ));
534 }
535 if !value
536 .bytes()
537 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
538 {
539 return Err(AgentMailValidationError::new(
540 "message_id",
541 "contains unsupported characters",
542 ));
543 }
544 if value.len() == "mail_".len() {
545 return Err(AgentMailValidationError::new(
546 "message_id",
547 "requires an id after mail_",
548 ));
549 }
550 Ok(())
551 }
552
553 fn validate_opaque_id(field: &'static str, value: &str) -> Result<(), AgentMailValidationError> {
554 if value.is_empty() {
555 return Err(AgentMailValidationError::new(field, "must not be empty"));
556 }
557 if value.len() > MAX_AGENT_MAIL_OPAQUE_ID_BYTES {
558 return Err(AgentMailValidationError::new(
559 field,
560 format!("must be at most {MAX_AGENT_MAIL_OPAQUE_ID_BYTES} bytes"),
561 ));
562 }
563 if value == "."
564 || value.contains("..")
565 || !value.bytes().all(|byte| {
566 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'@')
567 })
568 {
569 return Err(AgentMailValidationError::new(
570 field,
571 "must be an opaque id, not a path or URL",
572 ));
573 }
574 Ok(())
575 }
576
577 fn validate_bounded_text(
578 field: &'static str,
579 value: &str,
580 max_bytes: usize,
581 allow_line_breaks: bool,
582 ) -> Result<(), AgentMailValidationError> {
583 if value.is_empty() {
584 return Err(AgentMailValidationError::new(field, "must not be empty"));
585 }
586 if value.len() > max_bytes {
587 return Err(AgentMailValidationError::new(
588 field,
589 format!("must be at most {max_bytes} bytes"),
590 ));
591 }
592 if value.trim() != value {
593 return Err(AgentMailValidationError::new(
594 field,
595 "must not have leading or trailing whitespace",
596 ));
597 }
598 let has_forbidden_control = value
599 .chars()
600 .any(|ch| ch.is_control() && !(allow_line_breaks && matches!(ch, '\n' | '\t')));
601 if has_forbidden_control {
602 return Err(AgentMailValidationError::new(
603 field,
604 "contains unsupported control characters",
605 ));
606 }
607 Ok(())
608 }
609
610 fn validate_summary_and_delivery(
611 summary: &str,
612 evidence: &[AgentMailEvidenceRef],
613 delivery_mode: AgentMailDeliveryMode,
614 trigger_turn: bool,
615 hop_count: u8,
616 ) -> Result<(), AgentMailValidationError> {
617 validate_bounded_text("summary", summary, MAX_AGENT_MAIL_SUMMARY_BYTES, true)?;
618 if evidence.len() > MAX_AGENT_MAIL_EVIDENCE_REFS {
619 return Err(AgentMailValidationError::new(
620 "evidence",
621 format!("must contain at most {MAX_AGENT_MAIL_EVIDENCE_REFS} references"),
622 ));
623 }
624 for reference in evidence {
625 reference.validate()?;
626 }
627 if hop_count > MAX_AGENT_MAIL_HOPS {
628 return Err(AgentMailValidationError::new(
629 "hop_count",
630 format!("must be at most {MAX_AGENT_MAIL_HOPS}"),
631 ));
632 }
633 let expected_trigger = matches!(delivery_mode, AgentMailDeliveryMode::WakeAtSafeBoundary);
634 if trigger_turn != expected_trigger {
635 return Err(AgentMailValidationError::new(
636 "trigger_turn",
637 "must be false for queue_only and true for wake_at_safe_boundary",
638 ));
639 }
640 Ok(())
641 }
642
643 fn require_absent(
644 present: bool,
645 field: &'static str,
646 status: &'static str,
647 ) -> Result<(), AgentMailValidationError> {
648 if present {
649 return Err(AgentMailValidationError::new(
650 field,
651 format!("must be absent while status is {status}"),
652 ));
653 }
654 Ok(())
655 }
656
657 #[cfg(test)]
658 mod tests {
659 use super::*;
660
661 fn address(thread_id: &str) -> AgentMailAddress {
662 AgentMailAddress {
663 owner_id: "acct_local".into(),
664 workspace_id: "ws_123".into(),
665 thread_id: thread_id.into(),
666 thread_only: false,
667 task_id: Some(format!("task_{thread_id}")),
668 session_id: None,
669 }
670 }
671
672 fn queued_envelope() -> AgentMailEnvelope {
673 AgentMailEnvelope {
674 schema_version: AGENT_MAIL_SCHEMA_VERSION,
675 message_id: AgentMailMessageId::parse("mail_123").unwrap(),
676 source: address("thr_a"),
677 destination: address("thr_b"),
678 sender: AgentMailSender {
679 identity: "agent_a".into(),
680 display_label: "Agent A".into(),
681 },
682 summary: "A bounded handoff".into(),
683 evidence: vec![AgentMailEvidenceRef {
684 kind: AgentMailEvidenceKind::RuntimeEvent,
685 reference_id: "evt_42".into(),
686 label: Some("Build receipt".into()),
687 }],
688 delivery_mode: AgentMailDeliveryMode::QueueOnly,
689 trigger_turn: false,
690 hop_count: 0,
691 status: AgentMailStatus::Queued,
692 created_at: Utc::now(),
693 delivered_at: None,
694 read_at: None,
695 attempt_count: 0,
696 failure: None,
697 delivery_turn_id: None,
698 }
699 }
700
701 #[test]
702 fn queued_envelope_roundtrips_with_canonical_event_names() {
703 let envelope = queued_envelope();
704 envelope.validate().unwrap();
705 let value = serde_json::to_value(AgentMailEventPayload {
706 mail: envelope.clone(),
707 })
708 .unwrap();
709 let decoded: AgentMailEventPayload = serde_json::from_value(value).unwrap();
710 assert_eq!(decoded.mail, envelope);
711 assert_eq!(AGENT_MAIL_EVENT_QUEUED, "agent_mail.queued");
712 assert_eq!(
713 AGENT_MAIL_EVENT_DELIVERY_FAILED,
714 "agent_mail.delivery_failed"
715 );
716 }
717
718 #[test]
719 fn rejects_bounds_controls_paths_and_excess_hops() {
720 assert!(AgentMailMessageId::parse("../../secret").is_err());
721 let mut envelope = queued_envelope();
722 envelope.summary = format!("ok\0{}", "x".repeat(MAX_AGENT_MAIL_SUMMARY_BYTES));
723 assert!(envelope.validate().is_err());
724
725 let mut envelope = queued_envelope();
726 envelope.evidence[0].reference_id = "/tmp/transcript".into();
727 assert!(envelope.validate().is_err());
728
729 let mut envelope = queued_envelope();
730 envelope.hop_count = MAX_AGENT_MAIL_HOPS + 1;
731 assert!(envelope.validate().is_err());
732 }
733
734 #[test]
735 fn requires_task_or_session_and_consistent_wake_control() {
736 let mut envelope = queued_envelope();
737 envelope.destination.task_id = None;
738 assert!(envelope.validate().is_err());
739
740 let mut envelope = queued_envelope();
741 envelope.trigger_turn = true;
742 assert!(envelope.validate().is_err());
743 envelope.delivery_mode = AgentMailDeliveryMode::WakeAtSafeBoundary;
744 assert!(envelope.validate().is_ok());
745 }
746
747 #[test]
748 fn lifecycle_fields_are_validated() {
749 let mut envelope = queued_envelope();
750 envelope.status = AgentMailStatus::Delivered;
751 envelope.attempt_count = 1;
752 envelope.delivered_at = Some(envelope.created_at);
753 envelope.delivery_turn_id = Some("turn_1".into());
754 assert!(envelope.validate().is_ok());
755
756 envelope.status = AgentMailStatus::Read;
757 assert!(envelope.validate().is_err());
758 envelope.read_at = envelope.delivered_at;
759 assert!(envelope.validate().is_ok());
760 }
761
762 #[test]
763 fn canceled_envelope_validates_without_delivery_fields() {
764 let mut envelope = queued_envelope();
765 envelope.status = AgentMailStatus::Canceled;
766 assert!(envelope.validate().is_ok());
767 envelope.delivery_turn_id = Some("turn_1".into());
768 assert!(envelope.validate().is_err());
769 assert_eq!(AGENT_MAIL_EVENT_CANCELED, "agent_mail.canceled");
770 }
771
772 #[test]
773 fn replay_equivalence_ignores_delivery_state_but_not_intent() {
774 let queued = queued_envelope();
775 let mut delivered = queued.clone();
776 delivered.status = AgentMailStatus::Delivered;
777 delivered.attempt_count = 1;
778 delivered.created_at += chrono::Duration::seconds(1);
779 delivered.delivered_at = Some(delivered.created_at);
780 delivered.delivery_turn_id = Some("turn_1".into());
781 assert!(queued.is_idempotent_replay_of(&delivered));
782
783 delivered.summary = "Different intent under the same id".into();
784 assert!(!queued.is_idempotent_replay_of(&delivered));
785 }
786 }
787
787 lines RUST