1pub const ENQUEUE_FIXTURE: &str = include_str!("../../../fixtures/execution/enqueue.v1.json");
8
9use crate::execution::{
10 AgentCommand, AgentObservation, ContextGeneration, ConversationSurface, DurableEvent, EventId,
11 FacadeRequest, FacadeResult, InvocationContext, PreparedAction, Revision, RunId, Scope,
12 ThreadId,
13};
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16
17pub const CURRENT_VERSION: u16 = 1;
19
20#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
24pub struct DispatchBinding {
25 pub dispatch_id: String,
27 pub agent_session_id: String,
29}
30
31#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
33pub struct CheckpointReference {
34 pub object_key: String,
36 pub sha256: String,
38 pub format_version: u32,
40}
41
42#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
44pub struct Metadata {
45 pub version: u16,
47 pub message_id: String,
49 pub correlation_id: String,
51 pub causation_id: Option<String>,
53 pub sent_at_unix_ms: u64,
55 pub dispatch: DispatchBinding,
57}
58
59#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
61#[serde(tag = "phase", rename_all = "snake_case")]
62#[serde(deny_unknown_fields)]
63pub enum AppFacadeRequest {
64 Invoke {
66 context: InvocationContext,
68 request: FacadeRequest,
70 },
71 Prepare {
73 context: InvocationContext,
75 request: FacadeRequest,
77 },
78 Commit {
80 context: InvocationContext,
82 action: PreparedAction,
84 },
85 Reject {
87 context: InvocationContext,
89 action: PreparedAction,
91 },
92}
93
94#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
96#[serde(tag = "type", rename_all = "snake_case")]
97#[serde(deny_unknown_fields)]
98pub enum CommandResponse {
99 Accepted {
101 context: InvocationContext,
103 disposition: AdmissionDisposition,
105 queue_revision: Option<Revision>,
107 },
108 Rejected {
110 context: InvocationContext,
112 code: String,
114 message: String,
116 },
117}
118
119#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum AdmissionDisposition {
123 Queued,
125 InteractionReady,
127 CancelRequested,
129}
130
131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
133pub struct ObservationMessage {
134 pub sequence: u64,
136 pub context: InvocationContext,
138 pub observation: AgentObservation,
140}
141
142#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
144pub struct ExecutionFailure {
145 pub context: InvocationContext,
146 pub code: String,
147 pub message: String,
148}
149
150#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
152pub struct EventAck {
153 pub event_id: EventId,
154 pub checkpoint: CheckpointReference,
156}
157
158#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
160pub struct CheckpointPurgeRequest {
161 pub purge_id: String,
162 pub conversation_key: String,
163 pub scope: Scope,
164 pub surface_id: ConversationSurface,
165 pub thread_id: ThreadId,
166}
167
168#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
170#[serde(tag = "status", rename_all = "snake_case")]
171#[serde(deny_unknown_fields)]
172pub enum CheckpointPurgeAck {
173 Deleted {
174 purge_id: String,
175 conversation_key: String,
176 thread_id: ThreadId,
177 deleted_objects: u32,
178 },
179 Failed {
180 purge_id: String,
181 conversation_key: String,
182 thread_id: ThreadId,
183 code: String,
184 message: String,
185 },
186}
187
188#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
191#[serde(deny_unknown_fields)]
192pub struct LlmModelSnapshot {
193 pub capabilities: llm_api::ModelCapabilities,
194 pub generation_support: LlmGenerationSupport,
195}
196
197pub use llm_api::GenerationSupport as LlmGenerationSupport;
200
201#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
205pub struct LlmRoute {
206 pub backend: String,
207 pub profile: String,
208 pub model: String,
209 pub provider_preferences: Vec<String>,
210 pub temperature: Option<f64>,
211 pub cache_control: Option<bool>,
212 pub reasoning_effort: Option<String>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub thinking: Option<bool>,
215 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub fast_mode: Option<bool>,
217 pub context_window_tokens: u32,
219 pub model_snapshot: LlmModelSnapshot,
221}
222
223#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
226pub struct LlmExecutionPlan {
227 pub revision: Option<String>,
228 pub route: LlmRoute,
229}
230
231#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
234pub struct CommandRequest {
235 pub command: AgentCommand,
236 pub context_generation: Option<ContextGeneration>,
238 pub llm_plan: Option<LlmExecutionPlan>,
239 pub base_checkpoint: Option<CheckpointReference>,
241 pub abandoned_run_id: Option<RunId>,
243}
244
245#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
247pub struct EventMessage {
248 pub event: DurableEvent,
249 pub checkpoint: CheckpointReference,
250}
251
252#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
254#[serde(tag = "type", rename_all = "snake_case")]
255#[serde(deny_unknown_fields)]
256pub enum AppFacadeResponse {
257 Result {
259 result: FacadeResult,
261 },
262 Prepared {
264 action: PreparedAction,
266 },
267 #[serde(deserialize_with = "crate::execution::deserialize_empty_variant")]
269 Rejected,
270 Failed {
272 code: String,
274 message: String,
276 retry_after_ms: Option<u64>,
278 },
279}
280
281#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
283#[serde(tag = "family", content = "payload", rename_all = "snake_case")]
284pub enum Payload {
285 Command(Box<CommandRequest>),
287 CommandResponse(CommandResponse),
289 Event(EventMessage),
291 EventAck(EventAck),
293 CheckpointPurge(CheckpointPurgeRequest),
295 CheckpointPurgeAck(CheckpointPurgeAck),
297 Observation(ObservationMessage),
299 ExecutionFailure(ExecutionFailure),
301 AppFacadeRequest(AppFacadeRequest),
303 AppFacadeResponse(AppFacadeResponse),
305}
306
307#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
309pub struct Envelope {
310 pub metadata: Metadata,
312 pub payload: Payload,
314}
315
316impl Envelope {
317 pub fn decode_json(input: &str) -> Result<Self, ProtocolError> {
327 let mut deserializer = serde_json::Deserializer::from_str(input);
328 let mut unknown = Vec::new();
329 let envelope: Self = serde_ignored::deserialize(&mut deserializer, |path| {
330 unknown.push(path.to_string());
331 })
332 .map_err(|error| ProtocolError::InvalidJson {
333 message: error.to_string(),
334 })?;
335 deserializer
336 .end()
337 .map_err(|error| ProtocolError::InvalidJson {
338 message: error.to_string(),
339 })?;
340 if let Some(path) = unknown.into_iter().next() {
341 return Err(ProtocolError::UnknownField { path });
342 }
343 envelope.validate()?;
344 Ok(envelope)
345 }
346
347 pub fn validate(&self) -> Result<(), ProtocolError> {
354 if self.metadata.version != CURRENT_VERSION {
355 return Err(ProtocolError::UnsupportedVersion {
356 actual: self.metadata.version,
357 });
358 }
359 if self.metadata.message_id.trim().is_empty() {
360 return Err(ProtocolError::MissingIdentifier("message_id"));
361 }
362 if self.metadata.correlation_id.trim().is_empty() {
363 return Err(ProtocolError::MissingIdentifier("correlation_id"));
364 }
365 validate_dispatch(&self.metadata.dispatch)?;
366 if matches!(&self.payload, Payload::Observation(message) if message.sequence == 0) {
367 return Err(ProtocolError::InvalidBinding(
368 "observation sequence must be positive".into(),
369 ));
370 }
371 if let Some(context) = self.context() {
372 validate_context(context)?;
373 }
374 if let Payload::Command(request) = &self.payload {
375 validate_command_binding(request)?;
376 }
377 if let Payload::CheckpointPurge(request) = &self.payload {
378 validate_purge_request(request)?;
379 }
380 if let Payload::CheckpointPurgeAck(ack) = &self.payload {
381 validate_purge_ack(ack)?;
382 }
383 if let Payload::EventAck(ack) = &self.payload {
384 validate_checkpoint_reference(&ack.checkpoint)?;
385 }
386 match &self.payload {
387 Payload::Command(request) => {
388 if let Some(reference) = &request.base_checkpoint {
389 validate_checkpoint_reference(reference)?;
390 }
391 if matches!(&request.command, AgentCommand::Cancel { .. })
392 && (request.base_checkpoint.is_some() || request.abandoned_run_id.is_some())
393 {
394 return Err(ProtocolError::InvalidBinding(
395 "cancel must target live execution without checkpoint recovery metadata"
396 .to_owned(),
397 ));
398 }
399 if request.abandoned_run_id.is_some() && request.base_checkpoint.is_none() {
400 return Err(ProtocolError::InvalidBinding(
401 "an abandoned run requires a base checkpoint".to_owned(),
402 ));
403 }
404 }
405 Payload::Event(message) => validate_checkpoint_reference(&message.checkpoint)?,
406 _ => {}
407 }
408 Ok(())
409 }
410
411 fn context(&self) -> Option<&InvocationContext> {
412 match &self.payload {
413 Payload::Command(request) => match &request.command {
414 AgentCommand::Enqueue { context, .. }
415 | AgentCommand::SubmitInteraction { context, .. }
416 | AgentCommand::Cancel { context } => Some(context),
417 },
418 Payload::Event(message) => Some(&message.event.context),
419 Payload::Observation(message) => Some(&message.context),
420 Payload::ExecutionFailure(message) => Some(&message.context),
421 Payload::AppFacadeRequest(request) => match request {
422 AppFacadeRequest::Invoke { context, .. }
423 | AppFacadeRequest::Prepare { context, .. }
424 | AppFacadeRequest::Commit { context, .. }
425 | AppFacadeRequest::Reject { context, .. } => Some(context),
426 },
427 Payload::CommandResponse(response) => match response {
428 CommandResponse::Accepted { context, .. }
429 | CommandResponse::Rejected { context, .. } => Some(context),
430 },
431 Payload::EventAck(_)
432 | Payload::CheckpointPurge(_)
433 | Payload::CheckpointPurgeAck(_)
434 | Payload::AppFacadeResponse(_) => None,
435 }
436 }
437}
438
439fn validate_purge_request(request: &CheckpointPurgeRequest) -> Result<(), ProtocolError> {
440 if request.purge_id.trim().is_empty() {
441 return Err(ProtocolError::MissingIdentifier("purge_id"));
442 }
443 if request.conversation_key.trim().is_empty() {
444 return Err(ProtocolError::MissingIdentifier("conversation_key"));
445 }
446 if request.scope.scope_id.as_str().trim().is_empty() {
447 return Err(ProtocolError::MissingIdentifier("scope_id"));
448 }
449 if request.thread_id.as_str().trim().is_empty() {
450 return Err(ProtocolError::MissingIdentifier("thread_id"));
451 }
452 Ok(())
453}
454
455fn validate_purge_ack(ack: &CheckpointPurgeAck) -> Result<(), ProtocolError> {
456 let (purge_id, conversation_key, thread_id) = match ack {
457 CheckpointPurgeAck::Deleted {
458 purge_id,
459 conversation_key,
460 thread_id,
461 ..
462 }
463 | CheckpointPurgeAck::Failed {
464 purge_id,
465 conversation_key,
466 thread_id,
467 ..
468 } => (purge_id, conversation_key, thread_id),
469 };
470 if purge_id.trim().is_empty() {
471 return Err(ProtocolError::MissingIdentifier("purge_id"));
472 }
473 if conversation_key.trim().is_empty() {
474 return Err(ProtocolError::MissingIdentifier("conversation_key"));
475 }
476 if thread_id.as_str().trim().is_empty() {
477 return Err(ProtocolError::MissingIdentifier("thread_id"));
478 }
479 if let CheckpointPurgeAck::Failed { code, .. } = ack
480 && code.trim().is_empty()
481 {
482 return Err(ProtocolError::MissingIdentifier("code"));
483 }
484 Ok(())
485}
486
487fn validate_dispatch(dispatch: &DispatchBinding) -> Result<(), ProtocolError> {
488 if dispatch.dispatch_id.trim().is_empty() {
489 return Err(ProtocolError::MissingIdentifier("dispatch_id"));
490 }
491 if dispatch.agent_session_id.trim().is_empty() {
492 return Err(ProtocolError::MissingIdentifier("agent_session_id"));
493 }
494 Ok(())
495}
496
497fn validate_checkpoint_reference(reference: &CheckpointReference) -> Result<(), ProtocolError> {
498 if reference.object_key.trim().is_empty() {
499 return Err(ProtocolError::MissingIdentifier("checkpoint_object_key"));
500 }
501 if reference.format_version == 0
502 || reference.sha256.len() != 64
503 || !reference
504 .sha256
505 .bytes()
506 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
507 {
508 return Err(ProtocolError::InvalidBinding(
509 "checkpoint reference is invalid".to_owned(),
510 ));
511 }
512 Ok(())
513}
514
515fn validate_command_binding(request: &CommandRequest) -> Result<(), ProtocolError> {
516 match (&request.command, &request.context_generation) {
517 (AgentCommand::Enqueue { .. } | AgentCommand::SubmitInteraction { .. }, Some(value))
518 if value.is_complete() => {}
519 (AgentCommand::Enqueue { .. } | AgentCommand::SubmitInteraction { .. }, _) => {
520 return Err(ProtocolError::InvalidBinding(
521 "enqueue and submit_interaction require a context generation".to_owned(),
522 ));
523 }
524 (AgentCommand::Cancel { .. }, None) => {}
525 (AgentCommand::Cancel { .. }, Some(_)) => {
526 return Err(ProtocolError::InvalidBinding(
527 "cancel must not carry a context generation".to_owned(),
528 ));
529 }
530 }
531 match (&request.command, &request.llm_plan) {
532 (AgentCommand::Enqueue { .. }, Some(plan)) => {
533 validate_llm_plan(plan)?;
534 Ok(())
535 }
536 (AgentCommand::Enqueue { .. }, None) => Err(ProtocolError::InvalidBinding(
537 "enqueue requires a frozen LLM plan".to_owned(),
538 )),
539 (AgentCommand::SubmitInteraction { .. }, Some(plan)) => validate_llm_plan(plan),
540 (AgentCommand::SubmitInteraction { .. }, None) => Err(ProtocolError::InvalidBinding(
541 "submit_interaction requires the run's frozen LLM plan".to_owned(),
542 )),
543 (_, Some(_)) => Err(ProtocolError::InvalidBinding(
544 "only commands that invoke the model may carry an LLM plan".to_owned(),
545 )),
546 (_, None) => Ok(()),
547 }
548}
549
550fn validate_llm_plan(plan: &LlmExecutionPlan) -> Result<(), ProtocolError> {
551 let route = &plan.route;
552 route
553 .model_snapshot
554 .generation_support
555 .validate()
556 .map_err(|error| ProtocolError::InvalidBinding(error.into()))?;
557 llm_api::GenerationParameters {
558 temperature: route.temperature,
559 reasoning_effort: route.reasoning_effort.clone(),
560 thinking: route.thinking,
561 fast_mode: route.fast_mode,
562 }
563 .validate()
564 .map_err(|error| ProtocolError::InvalidBinding(error.into()))?;
565 if route.backend.trim().is_empty()
566 || route.profile.trim().is_empty()
567 || route.model.trim().is_empty()
568 {
569 return Err(ProtocolError::InvalidBinding(
570 "LLM backend, profile, and model are required".to_owned(),
571 ));
572 }
573 if plan
574 .revision
575 .as_ref()
576 .is_some_and(|value| value.trim().is_empty())
577 || route
578 .provider_preferences
579 .iter()
580 .any(|value| value.trim().is_empty())
581 || route
582 .reasoning_effort
583 .as_ref()
584 .is_some_and(|value| value.trim().is_empty())
585 || route.temperature.is_some_and(|value| !value.is_finite())
586 || route.context_window_tokens <= 20_000
587 {
588 return Err(ProtocolError::InvalidBinding(
589 "LLM route contains invalid optional settings".to_owned(),
590 ));
591 }
592 Ok(())
593}
594
595fn validate_context(context: &InvocationContext) -> Result<(), ProtocolError> {
596 validate_scope(&context.scope)?;
597 for (name, value) in [
598 ("thread_id", context.thread_id.as_str()),
599 ("run_id", context.run_id.as_str()),
600 ("operation_id", context.operation_id.as_str()),
601 ] {
602 if value.trim().is_empty() {
603 return Err(ProtocolError::MissingIdentifier(name));
604 }
605 }
606 if !context.actor.valid_for(&context.scope, &context.surface_id) {
607 return Err(ProtocolError::InvalidBinding(
608 "Actor does not match the conversation scope and surface".into(),
609 ));
610 }
611 Ok(())
612}
613
614fn validate_scope(scope: &Scope) -> Result<(), ProtocolError> {
615 if scope.scope_id.as_str().trim().is_empty() {
616 return Err(ProtocolError::MissingIdentifier("scope_id"));
617 }
618 if scope
619 .tenant_id
620 .as_ref()
621 .is_some_and(|tenant| tenant.as_str().trim().is_empty())
622 {
623 return Err(ProtocolError::MissingIdentifier("tenant_id"));
624 }
625 Ok(())
626}
627
628#[derive(Clone, Debug, Error, Eq, PartialEq)]
630pub enum ProtocolError {
631 #[error("invalid protocol JSON: {message}")]
633 InvalidJson {
634 message: String,
636 },
637 #[error("unknown protocol field: {path}")]
639 UnknownField {
640 path: String,
642 },
643 #[error("unsupported protocol version {actual}")]
645 UnsupportedVersion {
646 actual: u16,
648 },
649 #[error("missing required identifier: {0}")]
651 MissingIdentifier(&'static str),
652 #[error("invalid command binding: {0}")]
654 InvalidBinding(String),
655}
656
657#[cfg(test)]
658mod tests {
659 use crate::execution::{
660 AccessMode, Actor, AgentEvent, ClientId, ContentPart, EventId, Message, MessageRole,
661 OperationId, RunId, RunOptions, Scope, ScopeId, TenantId, ThreadId, UseCase, UserId,
662 };
663
664 use super::*;
665
666 #[test]
667 fn rejects_unknown_protocol_version() {
668 let envelope = Envelope {
669 metadata: Metadata {
670 version: CURRENT_VERSION + 1,
671 message_id: "message-1".to_owned(),
672 correlation_id: "correlation-1".to_owned(),
673 causation_id: None,
674 sent_at_unix_ms: 0,
675 dispatch: dispatch(),
676 },
677 payload: Payload::Event(EventMessage {
678 event: DurableEvent {
679 id: EventId::from("event-1"),
680 sequence: 1,
681 context: InvocationContext {
682 scope: Scope {
683 tenant_id: None,
684 scope_id: ScopeId::from("scope-1"),
685 },
686 actor: Actor::user(
687 UserId::from("user-1"),
688 Some(ClientId::from("client-1")),
689 ),
690 surface_id: ConversationSurface::client_personal("user-1").unwrap(),
691 thread_id: ThreadId::from("thread-1"),
692 run_id: RunId::from("run-1"),
693 operation_id: OperationId::from("operation-1"),
694 deadline_unix_ms: None,
695 traceparent: None,
696 },
697 event: AgentEvent::Started,
698 },
699 checkpoint: checkpoint(),
700 }),
701 };
702
703 assert_eq!(
704 envelope.validate(),
705 Err(ProtocolError::UnsupportedVersion {
706 actual: CURRENT_VERSION + 1
707 })
708 );
709 }
710
711 #[test]
712 fn command_fixture_round_trips_without_shape_drift() {
713 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
714 let envelope = Envelope::decode_json(fixture).expect("valid golden fixture");
715
716 let expected = Envelope {
717 metadata: Metadata {
718 version: CURRENT_VERSION,
719 message_id: "message-1".to_owned(),
720 correlation_id: "correlation-1".to_owned(),
721 causation_id: None,
722 sent_at_unix_ms: 1_700_000_000_000,
723 dispatch: dispatch(),
724 },
725 payload: Payload::Command(Box::new(CommandRequest {
726 command: AgentCommand::Enqueue {
727 context: InvocationContext {
728 scope: Scope {
729 tenant_id: Some(TenantId::from("tenant-1")),
730 scope_id: ScopeId::from("scope-1"),
731 },
732 actor: Actor::user(
733 UserId::from("user-1"),
734 Some(ClientId::from("client-1")),
735 ),
736 surface_id: ConversationSurface::client_personal("user-1").unwrap(),
737 thread_id: ThreadId::from("thread-1"),
738 run_id: RunId::from("run-1"),
739 operation_id: OperationId::from("operation-1"),
740 deadline_unix_ms: None,
741 traceparent: None,
742 },
743 message: Message {
744 continuation: None,
745 role: MessageRole::User,
746 content: vec![ContentPart::Text {
747 text: "hello".to_owned(),
748 }],
749 },
750 options: RunOptions {
751 use_case: UseCase("chat".to_owned()),
752 access_mode: AccessMode::Interactive,
753 allow_tools: true,
754 max_steps: 8,
755 credit_budget: None,
756 debug: false,
757 },
758 },
759 context_generation: Some(ContextGeneration {
760 user_scope: "scope-1".to_owned(),
761 identity: "identity-1".to_owned(),
762 memory: "memory-1".to_owned(),
763 integration_guide: "guide-1".to_owned(),
764 installed_integrations: "installed-1".to_owned(),
765 scope_integrations: "scope-integrations-1".to_owned(),
766 }),
767 llm_plan: Some(LlmExecutionPlan {
768 revision: Some("1700000000000".to_owned()),
769 route: LlmRoute {
770 backend: "openrouter".to_owned(),
771 profile: "cloud_openrouter".to_owned(),
772 model: "openai/gpt-5.4-mini".to_owned(),
773 provider_preferences: vec!["OpenAI".to_owned()],
774 temperature: Some(0.5),
775 cache_control: Some(true),
776 reasoning_effort: None,
777 thinking: None,
778 fast_mode: None,
779 context_window_tokens: 128_000,
780 model_snapshot: LlmModelSnapshot {
781 capabilities: llm_api::ModelCapabilities {
782 input: vec!["image".to_owned()],
783 tool_calling: true,
784 structured_output: true,
785 },
786 generation_support: LlmGenerationSupport {
787 temperature: Some(true),
788 max_tokens: Some(true),
789 thinking: Some(true),
790 reasoning_efforts: Some(vec!["high".into()]),
791 temperature_with_reasoning: Some(true),
792 ..LlmGenerationSupport::default()
793 },
794 },
795 },
796 }),
797 base_checkpoint: None,
798 abandoned_run_id: None,
799 })),
800 };
801 assert_eq!(envelope, expected);
802 assert_eq!(
803 serde_json::to_value(envelope).expect("serializes"),
804 serde_json::from_str::<serde_json::Value>(fixture).expect("fixture JSON")
805 );
806 }
807
808 #[test]
809 fn snapshot_is_required_and_support_metadata_is_strict() {
810 let mut fixture: serde_json::Value = serde_json::from_str(ENQUEUE_FIXTURE).unwrap();
811 fixture["payload"]["payload"]["llm_plan"]["route"]
812 .as_object_mut()
813 .unwrap()
814 .remove("model_snapshot");
815 assert!(Envelope::decode_json(&fixture.to_string()).is_err());
816 let mut envelope = Envelope::decode_json(ENQUEUE_FIXTURE).unwrap();
817 let Payload::Command(command) = &mut envelope.payload else {
818 panic!("command");
819 };
820 command
821 .llm_plan
822 .as_mut()
823 .unwrap()
824 .route
825 .model_snapshot
826 .generation_support
827 .max_output_tokens = Some(0);
828 assert!(envelope.validate().is_err());
829 }
830
831 #[test]
832 fn generation_support_travels_in_catalog_spelling() {
833 let support = LlmGenerationSupport {
834 temperature: Some(true),
835 max_tokens: Some(true),
836 thinking: Some(true),
837 reasoning_efforts: Some(vec!["low".into(), "high".into()]),
838 reasoning_effort_default: Some("high".into()),
839 temperature_with_reasoning: Some(false),
840 temperature_max: Some(2.0),
841 max_output_tokens: Some(8_192),
842 fast_mode: Some(true),
843 };
844 let encoded = serde_json::to_value(&support).unwrap();
845 assert_eq!(
846 encoded["reasoningEfforts"],
847 serde_json::json!(["low", "high"])
848 );
849 assert_eq!(
850 encoded["temperatureWithReasoning"],
851 serde_json::json!(false)
852 );
853 assert_eq!(
854 serde_json::from_value::<LlmGenerationSupport>(encoded).unwrap(),
855 support
856 );
857 let ignored = serde_json::from_value::<LlmGenerationSupport>(serde_json::json!({
858 "temperature": true, "maxTokens": true, "reasoningEfforts": ["low"],
859 "temperatureWithReasoning": null, "temperatureMax": null, "maxOutputTokens": null,
860 "reasoningIntensity": "high"
861 }))
862 .unwrap();
863 assert_eq!(ignored.temperature, Some(true));
864 assert_eq!(
865 ignored.reasoning_efforts.as_deref(),
866 Some(["low".to_string()].as_slice())
867 );
868 }
869
870 fn dispatch() -> DispatchBinding {
871 DispatchBinding {
872 dispatch_id: "dispatch-1".to_owned(),
873 agent_session_id: "agent-session-1".to_owned(),
874 }
875 }
876
877 fn checkpoint() -> CheckpointReference {
878 CheckpointReference {
879 object_key: "checkpoints/abc.json".to_owned(),
880 sha256: "a".repeat(64),
881 format_version: 1,
882 }
883 }
884
885 #[test]
886 fn every_v1_golden_fixture_round_trips() {
887 let schema: serde_json::Value = serde_json::from_str(include_str!(
888 "../../../schema/execution/envelope.v1.schema.json"
889 ))
890 .expect("valid JSON Schema document");
891 let validator = jsonschema::validator_for(&schema).expect("valid JSON Schema semantics");
892 for fixture in [
893 include_str!("../../../fixtures/execution/enqueue.v1.json"),
894 include_str!("../../../fixtures/execution/completed-event.v1.json"),
895 include_str!("../../../fixtures/execution/interaction-required-event.v1.json"),
896 include_str!("../../../fixtures/execution/failed-event.v1.json"),
897 include_str!("../../../fixtures/execution/app-facade-prepare.v1.json"),
898 include_str!("../../../fixtures/execution/observation.v1.json"),
899 include_str!("../../../fixtures/execution/admission.v1.json"),
900 include_str!("../../../fixtures/execution/app-facade-prepared.v1.json"),
901 include_str!("../../../fixtures/execution/user-action-required-event.v1.json"),
902 include_str!("../../../fixtures/execution/event-ack.v1.json"),
903 include_str!("../../../fixtures/execution/checkpoint-purge.v1.json"),
904 include_str!("../../../fixtures/execution/checkpoint-purge-ack.v1.json"),
905 ] {
906 let json: serde_json::Value =
907 serde_json::from_str(fixture).expect("valid golden fixture JSON");
908 validator
909 .validate(&json)
910 .expect("golden fixture matches the normative schema");
911 let envelope = Envelope::decode_json(fixture).expect("fixture matches Rust DTOs");
912 assert_eq!(serde_json::to_value(envelope).expect("serializes"), json);
913 }
914 }
915
916 #[test]
917 fn rejects_blank_scoped_identifiers() {
918 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
919 let mut envelope: Envelope = serde_json::from_str(fixture).expect("valid golden fixture");
920 let Payload::Command(request) = &mut envelope.payload else {
921 panic!("enqueue fixture changed family");
922 };
923 let CommandRequest {
924 command: AgentCommand::Enqueue { context, .. },
925 ..
926 } = request.as_mut()
927 else {
928 panic!("enqueue fixture changed family");
929 };
930 context.scope.scope_id = ScopeId::from(" ");
931 assert_eq!(
932 envelope.validate(),
933 Err(ProtocolError::MissingIdentifier("scope_id"))
934 );
935 }
936
937 #[test]
938 fn strict_decoder_checks_other_commands_and_message_parts() {
939 let golden: serde_json::Value = serde_json::from_str(ENQUEUE_FIXTURE).unwrap();
940 let context = golden["payload"]["payload"]["command"]["context"].clone();
941 for command in [
942 serde_json::json!({"type": "cancel", "context": context}),
943 serde_json::json!({"type": "submit_interaction", "context": context,
944 "interaction": {"batch_id": "batch-1", "responses": [{"actionId": "action-1", "response": {"action":"approve"}}]}}),
945 ] {
946 let mut input = golden.clone();
947 if command["type"] == "cancel" {
948 input["payload"]["payload"]["llm_plan"] = serde_json::Value::Null;
949 input["payload"]["payload"]["context_generation"] = serde_json::Value::Null;
950 }
951 input["payload"]["payload"]["command"] = command;
952 Envelope::decode_json(&input.to_string()).expect("valid command");
953 input["payload"]["payload"]["command"]["unexpected"] = serde_json::Value::Null;
954 assert!(Envelope::decode_json(&input.to_string()).is_err());
955 }
956 for part in [
957 serde_json::json!({"type": "text", "text": "hello"}),
958 serde_json::json!({"type": "artifact", "uri": crate::execution::ArtifactReference::new("tenant-1", "scope-1", "a".repeat(64), crate::execution::ArtifactMetadata::image("image/png", 1, 1, 1).unwrap()).unwrap().uri().unwrap()}),
959 serde_json::json!({"type": "tool_call", "id": "call-1", "name": "test", "arguments": {"arbitrary": {"nested": null}}}),
960 serde_json::json!({"type": "tool_result", "call_id": "call-1", "result": {"arbitrary": true}, "is_error": false}),
961 ] {
962 let mut input = golden.clone();
963 input["payload"]["payload"]["command"]["message"]["content"][0] = part;
964 Envelope::decode_json(&input.to_string()).expect("valid content and opaque JSON");
965 input["payload"]["payload"]["command"]["message"]["content"][0]["unexpected"] =
966 serde_json::Value::Bool(true);
967 assert!(Envelope::decode_json(&input.to_string()).is_err());
968 }
969 assert!(
970 serde_json::from_value::<crate::execution::AgentEvent>(
971 serde_json::json!({"type": "started", "unexpected": true})
972 )
973 .is_err()
974 );
975 assert!(
976 serde_json::from_value::<AppFacadeResponse>(
977 serde_json::json!({"type": "rejected", "unexpected": null})
978 )
979 .is_err()
980 );
981 assert!(
982 serde_json::from_value::<crate::execution::AgentEvent>(
983 serde_json::json!({"type": "started"})
984 )
985 .is_ok()
986 );
987 assert!(
988 serde_json::from_value::<AppFacadeResponse>(serde_json::json!({"type": "rejected"}))
989 .is_ok()
990 );
991 }
992
993 #[test]
994 fn decoder_checks_every_closed_object_in_golden_envelopes() {
995 fn object_paths(value: &serde_json::Value, pointer: &str, paths: &mut Vec<String>) {
996 match value {
997 serde_json::Value::Object(fields) => {
998 paths.push(pointer.to_owned());
999 for (key, child) in fields {
1000 let key = key.replace('~', "~0").replace('/', "~1");
1001 object_paths(child, &format!("{pointer}/{key}"), paths);
1002 }
1003 }
1004 serde_json::Value::Array(items) => {
1005 for (index, child) in items.iter().enumerate() {
1006 object_paths(child, &format!("{pointer}/{index}"), paths);
1007 }
1008 }
1009 _ => {}
1010 }
1011 }
1012
1013 let schema: serde_json::Value = serde_json::from_str(include_str!(
1014 "../../../schema/execution/envelope.v1.schema.json"
1015 ))
1016 .unwrap();
1017 let validator = jsonschema::validator_for(&schema).unwrap();
1018 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/execution");
1019 let mut accepted_unknown = Vec::new();
1020 let mut checked = 0;
1021 for file in std::fs::read_dir(fixtures).unwrap() {
1022 let file = file.unwrap().path();
1023 if file.extension().is_none_or(|extension| extension != "json") {
1024 continue;
1025 }
1026 let input = std::fs::read_to_string(&file).unwrap();
1027 let golden: serde_json::Value = serde_json::from_str(&input).unwrap();
1028 validator
1029 .validate(&golden)
1030 .expect("valid canonical fixture");
1031 Envelope::decode_json(&input).expect("valid fixture decodes");
1032 let mut paths = Vec::new();
1033 object_paths(&golden, "", &mut paths);
1034 for pointer in paths {
1035 for extra in [serde_json::Value::Bool(true), serde_json::Value::Null] {
1036 let mut input = golden.clone();
1037 input
1038 .pointer_mut(&pointer)
1039 .unwrap()
1040 .as_object_mut()
1041 .unwrap()
1042 .insert("__unknown_probe".to_owned(), extra);
1043 let decoded = Envelope::decode_json(&input.to_string());
1044 if validator.is_valid(&input) {
1045 decoded.expect("protocol-owned opaque JSON must remain extensible");
1046 } else {
1047 checked += 1;
1048 if decoded.is_ok() {
1049 accepted_unknown.push(format!(
1050 "{}:{pointer}",
1051 file.file_name().unwrap().to_string_lossy()
1052 ));
1053 }
1054 }
1055 }
1056 }
1057 }
1058 assert!(checked > 100, "exercise the entire fixture graph");
1059 assert!(
1060 accepted_unknown.is_empty(),
1061 "unknown fields accepted at {accepted_unknown:#?}"
1062 );
1063 }
1064
1065 #[test]
1066 fn admission_rejects_removed_modes_and_requires_one_frozen_model() {
1067 let mut input: serde_json::Value =
1068 serde_json::from_str(include_str!("../../../fixtures/execution/enqueue.v1.json"))
1069 .unwrap();
1070 assert!(Envelope::decode_json(&input.to_string()).is_ok());
1071 input["payload"]["payload"]["llm_plan"]["model_mode"] = "auto".into();
1072 assert!(Envelope::decode_json(&input.to_string()).is_err());
1073 input["payload"]["payload"]["llm_plan"]
1074 .as_object_mut()
1075 .unwrap()
1076 .remove("model_mode");
1077 input["payload"]["payload"]["command"]["options"]["model_mode"] = "cheap".into();
1078 assert!(Envelope::decode_json(&input.to_string()).is_err());
1079 input["payload"]["payload"]["command"]["options"]
1080 .as_object_mut()
1081 .unwrap()
1082 .remove("model_mode");
1083 let plan = input["payload"]["payload"]["llm_plan"].take();
1084 input["payload"]["payload"]["llm_plan"] = serde_json::json!({"routes": [plan]});
1085 assert!(Envelope::decode_json(&input.to_string()).is_err());
1086 }
1087
1088 #[test]
1089 fn strict_decoder_rejects_unknown_nested_fields() {
1090 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
1091 let input = fixture.replacen(
1092 "\"sent_at_unix_ms\": 1700000000000",
1093 "\"sent_at_unix_ms\": 1700000000000, \"unexpected\": true",
1094 1,
1095 );
1096 assert!(matches!(
1097 Envelope::decode_json(&input),
1098 Err(ProtocolError::UnknownField { .. })
1099 ));
1100
1101 let mut input: serde_json::Value = serde_json::from_str(fixture).expect("fixture JSON");
1102 input["payload"]["payload"]["options"]["unexpected"] = serde_json::Value::Bool(true);
1103 assert!(matches!(
1104 Envelope::decode_json(&input.to_string()),
1105 Err(ProtocolError::UnknownField { .. })
1106 ));
1107 }
1108
1109 #[test]
1110 fn strict_decoder_treats_skip_optional_nulls_as_absent() {
1111 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
1112 let mut input: serde_json::Value = serde_json::from_str(fixture).expect("fixture JSON");
1113 input["payload"]["payload"]["llm_plan"]["route"]["fast_mode"] = serde_json::Value::Null;
1114 input["payload"]["payload"]["llm_plan"]["route"]["thinking"] = serde_json::Value::Null;
1115 input["payload"]["payload"]["llm_plan"]["route"]["model_snapshot"]["generation_support"]
1116 ["fastMode"] = serde_json::Value::Null;
1117 input["payload"]["payload"]["llm_plan"]["route"]["model_snapshot"]["generation_support"]
1118 ["reasoningEffortDefault"] = serde_json::Value::Null;
1119 input["payload"]["payload"]["command"]["message"]["continuation"] = serde_json::Value::Null;
1120
1121 let envelope = Envelope::decode_json(&input.to_string())
1122 .expect("null on skip-optional fields deserializes as absent");
1123 let canonical = serde_json::to_value(&envelope).expect("serializes");
1124 let canonical_route = &canonical["payload"]["payload"]["llm_plan"]["route"];
1125 assert!(canonical_route.get("fast_mode").is_none());
1126 assert!(canonical_route.get("thinking").is_none());
1127 let canonical_support = &canonical_route["model_snapshot"]["generation_support"];
1128 assert!(canonical_support.get("fastMode").is_none());
1129 assert!(canonical_support.get("reasoningEffortDefault").is_none());
1130 assert!(
1131 canonical["payload"]["payload"]["command"]["message"]
1132 .get("continuation")
1133 .is_none()
1134 );
1135
1136 let schema: serde_json::Value = serde_json::from_str(include_str!(
1137 "../../../schema/execution/envelope.v1.schema.json"
1138 ))
1139 .expect("schema");
1140 let validator = jsonschema::validator_for(&schema).expect("schema");
1141 assert!(
1142 validator.validate(&input).is_err(),
1143 "canonical emit omits skip-optional keys; schema must not advertise null"
1144 );
1145 }
1146
1147 #[test]
1148 fn schema_rejects_generation_support_and_continuation_nulls() {
1149 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
1150 let schema: serde_json::Value = serde_json::from_str(include_str!(
1151 "../../../schema/execution/envelope.v1.schema.json"
1152 ))
1153 .expect("schema");
1154 let validator = jsonschema::validator_for(&schema).expect("schema");
1155 let golden: serde_json::Value = serde_json::from_str(fixture).expect("fixture JSON");
1156 assert!(
1157 validator.validate(&golden).is_ok(),
1158 "golden enqueue fixture must remain emit-valid"
1159 );
1160
1161 let mut support_null = golden.clone();
1162 support_null["payload"]["payload"]["llm_plan"]["route"]["model_snapshot"]["generation_support"]
1163 ["fastMode"] = serde_json::Value::Null;
1164 assert!(
1165 validator.validate(&support_null).is_err(),
1166 "skip-optional generation_support.fastMode must omit, not null"
1167 );
1168
1169 let mut continuation_null = golden;
1170 continuation_null["payload"]["payload"]["command"]["message"]["continuation"] =
1171 serde_json::Value::Null;
1172 assert!(
1173 validator.validate(&continuation_null).is_err(),
1174 "skip-optional message.continuation must omit, not null"
1175 );
1176 }
1177
1178 #[test]
1179 fn strict_decoder_still_rejects_unknown_null_fields() {
1180 let fixture = include_str!("../../../fixtures/execution/enqueue.v1.json");
1181 let mut input: serde_json::Value = serde_json::from_str(fixture).expect("fixture JSON");
1182 input["payload"]["payload"]["llm_plan"]["route"]["unexpected"] = serde_json::Value::Null;
1183 assert!(matches!(
1184 Envelope::decode_json(&input.to_string()),
1185 Err(ProtocolError::UnknownField { .. })
1186 ));
1187 }
1188
1189 #[test]
1190 fn abandoned_run_requires_a_base_checkpoint() {
1191 let mut value: serde_json::Value =
1192 serde_json::from_str(include_str!("../../../fixtures/execution/enqueue.v1.json"))
1193 .unwrap();
1194 value["payload"]["payload"]["abandoned_run_id"] =
1195 serde_json::Value::String("run-abandoned".to_owned());
1196
1197 assert!(matches!(
1198 Envelope::decode_json(&value.to_string()),
1199 Err(ProtocolError::InvalidBinding(_))
1200 ));
1201 }
1202}