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
191#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
197#[serde(deny_unknown_fields)]
198#[non_exhaustive]
199pub struct ScopeAttributes {
200 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub agent_id: Option<String>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub on_behalf_of_agent: Option<String>,
218 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220 pub delegates: bool,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub flow_id: Option<String>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub run_id: Option<String>,
249}
250
251impl ScopeAttributes {
252 pub fn new() -> Self {
253 Self::default()
254 }
255
256 #[must_use]
257 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
258 self.agent_id = agent_id;
259 self
260 }
261
262 #[must_use]
263 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
264 self.on_behalf_of_agent = on_behalf_of_agent;
265 self
266 }
267
268 #[must_use]
269 pub fn with_delegates(mut self, delegates: bool) -> Self {
270 self.delegates = delegates;
271 self
272 }
273
274 #[must_use]
275 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
276 self.flow_id = flow_id;
277 self
278 }
279
280 #[must_use]
281 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
282 self.run_id = run_id;
283 self
284 }
285
286 pub fn is_empty(&self) -> bool {
287 self.agent_id.is_none()
288 && self.on_behalf_of_agent.is_none()
289 && !self.delegates
290 && self.flow_id.is_none()
291 && self.run_id.is_none()
292 }
293}
294
295pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
299 crate::tool_call::validate_opaque_field("flow_id", flow_id)
300}
301
302pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
305 crate::tool_call::validate_opaque_field("run_id", run_id)
306}
307
308pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
311 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
316#[serde(deny_unknown_fields)]
317#[non_exhaustive]
318pub struct ScopeRecord {
319 #[serde(rename = "ref")]
320 pub scope_ref: String,
321 pub scope_epoch: u64,
325 pub kind: ScopeKind,
326 #[serde(
329 default,
330 skip_serializing_if = "Option::is_none",
331 deserialize_with = "deserialize_bind_proof_sha256"
332 )]
333 pub bind_proof_sha256: Option<String>,
334 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
339 pub replace_only_if_idle: bool,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub expires_at_ms: Option<u64>,
345 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub parent: Option<ScopeParent>,
347 #[serde(
350 default,
351 skip_serializing_if = "Vec::is_empty",
352 deserialize_with = "deserialize_scope_principals"
353 )]
354 pub child_owners: Vec<Principal>,
355 #[serde(default, skip_serializing_if = "Vec::is_empty")]
356 pub carriers: Vec<ScopeCarrier>,
357 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
358 pub attributes: ScopeAttributes,
359}
360
361impl ScopeRecord {
362 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
363 Self {
364 scope_ref: scope_ref.into(),
365 scope_epoch,
366 kind,
367 bind_proof_sha256: None,
368 replace_only_if_idle: false,
369 expires_at_ms: None,
370 parent: None,
371 child_owners: Vec::new(),
372 carriers: Vec::new(),
373 attributes: ScopeAttributes::default(),
374 }
375 }
376
377 #[must_use]
378 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
379 self.bind_proof_sha256 = hash;
380 self
381 }
382
383 #[must_use]
384 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
385 self.replace_only_if_idle = replace_only_if_idle;
386 self
387 }
388
389 #[must_use]
390 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
391 self.expires_at_ms = expires_at_ms;
392 self
393 }
394
395 #[must_use]
396 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
397 self.parent = parent;
398 self
399 }
400
401 #[must_use]
402 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
403 self.child_owners = child_owners;
404 self
405 }
406
407 #[must_use]
408 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
409 self.carriers = carriers;
410 self
411 }
412
413 #[must_use]
414 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
415 self.attributes = attributes;
416 self
417 }
418}
419
420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
422#[serde(deny_unknown_fields)]
423#[non_exhaustive]
424pub struct ScopeEnd {
425 #[serde(rename = "ref")]
426 pub scope_ref: String,
427 pub scope_epoch: u64,
428}
429
430impl ScopeEnd {
431 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
432 Self {
433 scope_ref: scope_ref.into(),
434 scope_epoch,
435 }
436 }
437}
438
439#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
441#[serde(rename_all = "snake_case")]
442pub enum ScopeEndOutcome {
443 Ended,
445 NotLive,
448}
449
450#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
452#[serde(deny_unknown_fields)]
453#[non_exhaustive]
454pub struct ScopeEndResult {
455 #[serde(rename = "ref")]
456 pub scope_ref: String,
457 pub scope_epoch: u64,
458 pub outcome: ScopeEndOutcome,
459}
460
461impl ScopeEndResult {
462 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
463 Self {
464 scope_ref: scope_ref.into(),
465 scope_epoch,
466 outcome,
467 }
468 }
469}
470
471#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
477#[serde(deny_unknown_fields)]
478#[non_exhaustive]
479pub struct ScopeSelector {
480 #[serde(deserialize_with = "deserialize_scope_principal")]
481 pub owner: Principal,
482 #[serde(rename = "ref")]
483 pub scope_ref: String,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub scope_epoch: Option<u64>,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub bind_proof: Option<String>,
490 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
493 pub hold_presence: bool,
494}
495
496impl ScopeSelector {
497 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
498 Self {
499 owner,
500 scope_ref: scope_ref.into(),
501 scope_epoch,
502 bind_proof: None,
503 hold_presence: false,
504 }
505 }
506
507 #[must_use]
508 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
509 self.bind_proof = proof;
510 self
511 }
512
513 #[must_use]
514 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
515 self.hold_presence = hold_presence;
516 self
517 }
518}
519
520impl std::fmt::Debug for ScopeSelector {
521 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522 f.debug_struct("ScopeSelector")
523 .field("owner", &self.owner)
524 .field("scope_ref", &self.scope_ref)
525 .field("scope_epoch", &self.scope_epoch)
526 .field(
527 "bind_proof",
528 &self.bind_proof.as_ref().map(|_| "<redacted>"),
529 )
530 .finish()
531 }
532}
533
534impl std::fmt::Display for ScopeSelector {
535 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
536 std::fmt::Debug::fmt(self, f)
537 }
538}
539
540#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
542#[serde(rename_all = "snake_case")]
543pub enum ParentState {
544 Linked,
546 Pending,
549 Ended,
552}
553
554#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
556#[serde(rename_all = "snake_case")]
557pub enum ScopeRecordOutcome {
558 Created,
560 Replaced,
562 Updated,
564 Unchanged,
567 Refused,
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
574pub struct ScopeRecordResult {
575 #[serde(rename = "ref")]
576 pub scope_ref: String,
577 pub scope_epoch: u64,
580 pub outcome: ScopeRecordOutcome,
581 #[serde(default, skip_serializing_if = "Option::is_none")]
583 pub code: Option<String>,
584 #[serde(default, skip_serializing_if = "Option::is_none")]
585 pub message: Option<String>,
586 #[serde(default, skip_serializing_if = "Option::is_none")]
589 pub version: Option<u64>,
590 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub parent_state: Option<ParentState>,
593}
594
595#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
599pub struct ScopeEnded {
600 #[serde(rename = "ref")]
601 pub scope_ref: String,
602 pub scope_epoch: u64,
603}
604
605#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
607#[serde(rename_all = "snake_case")]
608pub enum ScopeStatus {
609 Live,
610 Ended,
612 NotLive,
618}
619
620#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
623#[non_exhaustive]
624pub struct ScopeStamp {
625 pub owner: Principal,
626 #[serde(rename = "ref")]
627 pub scope_ref: String,
628 pub scope_epoch: u64,
629 pub kind: ScopeKind,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub parent: Option<ScopeParent>,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub parent_state: Option<ParentState>,
634 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
635 pub attributes: ScopeAttributes,
636 pub owner_authorized: bool,
639 #[serde(default, skip_serializing_if = "Option::is_none")]
644 pub expires_at_ms: Option<u64>,
645}
646
647impl ScopeStamp {
648 pub fn new(
650 owner: Principal,
651 scope_ref: impl Into<String>,
652 scope_epoch: u64,
653 kind: ScopeKind,
654 ) -> Self {
655 Self {
656 owner,
657 scope_ref: scope_ref.into(),
658 scope_epoch,
659 kind,
660 parent: None,
661 parent_state: None,
662 attributes: ScopeAttributes::new(),
663 owner_authorized: false,
664 expires_at_ms: None,
665 }
666 }
667
668 #[must_use]
669 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
670 self.parent = parent;
671 self
672 }
673
674 #[must_use]
675 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
676 self.parent_state = parent_state;
677 self
678 }
679
680 #[must_use]
681 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
682 self.attributes = attributes;
683 self
684 }
685
686 #[must_use]
687 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
688 self.owner_authorized = owner_authorized;
689 self
690 }
691
692 #[must_use]
693 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
694 self.expires_at_ms = expires_at_ms;
695 self
696 }
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702 use crate::tool_call::OpaqueFieldError;
703
704 #[test]
705 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
706 let field = "flow_id";
707 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
708 assert_eq!(validate_flow_id("f"), Ok(()));
709 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
710 assert_eq!(
711 validate_flow_id(&"f".repeat(257)),
712 Err(OpaqueFieldError::TooLong { field, length: 257 })
713 );
714 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
715 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
716 let error = validate_flow_id(bad).unwrap_err();
717 assert_eq!(
718 error,
719 OpaqueFieldError::InvalidCharacter { field, index: 1 }
720 );
721 assert_eq!(error.field(), "flow_id");
722 }
723 }
724
725 #[test]
726 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
727 let attributes = ScopeAttributes::default();
728 assert!(attributes.is_empty());
729 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
730 assert_eq!(
731 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
732 attributes
733 );
734 let attributes = ScopeAttributes {
735 flow_id: Some("flow:7".to_string()),
736 ..ScopeAttributes::default()
737 };
738 assert!(!attributes.is_empty());
739 let encoded = serde_json::to_string(&attributes).unwrap();
740 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
741 assert_eq!(
742 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
743 attributes
744 );
745 assert!(
746 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
747 .is_err()
748 );
749 }
750}