1use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::fmt;
8
9pub const PROTOCOL: &str = "rpi-shared-host";
10pub const MAJOR: u16 = 1;
11pub const MINOR: u16 = 6;
12pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
13pub const MAX_RESULT_TEXT_BYTES: usize = 16 * 1024;
15pub const MAX_PAGE_SIZE: usize = 128;
16pub const MAX_SUBMIT_PROMPT_BYTES: usize = 256 * 1024;
19
20macro_rules! identity {
21 ($name:ident) => {
22 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
23 #[serde(try_from = "String", into = "String")]
24 pub struct $name(uuid::Uuid);
25 impl $name {
26 pub fn new() -> Self {
27 Self(uuid::Uuid::new_v4())
28 }
29 }
30 impl Default for $name {
31 fn default() -> Self {
32 Self::new()
33 }
34 }
35 impl TryFrom<String> for $name {
36 type Error = &'static str;
37 fn try_from(value: String) -> Result<Self, Self::Error> {
38 let id = uuid::Uuid::parse_str(&value).map_err(|_| "invalid identity")?;
39 if id.is_nil() {
40 return Err("nil identity");
41 }
42 Ok(Self(id))
43 }
44 }
45 impl From<$name> for String {
46 fn from(value: $name) -> Self {
47 value.0.to_string()
48 }
49 }
50 impl fmt::Display for $name {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 self.0.fmt(f)
53 }
54 }
55 };
56}
57identity!(HostId);
58identity!(Epoch);
59identity!(AgentId);
60identity!(RequestId);
61identity!(CallId);
62identity!(TicketId);
63identity!(ControlScopeId);
64identity!(ProfileVersion);
65identity!(RunId);
66
67#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct MiniRequest {
72 pub scope: ControlScopeId,
73 pub epoch: Epoch,
74 pub request_id: RequestId,
75 pub action: MiniAction,
76}
77#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
79pub enum MiniAction {
80 Submit {
81 agent_id: AgentId,
82 prompt: String,
83 },
84 Cancel {
85 agent_id: AgentId,
86 submitted_request_id: RequestId,
87 run_id: RunId,
88 },
89 Close {
92 agent_id: AgentId,
93 },
94}
95impl MiniAction {
96 pub fn agent(&self) -> AgentId {
97 match self {
98 Self::Submit { agent_id, .. }
99 | Self::Cancel { agent_id, .. }
100 | Self::Close { agent_id } => *agent_id,
101 }
102 }
103}
104impl MiniRequest {
105 pub fn valid(&self) -> bool {
106 match &self.action {
107 MiniAction::Submit { prompt, .. } => {
108 !prompt.trim().is_empty() && prompt.len() <= MAX_SUBMIT_PROMPT_BYTES
109 }
110 _ => true,
111 }
112 }
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct ProfileRef {
119 pub agent_id: AgentId,
120 pub version: ProfileVersion,
121}
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct AdministrativeRequest {
127 pub scope: ControlScopeId,
128 pub request_id: RequestId,
129 pub epoch: Epoch,
130 pub action: AdministrativeAction,
131}
132#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
133#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
134pub enum AdministrativeAction {
135 Create {
137 agent_id: AgentId,
138 },
139 Restore {
140 agent_id: AgentId,
141 revision: u64,
142 },
143 CreateProfile {
144 profile: ProfileRef,
145 },
146 RestoreProfile {
147 profile: ProfileRef,
148 revision: u64,
149 },
150 Cancel {
151 agent_id: AgentId,
152 revision: u64,
153 ticket_id: TicketId,
154 },
155 CancelSubmitted {
157 agent_id: AgentId,
158 revision: u64,
159 submitted_request_id: RequestId,
160 },
161 Close {
162 agent_id: AgentId,
163 revision: u64,
164 },
165 Stop {},
166}
167impl AdministrativeRequest {
168 pub fn valid(&self) -> bool {
169 match self.action {
170 AdministrativeAction::Restore { revision, .. }
171 | AdministrativeAction::RestoreProfile { revision, .. }
172 | AdministrativeAction::Cancel { revision, .. }
173 | AdministrativeAction::CancelSubmitted { revision, .. }
174 | AdministrativeAction::Close { revision, .. } => {
175 (1..=i64::MAX as u64).contains(&revision)
176 }
177 _ => true,
178 }
179 }
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(deny_unknown_fields)]
184pub struct Version {
185 pub major: u16,
186 pub minor: u16,
187}
188impl Default for Version {
189 fn default() -> Self {
190 Self {
191 major: MAJOR,
192 minor: MINOR,
193 }
194 }
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(rename_all = "snake_case")]
200pub enum Capability {
201 Status,
202 List,
203 Inspect,
204 Receipts,
205 Results,
206 Profiles,
207 AdministrativeReceipts,
208 AdministrativeCreate,
209 AdministrativeRestore,
210 AdministrativeClose,
211 AdministrativeCancel,
212 AdministrativeStop,
213 Create,
214 Submit,
215 Cancel,
216 Close,
217 Restore,
218 Events,
219 Approvals,
220 Configure,
221 Stop,
222 Mini,
223 #[serde(other)]
224 Unknown,
225}
226
227#[derive(Clone, Serialize, Deserialize)]
230#[serde(try_from = "String", into = "String")]
231pub struct AuthToken(String);
232impl AuthToken {
233 pub fn new(value: String) -> Result<Self, &'static str> {
234 if !(32..=128).contains(&value.len())
235 || !value
236 .bytes()
237 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
238 {
239 return Err("invalid authentication token");
240 }
241 Ok(Self(value))
242 }
243 pub fn matches(&self, other: &Self) -> bool {
244 let a = self.0.as_bytes();
247 let b = other.0.as_bytes();
248 let mut diff = a.len() ^ b.len();
249 for i in 0..128 {
250 diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
251 }
252 diff == 0
253 }
254}
255impl TryFrom<String> for AuthToken {
256 type Error = &'static str;
257 fn try_from(value: String) -> Result<Self, Self::Error> {
258 Self::new(value)
259 }
260}
261impl From<AuthToken> for String {
262 fn from(value: AuthToken) -> Self {
263 value.0
264 }
265}
266impl fmt::Debug for AuthToken {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 f.write_str("AuthToken([redacted])")
269 }
270}
271
272#[derive(Clone, Debug, Serialize, Deserialize)]
273#[serde(deny_unknown_fields)]
274pub struct Hello {
275 pub protocol: String,
276 pub version: Version,
277 pub host_id: HostId,
278 pub token: AuthToken,
279}
280
281#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
282#[serde(deny_unknown_fields)]
283pub struct Limits {
284 pub max_frame_bytes: usize,
285 pub max_in_flight: usize,
286 pub max_page_size: usize,
287}
288impl Default for Limits {
289 fn default() -> Self {
290 Self {
291 max_frame_bytes: MAX_FRAME_BYTES,
292 max_in_flight: 64,
293 max_page_size: MAX_PAGE_SIZE,
294 }
295 }
296}
297impl Limits {
298 pub fn valid(&self) -> bool {
299 (512..=MAX_FRAME_BYTES).contains(&self.max_frame_bytes)
300 && (1..=64).contains(&self.max_in_flight)
301 && (1..=MAX_PAGE_SIZE).contains(&self.max_page_size)
302 }
303}
304
305#[derive(Clone, Debug, Serialize, Deserialize)]
306#[serde(deny_unknown_fields)]
307pub struct Welcome {
308 pub protocol: String,
309 pub version: Version,
310 pub host_id: HostId,
311 pub epoch: Epoch,
312 pub capabilities: Vec<Capability>,
313 pub limits: Limits,
314}
315impl Welcome {
316 pub fn compatible(&self, host: HostId) -> bool {
317 self.protocol == PROTOCOL
318 && self.version.major == MAJOR
319 && self.host_id == host
320 && self.limits.valid()
321 && self.capabilities.len() <= 64
322 }
323 pub fn supports(&self, capability: Capability) -> bool {
324 capability != Capability::Unknown
325 && self.capabilities.contains(&capability)
326 && (capability != Capability::Mini || self.version.minor >= 6)
327 }
328}
329
330#[derive(Clone, Debug, Serialize, Deserialize)]
331#[serde(deny_unknown_fields)]
332pub struct Request {
333 pub call_id: CallId,
335 pub epoch: Epoch,
336 pub command: Command,
337}
338
339#[derive(Clone, Debug, Serialize, Deserialize)]
340#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
341pub enum Command {
342 Status {},
345 MiniExecute {
348 request: MiniRequest,
349 },
350 MiniReceipt {
352 request: MiniRequest,
353 },
354 MiniResult {
356 scope: ControlScopeId,
357 epoch: Epoch,
358 agent_id: AgentId,
359 request_id: RequestId,
360 run_id: Option<RunId>,
361 offset: usize,
362 max_bytes: usize,
363 },
364 List {
365 after: Option<AgentId>,
366 limit: usize,
367 },
368 Inspect {
369 agent_id: AgentId,
370 },
371 Profiles {
373 after: Option<AgentId>,
374 limit: usize,
375 },
376 AdministrativeReceipt {
378 request: AdministrativeRequest,
379 },
380 AdministrativeCreate {
382 request: AdministrativeRequest,
383 },
384 AdministrativeRestore {
386 request: AdministrativeRequest,
387 },
388 AdministrativeClose {
390 request: AdministrativeRequest,
391 },
392 AdministrativeCancel {
395 request: AdministrativeRequest,
396 },
397 AdministrativeStop {
400 request: AdministrativeRequest,
401 },
402 Receipt {
405 agent_id: AgentId,
406 request_id: RequestId,
407 },
408 Result {
411 agent_id: AgentId,
412 request_id: RequestId,
413 run_id: Option<String>,
414 offset: usize,
415 max_bytes: usize,
416 },
417 Submit {
421 agent_id: AgentId,
422 request_id: RequestId,
423 prompt: String,
424 },
425 Cancel {
428 mutation: AgentMutation,
429 ticket_id: TicketId,
430 },
431 Close {
432 mutation: AgentMutation,
433 },
434 Restore {
435 mutation: AgentMutation,
436 },
437 Stop {
438 request_id: RequestId,
439 },
440}
441#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
442#[serde(deny_unknown_fields)]
443pub struct AgentMutation {
444 pub request_id: RequestId,
445 pub agent_id: AgentId,
446 pub revision: u64,
447}
448impl Command {
449 pub fn capability(&self) -> Capability {
450 match self {
451 Self::Status {} => Capability::Status,
452 Self::MiniExecute { .. } | Self::MiniReceipt { .. } | Self::MiniResult { .. } => {
453 Capability::Mini
454 }
455 Self::List { .. } => Capability::List,
456 Self::Inspect { .. } => Capability::Inspect,
457 Self::Profiles { .. } => Capability::Profiles,
458 Self::AdministrativeReceipt { .. } => Capability::AdministrativeReceipts,
459 Self::AdministrativeCreate { .. } => Capability::AdministrativeCreate,
460 Self::AdministrativeRestore { .. } => Capability::AdministrativeRestore,
461 Self::AdministrativeClose { .. } => Capability::AdministrativeClose,
462 Self::AdministrativeCancel { .. } => Capability::AdministrativeCancel,
463 Self::AdministrativeStop { .. } => Capability::AdministrativeStop,
464 Self::Receipt { .. } => Capability::Receipts,
465 Self::Result { .. } => Capability::Results,
466 Self::Submit { .. } => Capability::Submit,
467 Self::Cancel { .. } => Capability::Cancel,
468 Self::Close { .. } => Capability::Close,
469 Self::Restore { .. } => Capability::Restore,
470 Self::Stop { .. } => Capability::Stop,
471 }
472 }
473 pub fn request_id(&self) -> Option<RequestId> {
474 match self {
475 Self::MiniExecute { request } => Some(request.request_id),
476 Self::AdministrativeCreate { request }
477 | Self::AdministrativeRestore { request }
478 | Self::AdministrativeClose { request }
479 | Self::AdministrativeCancel { request }
480 | Self::AdministrativeStop { request } => Some(request.request_id),
481 Self::Cancel { mutation, .. }
482 | Self::Close { mutation }
483 | Self::Restore { mutation } => Some(mutation.request_id),
484 Self::Submit { request_id, .. } => Some(*request_id),
485 Self::Stop { request_id } => Some(*request_id),
486 _ => None,
487 }
488 }
489 pub fn valid(&self, limits: Limits) -> bool {
490 match self {
491 Self::MiniExecute { request } | Self::MiniReceipt { request } => request.valid(),
492 Self::MiniResult {
493 offset,
494 max_bytes,
495 run_id,
496 ..
497 } => {
498 (4..=MAX_RESULT_TEXT_BYTES).contains(max_bytes)
499 && (*offset == 0 || run_id.is_some())
500 }
501 Self::List { limit, .. } | Self::Profiles { limit, .. } => {
502 (1..=limits.max_page_size).contains(limit)
503 }
504 Self::AdministrativeReceipt { request } => request.valid(),
505 Self::AdministrativeCreate { request } => {
506 request.valid()
507 && matches!(request.action, AdministrativeAction::CreateProfile { .. })
508 }
509 Self::AdministrativeRestore { request } => {
510 request.valid()
511 && matches!(request.action, AdministrativeAction::RestoreProfile { .. })
512 }
513 Self::AdministrativeClose { request } => {
514 request.valid() && matches!(request.action, AdministrativeAction::Close { .. })
515 }
516 Self::AdministrativeCancel { request } => {
517 request.valid()
518 && matches!(request.action, AdministrativeAction::CancelSubmitted { .. })
519 }
520 Self::AdministrativeStop { request } => {
521 request.valid() && matches!(request.action, AdministrativeAction::Stop {})
522 }
523 Self::Cancel { mutation, .. }
524 | Self::Close { mutation }
525 | Self::Restore { mutation } => (1..=i64::MAX as u64).contains(&mutation.revision),
526 Self::Result {
527 run_id,
528 offset,
529 max_bytes,
530 ..
531 } => {
532 (4..=MAX_RESULT_TEXT_BYTES).contains(max_bytes)
533 && (*offset == 0 || run_id.is_some())
534 && run_id
535 .as_ref()
536 .is_none_or(|id| !id.is_empty() && id.len() <= 128)
537 }
538 Self::Submit { prompt, .. } => {
539 !prompt.trim().is_empty() && prompt.len() <= MAX_SUBMIT_PROMPT_BYTES
540 }
541 _ => true,
542 }
543 }
544}
545
546#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
547#[serde(rename_all = "snake_case")]
548pub enum ErrorCode {
549 Unsupported,
550 Unauthorized,
551 InvalidRequest,
552 NotFound,
553 Busy,
554 Capacity,
555 StaleEpoch,
556 StaleRevision,
557 Conflict,
558 ResyncRequired,
559 PersistenceUncertain,
560 OutcomeUnknown,
561 Expired,
562 Internal,
563}
564
565#[derive(Clone, Debug, Serialize, Deserialize)]
566#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
567pub enum Reply {
568 Data {
571 data: Value,
572 },
573 Error {
574 code: ErrorCode,
575 },
576}
577#[derive(Clone, Debug, Serialize, Deserialize)]
578#[serde(deny_unknown_fields)]
579pub struct Response {
580 pub call_id: CallId,
581 pub epoch: Epoch,
582 pub reply: Reply,
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588 #[test]
589 fn mini_intents_are_closed_volatile_and_never_durable_admissions() {
590 let request = MiniRequest {
591 scope: ControlScopeId::new(),
592 epoch: Epoch::new(),
593 request_id: RequestId::new(),
594 action: MiniAction::Submit {
595 agent_id: AgentId::new(),
596 prompt: "literal {{mini}}".into(),
597 },
598 };
599 let execute = Command::MiniExecute {
600 request: request.clone(),
601 };
602 let query = Command::MiniReceipt {
603 request: request.clone(),
604 };
605 assert_eq!(execute.request_id(), Some(request.request_id));
606 assert_eq!(query.request_id(), None);
607 assert_eq!(execute.capability(), Capability::Mini);
608 assert!(execute.valid(Limits::default()));
609 for key in ["grant", "session", "durable", "revision"] {
610 let mut value = serde_json::to_value(&execute).unwrap();
611 value["request"][key] = Value::Bool(true);
612 assert!(serde_json::from_value::<Command>(value).is_err());
613 }
614 let mut empty = request;
615 empty.action = MiniAction::Submit {
616 agent_id: AgentId::new(),
617 prompt: " ".into(),
618 };
619 assert!(!empty.valid());
620 let mut value = serde_json::to_value(Command::MiniResult {
621 scope: ControlScopeId::new(),
622 epoch: Epoch::new(),
623 agent_id: AgentId::new(),
624 request_id: RequestId::new(),
625 run_id: None,
626 offset: 1,
627 max_bytes: 4096,
628 })
629 .unwrap();
630 assert!(!serde_json::from_value::<Command>(value.clone())
631 .unwrap()
632 .valid(Limits::default()));
633 value["run_id"] = serde_json::json!(RunId::new());
634 assert!(serde_json::from_value::<Command>(value)
635 .unwrap()
636 .valid(Limits::default()));
637 }
638 #[test]
639 fn golden_frames_roundtrip_and_reject_ambiguous_mutations() {
640 let frames: Value = serde_json::from_str(include_str!("fixtures/control-v1.json")).unwrap();
641 let hello: Hello = serde_json::from_value(frames["hello"].clone()).unwrap();
642 let welcome: Welcome = serde_json::from_value(frames["welcome"].clone()).unwrap();
643 assert!(welcome.compatible(hello.host_id));
644 assert!(welcome.supports(Capability::Status));
645 assert!(!welcome.supports(Capability::Unknown));
646 for value in frames["requests"].as_array().unwrap() {
647 let request: Request = serde_json::from_value(value.clone()).unwrap();
648 assert!(request.command.valid(welcome.limits));
649 assert_eq!(serde_json::to_value(request).unwrap(), *value);
650 }
651 let response: Response = serde_json::from_value(frames["response"].clone()).unwrap();
652 assert_eq!(serde_json::to_value(response).unwrap(), frames["response"]);
653 let cancel = frames["requests"]
654 .as_array()
655 .unwrap()
656 .iter()
657 .position(|value| value["command"]["op"] == "cancel")
658 .expect("golden fixture carries a cancel mutation");
659 let mut request = frames["requests"][cancel].clone();
660 request["command"]["mutation"]["revision"] = 0.into();
661 assert!(!serde_json::from_value::<Request>(request.clone())
662 .unwrap()
663 .command
664 .valid(welcome.limits));
665 request["command"]["mutation"]
666 .as_object_mut()
667 .unwrap()
668 .remove("request_id");
669 assert!(serde_json::from_value::<Request>(request).is_err());
670 assert!(
671 serde_json::from_str::<CallId>("\"00000000-0000-0000-0000-000000000000\"").is_err()
672 );
673 assert!(
674 serde_json::from_str::<Command>(r#"{"op":"status","argv":["--approve"]}"#).is_err()
675 );
676 let agent: AgentId = "66666666-6666-4666-8666-666666666666"
677 .to_string()
678 .try_into()
679 .unwrap();
680 let request: RequestId = "99999999-9999-4999-8999-999999999999"
681 .to_string()
682 .try_into()
683 .unwrap();
684 for prompt in [String::new(), " \n ".into()] {
685 assert!(!Command::Submit {
686 agent_id: agent,
687 request_id: request,
688 prompt
689 }
690 .valid(welcome.limits));
691 }
692 assert!(!Command::Submit {
693 agent_id: agent,
694 request_id: request,
695 prompt: "x".repeat(MAX_SUBMIT_PROMPT_BYTES + 1),
696 }
697 .valid(welcome.limits));
698 assert!(Command::Submit {
699 agent_id: agent,
700 request_id: request,
701 prompt: "hello".into(),
702 }
703 .valid(welcome.limits));
704 }
705 #[test]
706 fn result_pages_are_read_only_bounded_and_require_original_run_after_offset_zero() {
707 let agent_id = AgentId::new();
708 let request_id = RequestId::new();
709 let make = |run_id: Option<String>, offset, max_bytes| Command::Result {
710 agent_id,
711 request_id,
712 run_id,
713 offset,
714 max_bytes,
715 };
716 let command = make(None, 0, MAX_RESULT_TEXT_BYTES);
717 assert_eq!(command.capability(), Capability::Results);
718 assert!(command.request_id().is_none());
719 assert!(command.valid(Limits::default()));
720 assert!(!make(None, 1, 4096).valid(Limits::default()));
721 assert!(!make(Some(String::new()), 0, 4096).valid(Limits::default()));
722 assert!(!make(Some("x".repeat(129)), 0, 4096).valid(Limits::default()));
723 assert!(!make(None, 0, 3).valid(Limits::default()));
724 assert!(!make(None, 0, MAX_RESULT_TEXT_BYTES + 1).valid(Limits::default()));
725 assert!(make(Some("native-run".into()), usize::MAX, 4).valid(Limits::default()));
726 assert!(serde_json::from_str::<Command>(r#"{"op":"result","agent_id":"66666666-6666-4666-8666-666666666666","request_id":"99999999-9999-4999-8999-999999999999","offset":0,"max_bytes":4096,"path":"/must/not/read"}"#).is_err());
727 }
728 #[test]
729 fn token_debug_and_errors_never_reveal_material() {
730 let token = AuthToken::new("fixture-only-auth-token-0123456789".into()).unwrap();
731 assert_eq!(format!("{token:?}"), "AuthToken([redacted])");
732 assert!(token.matches(&token.clone()));
733 assert!(
734 !token.matches(&AuthToken::new("fixture-only-auth-token-9876543210".into()).unwrap())
735 );
736 assert!(AuthToken::new("private/invalid\nvalue".into()).is_err());
737 }
738 #[test]
739 fn future_minor_and_unknown_capability_do_not_grant_authority() {
740 let mut welcome: Welcome = serde_json::from_value(
741 serde_json::from_str::<Value>(include_str!("fixtures/control-v1.json")).unwrap()
742 ["welcome"]
743 .clone(),
744 )
745 .unwrap();
746 welcome.version.minor = u16::MAX;
747 welcome
748 .capabilities
749 .push(serde_json::from_str("\"future_capability\"").unwrap());
750 assert!(welcome.compatible(welcome.host_id));
751 assert!(!welcome.supports(Capability::Unknown));
752 welcome.version.major += 1;
753 assert!(!welcome.compatible(welcome.host_id));
754 assert!(!Limits {
755 max_frame_bytes: usize::MAX,
756 ..Limits::default()
757 }
758 .valid());
759 }
760 #[test]
761 fn administrative_queries_are_closed_bounded_and_never_claim_mutation_identity() {
762 let agent = AgentId::new();
763 let profile = ProfileRef {
764 agent_id: agent,
765 version: ProfileVersion::new(),
766 };
767 for action in [
768 AdministrativeAction::Create { agent_id: agent },
769 AdministrativeAction::Restore {
770 agent_id: agent,
771 revision: 1,
772 },
773 AdministrativeAction::CreateProfile { profile },
774 AdministrativeAction::RestoreProfile {
775 profile,
776 revision: 1,
777 },
778 AdministrativeAction::Cancel {
779 agent_id: agent,
780 revision: 1,
781 ticket_id: TicketId::new(),
782 },
783 AdministrativeAction::Close {
784 agent_id: agent,
785 revision: 1,
786 },
787 AdministrativeAction::Stop {},
788 ] {
789 let request = AdministrativeRequest {
790 scope: ControlScopeId::new(),
791 request_id: RequestId::new(),
792 epoch: Epoch::new(),
793 action,
794 };
795 let encoded = serde_json::to_value(&request).unwrap();
796 assert!(serde_json::to_vec(&request).unwrap().len() < 4096);
797 assert_eq!(
798 serde_json::from_value::<AdministrativeRequest>(encoded.clone()).unwrap(),
799 request
800 );
801 let command = Command::AdministrativeReceipt { request };
802 assert!(command.valid(Limits::default()));
803 assert_eq!(command.request_id(), None);
804 assert_eq!(command.capability(), Capability::AdministrativeReceipts);
805 let mut injected = encoded;
806 injected["action"]["grant"] = serde_json::json!({"stop": true});
807 assert!(serde_json::from_value::<AdministrativeRequest>(injected).is_err());
808 }
809 for limit in [0, MAX_PAGE_SIZE + 1, usize::MAX] {
810 assert!(!Command::Profiles { after: None, limit }.valid(Limits::default()));
811 }
812 assert_eq!(
813 Command::Profiles {
814 after: None,
815 limit: 1
816 }
817 .request_id(),
818 None
819 );
820 assert!(
821 serde_json::from_str::<ProfileVersion>("\"00000000-0000-0000-0000-000000000000\"")
822 .is_err()
823 );
824 }
825 #[test]
826 fn administrative_receipt_revision_limits_and_old_epoch_are_independent_from_transport() {
827 for revision in [0, i64::MAX as u64 + 1, u64::MAX] {
828 let request = AdministrativeRequest {
829 scope: ControlScopeId::new(),
830 request_id: RequestId::new(),
831 epoch: Epoch::new(),
832 action: AdministrativeAction::Close {
833 agent_id: AgentId::new(),
834 revision,
835 },
836 };
837 assert!(!request.valid());
838 }
839 let frames: Value = serde_json::from_str(include_str!("fixtures/control-v1.json")).unwrap();
840 let frame: Request = serde_json::from_value(
841 frames["requests"]
842 .as_array()
843 .unwrap()
844 .iter()
845 .find(|value| value["command"]["op"] == "administrative_receipt")
846 .expect("golden fixture carries the original historical query")
847 .clone(),
848 )
849 .unwrap();
850 let Command::AdministrativeReceipt { request } = frame.command else {
851 panic!("expected administrative query");
852 };
853 assert_ne!(frame.epoch, request.epoch);
854 assert!(request.valid());
855 }
856 #[test]
857 fn administrative_cancel_binds_stable_input_and_rejects_hybrid_or_unbounded_intents() {
858 let request = AdministrativeRequest {
859 scope: ControlScopeId::new(),
860 request_id: RequestId::new(),
861 epoch: Epoch::new(),
862 action: AdministrativeAction::CancelSubmitted {
863 agent_id: AgentId::new(),
864 revision: 1,
865 submitted_request_id: RequestId::new(),
866 },
867 };
868 let command = Command::AdministrativeCancel {
869 request: request.clone(),
870 };
871 assert!(command.valid(Limits::default()));
872 assert_eq!(command.request_id(), Some(request.request_id));
873 assert_eq!(command.capability(), Capability::AdministrativeCancel);
874 for revision in [0, i64::MAX as u64 + 1] {
875 let mut value = serde_json::to_value(&command).unwrap();
876 value["request"]["action"]["revision"] = serde_json::json!(revision);
877 assert!(!serde_json::from_value::<Command>(value)
878 .unwrap()
879 .valid(Limits::default()));
880 }
881 for case in 0..4 {
882 let mut value = serde_json::to_value(&command).unwrap();
883 match case {
884 0 => {
885 value["request"]["action"]["submitted_request_id"] =
886 serde_json::json!("00000000-0000-0000-0000-000000000000")
887 }
888 1 => value["request"]["action"]["ticket_id"] = serde_json::json!(TicketId::new()),
889 2 => value["request"]["grant"] = serde_json::json!({"cancel":true}),
890 _ => {
891 value["request"]["action"]
892 .as_object_mut()
893 .unwrap()
894 .remove("submitted_request_id");
895 }
896 }
897 assert!(serde_json::from_value::<Command>(value).is_err());
898 }
899 }
900 #[test]
901 fn administrative_stop_is_closed_complete_and_distinct_from_legacy_placeholder() {
902 let request = AdministrativeRequest {
903 scope: ControlScopeId::new(),
904 request_id: RequestId::new(),
905 epoch: Epoch::new(),
906 action: AdministrativeAction::Stop {},
907 };
908 let command = Command::AdministrativeStop {
909 request: request.clone(),
910 };
911 assert!(command.valid(Limits::default()));
912 assert_eq!(command.request_id(), Some(request.request_id));
913 assert_eq!(command.capability(), Capability::AdministrativeStop);
914 let original = serde_json::to_value(&command).unwrap();
915 for field in ["scope", "request_id", "epoch", "action"] {
916 let mut value = original.clone();
917 value["request"].as_object_mut().unwrap().remove(field);
918 assert!(serde_json::from_value::<Command>(value).is_err());
919 }
920 for field in ["scope", "request_id", "epoch"] {
921 let mut value = original.clone();
922 value["request"][field] = serde_json::json!("00000000-0000-0000-0000-000000000000");
923 assert!(serde_json::from_value::<Command>(value).is_err());
924 }
925 for field in ["agent_id", "revision", "grant", "ticket_id"] {
926 let mut value = original.clone();
927 value["request"]["action"][field] = serde_json::json!(1);
928 assert!(serde_json::from_value::<Command>(value).is_err());
929 }
930 let legacy = Command::Stop {
931 request_id: request.request_id,
932 };
933 assert_eq!(legacy.capability(), Capability::Stop);
934 assert_ne!(legacy.capability(), command.capability());
935 }
936 #[test]
937 fn administrative_execution_commands_match_exact_intent_and_keep_mutation_identity() {
938 let agent_id = AgentId::new();
939 let profile = ProfileRef {
940 agent_id,
941 version: ProfileVersion::new(),
942 };
943 let actions = [
944 AdministrativeAction::Create { agent_id },
945 AdministrativeAction::Restore {
946 agent_id,
947 revision: 1,
948 },
949 AdministrativeAction::CreateProfile { profile },
950 AdministrativeAction::RestoreProfile {
951 profile,
952 revision: 1,
953 },
954 AdministrativeAction::Cancel {
955 agent_id,
956 revision: 1,
957 ticket_id: TicketId::new(),
958 },
959 AdministrativeAction::Close {
960 agent_id,
961 revision: 1,
962 },
963 AdministrativeAction::Stop {},
964 AdministrativeAction::CancelSubmitted {
965 agent_id,
966 revision: 1,
967 submitted_request_id: RequestId::new(),
968 },
969 ];
970 type Constructor = fn(AdministrativeRequest) -> Command;
971 let constructors: [(Constructor, Capability, usize); 5] = [
972 (
973 |request| Command::AdministrativeCreate { request },
974 Capability::AdministrativeCreate,
975 2,
976 ),
977 (
978 |request| Command::AdministrativeRestore { request },
979 Capability::AdministrativeRestore,
980 3,
981 ),
982 (
983 |request| Command::AdministrativeClose { request },
984 Capability::AdministrativeClose,
985 5,
986 ),
987 (
988 |request| Command::AdministrativeCancel { request },
989 Capability::AdministrativeCancel,
990 7,
991 ),
992 (
993 |request| Command::AdministrativeStop { request },
994 Capability::AdministrativeStop,
995 6,
996 ),
997 ];
998 for (make, capability, allowed) in constructors {
999 for (index, action) in actions.iter().enumerate() {
1000 let request = AdministrativeRequest {
1001 scope: ControlScopeId::new(),
1002 request_id: RequestId::new(),
1003 epoch: Epoch::new(),
1004 action: action.clone(),
1005 };
1006 let id = request.request_id;
1007 let command = make(request);
1008 assert_eq!(command.capability(), capability);
1009 assert_eq!(command.request_id(), Some(id));
1010 assert_eq!(command.valid(Limits::default()), index == allowed);
1011 let mut value = serde_json::to_value(command).unwrap();
1012 value["request"]["grant"] = serde_json::json!({"create": true});
1013 assert!(serde_json::from_value::<Command>(value).is_err());
1014 }
1015 }
1016 }
1017}