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