1use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18#[derive(Deserialize)]
22#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
23enum ScopePrincipal {
24 Reserved { module_id: String },
25 Direct {},
26 Unverified {},
27}
28
29impl From<ScopePrincipal> for Principal {
30 fn from(value: ScopePrincipal) -> Self {
31 match value {
32 ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
33 ScopePrincipal::Direct {} => Self::Direct,
34 ScopePrincipal::Unverified {} => Self::Unverified,
35 }
36 }
37}
38
39fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
40 deserializer: D,
41) -> Result<Principal, D::Error> {
42 ScopePrincipal::deserialize(deserializer).map(Into::into)
43}
44
45fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
46 deserializer: D,
47) -> Result<Vec<Principal>, D::Error> {
48 Vec::<ScopePrincipal>::deserialize(deserializer)
49 .map(|principals| principals.into_iter().map(Into::into).collect())
50}
51
52pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
54 if hash.len() == 64
55 && hash
56 .bytes()
57 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
58 {
59 Ok(())
60 } else {
61 Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
62 }
63}
64
65fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
66 deserializer: D,
67) -> Result<Option<String>, D::Error> {
68 let hash = Option::<String>::deserialize(deserializer)?;
69 if let Some(hash) = &hash {
70 validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
71 }
72 Ok(hash)
73}
74
75pub const CAP_SCOPES_V1: &str = "scopes/v1";
79
80pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
85
86pub const SCOPE_SYNC_OP: &str = "scope.sync";
88pub const SCOPE_APPLY_OP: &str = "scope.apply";
91pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
93
94pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
96pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
99pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
102pub const MAX_CARRIER_TARGETS: usize = 16;
104pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
107
108#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
111#[serde(rename_all = "snake_case")]
112pub enum ScopeKind {
113 Head,
114 Worker,
115 Ephemeral,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
121#[serde(deny_unknown_fields)]
122#[non_exhaustive]
123pub struct ScopeParent {
124 #[serde(deserialize_with = "deserialize_scope_principal")]
125 pub owner: Principal,
126 #[serde(rename = "ref")]
127 pub scope_ref: String,
128 pub scope_epoch: u64,
129}
130
131impl ScopeParent {
132 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
133 Self {
134 owner,
135 scope_ref: scope_ref.into(),
136 scope_epoch,
137 }
138 }
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
148#[serde(deny_unknown_fields)]
149#[non_exhaustive]
150pub struct ScopeCarrier {
151 #[serde(deserialize_with = "deserialize_scope_principal")]
152 pub principal: Principal,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub targets: Option<Vec<String>>,
155}
156
157impl ScopeCarrier {
158 pub fn new(principal: Principal) -> Self {
159 Self {
160 principal,
161 targets: None,
162 }
163 }
164
165 #[must_use]
166 pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
167 self.targets = targets;
168 self
169 }
170}
171
172pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
178
179pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
185
186pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
190
191pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
193
194#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
200#[serde(deny_unknown_fields)]
201#[non_exhaustive]
202pub struct ScopeAttributes {
203 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub agent_id: Option<String>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub on_behalf_of_agent: Option<String>,
221 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
223 pub delegates: bool,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub flow_id: Option<String>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub run_id: Option<String>,
252}
253
254impl ScopeAttributes {
255 pub fn new() -> Self {
256 Self::default()
257 }
258
259 #[must_use]
260 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
261 self.agent_id = agent_id;
262 self
263 }
264
265 #[must_use]
266 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
267 self.on_behalf_of_agent = on_behalf_of_agent;
268 self
269 }
270
271 #[must_use]
272 pub fn with_delegates(mut self, delegates: bool) -> Self {
273 self.delegates = delegates;
274 self
275 }
276
277 #[must_use]
278 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
279 self.flow_id = flow_id;
280 self
281 }
282
283 #[must_use]
284 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
285 self.run_id = run_id;
286 self
287 }
288
289 pub fn is_empty(&self) -> bool {
290 self.agent_id.is_none()
291 && self.on_behalf_of_agent.is_none()
292 && !self.delegates
293 && self.flow_id.is_none()
294 && self.run_id.is_none()
295 }
296}
297
298pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
302 crate::tool_call::validate_opaque_field("flow_id", flow_id)
303}
304
305pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
308 crate::tool_call::validate_opaque_field("run_id", run_id)
309}
310
311pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
314 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
315}
316
317pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
319
320pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
322 if value.is_empty() || value.len() > 128 {
323 return Err("project_id must contain 1 to 128 bytes");
324 }
325 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
326 return Err("project_id must be printable ASCII without whitespace");
327 }
328 Ok(())
329}
330
331#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
333#[serde(deny_unknown_fields)]
334#[non_exhaustive]
335pub struct ScopeRecord {
336 #[serde(rename = "ref")]
337 pub scope_ref: String,
338 pub scope_epoch: u64,
342 pub kind: ScopeKind,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub workdir: Option<String>,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub project_id: Option<String>,
350 #[serde(
353 default,
354 skip_serializing_if = "Option::is_none",
355 deserialize_with = "deserialize_bind_proof_sha256"
356 )]
357 pub bind_proof_sha256: Option<String>,
358 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
363 pub replace_only_if_idle: bool,
364 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub expires_at_ms: Option<u64>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub parent: Option<ScopeParent>,
371 #[serde(
374 default,
375 skip_serializing_if = "Vec::is_empty",
376 deserialize_with = "deserialize_scope_principals"
377 )]
378 pub child_owners: Vec<Principal>,
379 #[serde(default, skip_serializing_if = "Vec::is_empty")]
380 pub carriers: Vec<ScopeCarrier>,
381 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
382 pub attributes: ScopeAttributes,
383}
384
385impl ScopeRecord {
386 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
387 Self {
388 scope_ref: scope_ref.into(),
389 scope_epoch,
390 kind,
391 workdir: None,
392 project_id: None,
393 bind_proof_sha256: None,
394 replace_only_if_idle: false,
395 expires_at_ms: None,
396 parent: None,
397 child_owners: Vec::new(),
398 carriers: Vec::new(),
399 attributes: ScopeAttributes::default(),
400 }
401 }
402
403 #[must_use]
404 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
405 self.workdir = workdir;
406 self
407 }
408
409 #[must_use]
410 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
411 self.project_id = project_id;
412 self
413 }
414
415 #[must_use]
416 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
417 self.bind_proof_sha256 = hash;
418 self
419 }
420
421 #[must_use]
422 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
423 self.replace_only_if_idle = replace_only_if_idle;
424 self
425 }
426
427 #[must_use]
428 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
429 self.expires_at_ms = expires_at_ms;
430 self
431 }
432
433 #[must_use]
434 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
435 self.parent = parent;
436 self
437 }
438
439 #[must_use]
440 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
441 self.child_owners = child_owners;
442 self
443 }
444
445 #[must_use]
446 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
447 self.carriers = carriers;
448 self
449 }
450
451 #[must_use]
452 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
453 self.attributes = attributes;
454 self
455 }
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
460#[serde(deny_unknown_fields)]
461#[non_exhaustive]
462pub struct ScopeEnd {
463 #[serde(rename = "ref")]
464 pub scope_ref: String,
465 pub scope_epoch: u64,
466}
467
468impl ScopeEnd {
469 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
470 Self {
471 scope_ref: scope_ref.into(),
472 scope_epoch,
473 }
474 }
475}
476
477#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
479#[serde(rename_all = "snake_case")]
480pub enum ScopeEndOutcome {
481 Ended,
483 NotLive,
486}
487
488#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
490#[serde(deny_unknown_fields)]
491#[non_exhaustive]
492pub struct ScopeEndResult {
493 #[serde(rename = "ref")]
494 pub scope_ref: String,
495 pub scope_epoch: u64,
496 pub outcome: ScopeEndOutcome,
497}
498
499impl ScopeEndResult {
500 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
501 Self {
502 scope_ref: scope_ref.into(),
503 scope_epoch,
504 outcome,
505 }
506 }
507}
508
509#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
515#[serde(deny_unknown_fields)]
516#[non_exhaustive]
517pub struct ScopeSelector {
518 #[serde(deserialize_with = "deserialize_scope_principal")]
519 pub owner: Principal,
520 #[serde(rename = "ref")]
521 pub scope_ref: String,
522 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub scope_epoch: Option<u64>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub bind_proof: Option<String>,
528 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
531 pub hold_presence: bool,
532}
533
534impl ScopeSelector {
535 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
536 Self {
537 owner,
538 scope_ref: scope_ref.into(),
539 scope_epoch,
540 bind_proof: None,
541 hold_presence: false,
542 }
543 }
544
545 #[must_use]
546 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
547 self.bind_proof = proof;
548 self
549 }
550
551 #[must_use]
552 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
553 self.hold_presence = hold_presence;
554 self
555 }
556}
557
558impl std::fmt::Debug for ScopeSelector {
559 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560 f.debug_struct("ScopeSelector")
561 .field("owner", &self.owner)
562 .field("scope_ref", &self.scope_ref)
563 .field("scope_epoch", &self.scope_epoch)
564 .field(
565 "bind_proof",
566 &self.bind_proof.as_ref().map(|_| "<redacted>"),
567 )
568 .finish()
569 }
570}
571
572impl std::fmt::Display for ScopeSelector {
573 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574 std::fmt::Debug::fmt(self, f)
575 }
576}
577
578#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
580#[serde(rename_all = "snake_case")]
581pub enum ParentState {
582 Linked,
584 Pending,
587 Ended,
590}
591
592#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
594#[serde(rename_all = "snake_case")]
595pub enum ScopeRecordOutcome {
596 Created,
598 Replaced,
600 Updated,
602 Unchanged,
605 Refused,
608}
609
610#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
612pub struct ScopeRecordResult {
613 #[serde(rename = "ref")]
614 pub scope_ref: String,
615 pub scope_epoch: u64,
618 pub outcome: ScopeRecordOutcome,
619 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub code: Option<String>,
622 #[serde(default, skip_serializing_if = "Option::is_none")]
623 pub message: Option<String>,
624 #[serde(default, skip_serializing_if = "Option::is_none")]
627 pub version: Option<u64>,
628 #[serde(default, skip_serializing_if = "Option::is_none")]
630 pub parent_state: Option<ParentState>,
631}
632
633#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
637pub struct ScopeEnded {
638 #[serde(rename = "ref")]
639 pub scope_ref: String,
640 pub scope_epoch: u64,
641}
642
643#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
645#[serde(rename_all = "snake_case")]
646pub enum ScopeStatus {
647 Live,
648 Ended,
650 NotLive,
656}
657
658#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
661#[non_exhaustive]
662pub struct ScopeStamp {
663 pub owner: Principal,
664 #[serde(rename = "ref")]
665 pub scope_ref: String,
666 pub scope_epoch: u64,
667 pub kind: ScopeKind,
668 #[serde(default, skip_serializing_if = "Option::is_none")]
671 pub workdir: Option<String>,
672 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub project_id: Option<String>,
675 #[serde(default, skip_serializing_if = "Option::is_none")]
676 pub parent: Option<ScopeParent>,
677 #[serde(default, skip_serializing_if = "Option::is_none")]
678 pub parent_state: Option<ParentState>,
679 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
680 pub attributes: ScopeAttributes,
681 pub owner_authorized: bool,
684 #[serde(default, skip_serializing_if = "Option::is_none")]
689 pub expires_at_ms: Option<u64>,
690}
691
692impl ScopeStamp {
693 pub fn new(
695 owner: Principal,
696 scope_ref: impl Into<String>,
697 scope_epoch: u64,
698 kind: ScopeKind,
699 ) -> Self {
700 Self {
701 owner,
702 scope_ref: scope_ref.into(),
703 scope_epoch,
704 kind,
705 workdir: None,
706 project_id: None,
707 parent: None,
708 parent_state: None,
709 attributes: ScopeAttributes::new(),
710 owner_authorized: false,
711 expires_at_ms: None,
712 }
713 }
714
715 #[must_use]
716 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
717 self.workdir = workdir;
718 self
719 }
720
721 #[must_use]
722 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
723 self.project_id = project_id;
724 self
725 }
726
727 #[must_use]
728 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
729 self.parent = parent;
730 self
731 }
732
733 #[must_use]
734 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
735 self.parent_state = parent_state;
736 self
737 }
738
739 #[must_use]
740 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
741 self.attributes = attributes;
742 self
743 }
744
745 #[must_use]
746 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
747 self.owner_authorized = owner_authorized;
748 self
749 }
750
751 #[must_use]
752 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
753 self.expires_at_ms = expires_at_ms;
754 self
755 }
756}
757
758#[cfg(test)]
759mod tests {
760 use super::*;
761 use crate::tool_call::OpaqueFieldError;
762
763 #[test]
764 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
765 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
766 assert_eq!(validate_project_id(valid), Ok(()));
767 }
768 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
769 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
770 }
771 }
772
773 #[test]
774 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
775 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
776 assert_eq!(
777 serde_json::to_string(&record).unwrap(),
778 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
779 );
780 let record = record
781 .with_workdir(Some("/folder".into()))
782 .with_project_id(Some("project:1".into()));
783 let encoded = serde_json::to_string(&record).unwrap();
784 assert_eq!(
785 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
786 record
787 );
788 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
789 assert_eq!(
790 serde_json::to_string(&stamp).unwrap(),
791 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
792 );
793 let stamp = stamp
794 .with_workdir(record.workdir)
795 .with_project_id(record.project_id);
796 let encoded = serde_json::to_string(&stamp).unwrap();
797 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
798 }
799
800 #[test]
801 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
802 let field = "flow_id";
803 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
804 assert_eq!(validate_flow_id("f"), Ok(()));
805 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
806 assert_eq!(
807 validate_flow_id(&"f".repeat(257)),
808 Err(OpaqueFieldError::TooLong { field, length: 257 })
809 );
810 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
811 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
812 let error = validate_flow_id(bad).unwrap_err();
813 assert_eq!(
814 error,
815 OpaqueFieldError::InvalidCharacter { field, index: 1 }
816 );
817 assert_eq!(error.field(), "flow_id");
818 }
819 }
820
821 #[test]
822 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
823 let attributes = ScopeAttributes::default();
824 assert!(attributes.is_empty());
825 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
826 assert_eq!(
827 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
828 attributes
829 );
830 let attributes = ScopeAttributes {
831 flow_id: Some("flow:7".to_string()),
832 ..ScopeAttributes::default()
833 };
834 assert!(!attributes.is_empty());
835 let encoded = serde_json::to_string(&attributes).unwrap();
836 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
837 assert_eq!(
838 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
839 attributes
840 );
841 assert!(
842 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
843 .is_err()
844 );
845 }
846}