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
317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
319#[serde(deny_unknown_fields)]
320#[non_exhaustive]
321pub struct ScopeRecord {
322 #[serde(rename = "ref")]
323 pub scope_ref: String,
324 pub scope_epoch: u64,
328 pub kind: ScopeKind,
329 #[serde(
332 default,
333 skip_serializing_if = "Option::is_none",
334 deserialize_with = "deserialize_bind_proof_sha256"
335 )]
336 pub bind_proof_sha256: Option<String>,
337 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
342 pub replace_only_if_idle: bool,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub expires_at_ms: Option<u64>,
348 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub parent: Option<ScopeParent>,
350 #[serde(
353 default,
354 skip_serializing_if = "Vec::is_empty",
355 deserialize_with = "deserialize_scope_principals"
356 )]
357 pub child_owners: Vec<Principal>,
358 #[serde(default, skip_serializing_if = "Vec::is_empty")]
359 pub carriers: Vec<ScopeCarrier>,
360 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
361 pub attributes: ScopeAttributes,
362}
363
364impl ScopeRecord {
365 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
366 Self {
367 scope_ref: scope_ref.into(),
368 scope_epoch,
369 kind,
370 bind_proof_sha256: None,
371 replace_only_if_idle: false,
372 expires_at_ms: None,
373 parent: None,
374 child_owners: Vec::new(),
375 carriers: Vec::new(),
376 attributes: ScopeAttributes::default(),
377 }
378 }
379
380 #[must_use]
381 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
382 self.bind_proof_sha256 = hash;
383 self
384 }
385
386 #[must_use]
387 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
388 self.replace_only_if_idle = replace_only_if_idle;
389 self
390 }
391
392 #[must_use]
393 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
394 self.expires_at_ms = expires_at_ms;
395 self
396 }
397
398 #[must_use]
399 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
400 self.parent = parent;
401 self
402 }
403
404 #[must_use]
405 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
406 self.child_owners = child_owners;
407 self
408 }
409
410 #[must_use]
411 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
412 self.carriers = carriers;
413 self
414 }
415
416 #[must_use]
417 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
418 self.attributes = attributes;
419 self
420 }
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
425#[serde(deny_unknown_fields)]
426#[non_exhaustive]
427pub struct ScopeEnd {
428 #[serde(rename = "ref")]
429 pub scope_ref: String,
430 pub scope_epoch: u64,
431}
432
433impl ScopeEnd {
434 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
435 Self {
436 scope_ref: scope_ref.into(),
437 scope_epoch,
438 }
439 }
440}
441
442#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
444#[serde(rename_all = "snake_case")]
445pub enum ScopeEndOutcome {
446 Ended,
448 NotLive,
451}
452
453#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
455#[serde(deny_unknown_fields)]
456#[non_exhaustive]
457pub struct ScopeEndResult {
458 #[serde(rename = "ref")]
459 pub scope_ref: String,
460 pub scope_epoch: u64,
461 pub outcome: ScopeEndOutcome,
462}
463
464impl ScopeEndResult {
465 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
466 Self {
467 scope_ref: scope_ref.into(),
468 scope_epoch,
469 outcome,
470 }
471 }
472}
473
474#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
480#[serde(deny_unknown_fields)]
481#[non_exhaustive]
482pub struct ScopeSelector {
483 #[serde(deserialize_with = "deserialize_scope_principal")]
484 pub owner: Principal,
485 #[serde(rename = "ref")]
486 pub scope_ref: String,
487 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub scope_epoch: Option<u64>,
489 #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub bind_proof: Option<String>,
493 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
496 pub hold_presence: bool,
497}
498
499impl ScopeSelector {
500 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
501 Self {
502 owner,
503 scope_ref: scope_ref.into(),
504 scope_epoch,
505 bind_proof: None,
506 hold_presence: false,
507 }
508 }
509
510 #[must_use]
511 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
512 self.bind_proof = proof;
513 self
514 }
515
516 #[must_use]
517 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
518 self.hold_presence = hold_presence;
519 self
520 }
521}
522
523impl std::fmt::Debug for ScopeSelector {
524 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
525 f.debug_struct("ScopeSelector")
526 .field("owner", &self.owner)
527 .field("scope_ref", &self.scope_ref)
528 .field("scope_epoch", &self.scope_epoch)
529 .field(
530 "bind_proof",
531 &self.bind_proof.as_ref().map(|_| "<redacted>"),
532 )
533 .finish()
534 }
535}
536
537impl std::fmt::Display for ScopeSelector {
538 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539 std::fmt::Debug::fmt(self, f)
540 }
541}
542
543#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
545#[serde(rename_all = "snake_case")]
546pub enum ParentState {
547 Linked,
549 Pending,
552 Ended,
555}
556
557#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
559#[serde(rename_all = "snake_case")]
560pub enum ScopeRecordOutcome {
561 Created,
563 Replaced,
565 Updated,
567 Unchanged,
570 Refused,
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
577pub struct ScopeRecordResult {
578 #[serde(rename = "ref")]
579 pub scope_ref: String,
580 pub scope_epoch: u64,
583 pub outcome: ScopeRecordOutcome,
584 #[serde(default, skip_serializing_if = "Option::is_none")]
586 pub code: Option<String>,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub message: Option<String>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub version: Option<u64>,
593 #[serde(default, skip_serializing_if = "Option::is_none")]
595 pub parent_state: Option<ParentState>,
596}
597
598#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
602pub struct ScopeEnded {
603 #[serde(rename = "ref")]
604 pub scope_ref: String,
605 pub scope_epoch: u64,
606}
607
608#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
610#[serde(rename_all = "snake_case")]
611pub enum ScopeStatus {
612 Live,
613 Ended,
615 NotLive,
621}
622
623#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
626#[non_exhaustive]
627pub struct ScopeStamp {
628 pub owner: Principal,
629 #[serde(rename = "ref")]
630 pub scope_ref: String,
631 pub scope_epoch: u64,
632 pub kind: ScopeKind,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
634 pub parent: Option<ScopeParent>,
635 #[serde(default, skip_serializing_if = "Option::is_none")]
636 pub parent_state: Option<ParentState>,
637 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
638 pub attributes: ScopeAttributes,
639 pub owner_authorized: bool,
642 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub expires_at_ms: Option<u64>,
648}
649
650impl ScopeStamp {
651 pub fn new(
653 owner: Principal,
654 scope_ref: impl Into<String>,
655 scope_epoch: u64,
656 kind: ScopeKind,
657 ) -> Self {
658 Self {
659 owner,
660 scope_ref: scope_ref.into(),
661 scope_epoch,
662 kind,
663 parent: None,
664 parent_state: None,
665 attributes: ScopeAttributes::new(),
666 owner_authorized: false,
667 expires_at_ms: None,
668 }
669 }
670
671 #[must_use]
672 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
673 self.parent = parent;
674 self
675 }
676
677 #[must_use]
678 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
679 self.parent_state = parent_state;
680 self
681 }
682
683 #[must_use]
684 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
685 self.attributes = attributes;
686 self
687 }
688
689 #[must_use]
690 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
691 self.owner_authorized = owner_authorized;
692 self
693 }
694
695 #[must_use]
696 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
697 self.expires_at_ms = expires_at_ms;
698 self
699 }
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705 use crate::tool_call::OpaqueFieldError;
706
707 #[test]
708 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
709 let field = "flow_id";
710 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
711 assert_eq!(validate_flow_id("f"), Ok(()));
712 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
713 assert_eq!(
714 validate_flow_id(&"f".repeat(257)),
715 Err(OpaqueFieldError::TooLong { field, length: 257 })
716 );
717 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
718 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
719 let error = validate_flow_id(bad).unwrap_err();
720 assert_eq!(
721 error,
722 OpaqueFieldError::InvalidCharacter { field, index: 1 }
723 );
724 assert_eq!(error.field(), "flow_id");
725 }
726 }
727
728 #[test]
729 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
730 let attributes = ScopeAttributes::default();
731 assert!(attributes.is_empty());
732 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
733 assert_eq!(
734 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
735 attributes
736 );
737 let attributes = ScopeAttributes {
738 flow_id: Some("flow:7".to_string()),
739 ..ScopeAttributes::default()
740 };
741 assert!(!attributes.is_empty());
742 let encoded = serde_json::to_string(&attributes).unwrap();
743 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
744 assert_eq!(
745 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
746 attributes
747 );
748 assert!(
749 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
750 .is_err()
751 );
752 }
753}