Skip to main content

subc_protocol/
scope.rs

1//! Scope records: owned identity records the daemon holds for sessions.
2//!
3//! A scope is identified by `(owner, ref)`. The owner is the module whose own
4//! registered connection synced it, never a value in the request, and the
5//! `ref` is an opaque string unique within that owner only. The design is
6//! `docs/designs/daemon-scopes.md`; the wire shapes here are the owner-facing
7//! half of it (`scope.sync`, `scope.apply`, `scope.describe`).
8//!
9//! Every record type refuses unknown fields. A field this daemon does not know
10//! may be one that narrows authority in a later version (a carrier's target
11//! list, say), and silently dropping it would widen what the scope grants, so
12//! an owner sending one is told its body is malformed instead.
13
14use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18// Scope principals are authority-bearing input: an unrecognized constraint must
19// not silently widen a grant. Principal elsewhere is a forward-compatible caller
20// fact, so keep its general decoder lenient and enforce this only on scope input.
21#[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
52/// A scope bind-proof hash is the lowercase hexadecimal SHA-256 digest.
53pub 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
75/// The `server.describe` capability a daemon advertises when it admits routes
76/// under scopes. A carrier that needs a scoped route and does not see it fails
77/// the call (`scope_unsupported`) instead of opening an unscoped route.
78pub const CAP_SCOPES_V1: &str = "scopes/v1";
79
80/// The `server.describe` capability a daemon advertises when it checks a
81/// `route.open`'s `role_versions` and forwards them on the module's bind. A
82/// daemon without it drops the field silently, so a consumer that relies on
83/// the provider seeing its role versions checks for this first.
84pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
85
86/// Module-to-subc op that registers an owner's full scope set.
87pub const SCOPE_SYNC_OP: &str = "scope.sync";
88/// Module-to-subc op that upserts or ends scopes without replacing the owner's
89/// full scope set.
90pub const SCOPE_APPLY_OP: &str = "scope.apply";
91/// Module-to-subc op that reads one scope's current state.
92pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
93
94/// Most live scopes one owner may hold. A sync naming more is refused whole.
95pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
96/// Most bytes one scope's `attributes` may take, measured as compact JSON. A
97/// sync carrying a larger record is refused whole.
98pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
99/// Most ended scopes the daemon remembers per owner. The oldest is forgotten
100/// first, and reaching the bound never refuses a sync.
101pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
102/// Most modules one targeted carrier entry may list.
103pub const MAX_CARRIER_TARGETS: usize = 16;
104/// Most milliseconds a new scope epoch's deadline may be ahead of the daemon's
105/// current Unix wall clock: 24 hours.
106pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
107
108/// What a scope stands for. Closed, and fixed for the life of one
109/// `scope_epoch`: a different kind needs a new epoch, which ends the old scope.
110#[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/// A link from a scope to another scope, pinned to that scope's session by its
119/// epoch.
120#[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/// Who, besides the owner, may open routes under a scope.
142///
143/// `targets` absent means the carrier may open to any module. Present, it
144/// names the only module ids the carrier may open to, and must hold between 1
145/// and [`MAX_CARRIER_TARGETS`] entries: an empty list is refused rather than
146/// read as either "none" or "all".
147#[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
172/// Declaring this in a manifest's `capabilities.provides` promises that the
173/// module recognises a scope carrying `flow_id` and applies flow behaviour:
174/// it never treats the flow as its owner agent.
175/// During migration, either this capability or
176/// [`crate::call_mode::CALL_MODES_CAPABILITY`] admits flow scopes.
177pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
178
179/// Declaring this in a manifest's `capabilities.provides` promises that the
180/// module recognises `run_id` as one agent run and does not exercise the agent's
181/// delegated authority under that scope.
182/// During migration it admits non-delegating run scopes; delegating runs require
183/// [`crate::call_mode::CALL_MODES_CAPABILITY`] instead.
184pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
185
186/// Declaring this in a manifest's `capabilities.provides` promises that the
187/// module recognises `on_behalf_of_agent` as attribution only, never authority.
188/// The daemon also advertises this capability to scope-authority owners.
189pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
190
191/// The authority-controlled attributes the daemon copies into scope stamps,
192/// subject to each field's target capability gate.
193/// Only an owner module named in the daemon config's `scope_authority_owners`
194/// list (by default the module that owns agent sessions) may set them; a scope
195/// owned by any other module must leave them empty.
196#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
197#[serde(deny_unknown_fields)]
198#[non_exhaustive]
199pub struct ScopeAttributes {
200    /// The agent the scope's session belongs to. Identity, never permission.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub agent_id: Option<String>,
203    /// Attribution only, never authority. A provider may use this to choose
204    /// identity-scoped presentation (bot choice, read budgets, bound
205    /// repositories) and for logging. It must never treat this as authority to
206    /// act as that agent, hand out the agent's per-agent handles or consent on
207    /// its strength, or treat it as `agent_id`.
208    ///
209    /// Set only by a scope-authority owner and validated with `agent_id`'s
210    /// token rule. Mutually exclusive with `agent_id`, `delegates` and `flow_id`;
211    /// `run_id` requires `agent_id` and is therefore excluded too. Adding,
212    /// changing or removing this within an epoch increments the content version
213    /// and closes routes with `scope_delegation_changed`. Bind stamps include
214    /// it only for targets providing [`SCOPE_ON_BEHALF_OF_CAPABILITY`]; describe
215    /// replies include it only for callers providing that capability.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub on_behalf_of_agent: Option<String>,
218    /// Whether a provider may act as `agent_id`. Refused without `agent_id`.
219    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220    pub delegates: bool,
221    /// This scope belongs to the named flow, an automated workflow run on an
222    /// agent's behalf. Set only by an authority owner (see above), validated
223    /// with [`validate_flow_id`], and stamped verbatim. It needs neither
224    /// `agent_id` nor `delegates`. Providers treat a module other than the
225    /// owner that opens a route under a flow scope as the flow's carrier.
226    ///
227    /// Like an `agent_id` change, changing this within the same scope epoch is
228    /// accepted: the scope's content version increases (the number providers
229    /// compare to notice a change), and every route under the scope is closed
230    /// with the reason `scope_delegation_changed`, so no live route keeps the
231    /// old identity.
232    /// A target must provide [`FLOW_SCOPES_CAPABILITY`] or
233    /// [`crate::call_mode::CALL_MODES_CAPABILITY`] before the daemon may send a
234    /// bind stamped with this field. Decoding it alone is not enough:
235    /// the target must also apply flow behaviour instead of agent behaviour.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub flow_id: Option<String>,
238    /// Identifies one run carried out on behalf of `agent_id`. Requires
239    /// `agent_id`, forbids `flow_id`, and uses
240    /// [`validate_run_id`]'s token rule.
241    /// Adding, changing or removing it within an epoch increments the scope's
242    /// content version and closes routes under the scope with
243    /// `scope_delegation_changed`. The daemon sends this field in a bind only to
244    /// a target module providing [`AGENT_RUN_SCOPES_CAPABILITY`] or
245    /// [`crate::call_mode::CALL_MODES_CAPABILITY`]. A delegating run scope is
246    /// accepted as a record, but binds only to a target providing the latter.
247    #[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
295/// Check a flow id using the shared opaque-token rule: 1–256 printable,
296/// non-space ASCII bytes. Errors name `flow_id`. Scope refs remain opaque and
297/// are not subject to this token rule.
298pub 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
302/// Check a run id using the shared opaque-token rule: 1–256 ASCII bytes in
303/// `0x21`–`0x7E`. Errors name `run_id`.
304pub 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
308/// Check attribution using the agent token rule: 1–256 printable, non-space
309/// ASCII bytes. Errors name `on_behalf_of_agent`.
310pub 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/// One scope as its owner registers it in `scope.sync` or `scope.apply`.
315#[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    /// Owner-supplied session number. The owner keeps it with its own record of
322    /// the session, re-sends the same value for the same session after any
323    /// restart, and uses a higher one when it reuses the ref for a new session.
324    pub scope_epoch: u64,
325    pub kind: ScopeKind,
326    /// Only the holder of the scope's bind proof can bind it when this hash is
327    /// present. Without a hash, admission is unchanged and proofs are ignored.
328    #[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    /// Refuse an epoch replacement or bind-proof change while routes are bound
335    /// to the live epoch, including binds admitted but not yet committed, or
336    /// connected presence holders remain. Send only after capability discovery.
337    /// This is a request condition, not a stored scope attribute.
338    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
339    pub replace_only_if_idle: bool,
340    /// Absolute Unix wall-clock deadline in milliseconds. It cannot be added,
341    /// changed or removed within this scope epoch; absent means no deadline.
342    /// This is not an authority attribute.
343    #[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    /// Principals, other than the owner, allowed to register child scopes under
348    /// this one. Listing a principal here grants it nothing else.
349    #[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/// A request to end one scope session in `scope.apply`.
421#[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/// What `scope.apply` did with one requested end.
440#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
441#[serde(rename_all = "snake_case")]
442pub enum ScopeEndOutcome {
443    /// The named scope ref was live at this epoch and was ended.
444    Ended,
445    /// The named scope ref was not live at this epoch; this end request changed
446    /// nothing.
447    NotLive,
448}
449
450/// The per-end result in a `scope.apply` reply, in request order.
451#[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/// The scope a `route.open` asks to be admitted under.
472///
473/// `scope_epoch` is optional on the wire only so that leaving it out is
474/// refused by name (`scope_epoch_required`) rather than as a malformed body:
475/// every opener must name it, the owner included.
476#[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    /// Base64url-encoded 32-byte secret, without padding. Ignored for records
487    /// without a bind-proof hash, so holders may always send their proof.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub bind_proof: Option<String>,
490    /// Keep connection-held presence after an admitted open, even if its route
491    /// closes. Send only to daemons advertising `scope-replace-if-idle/v1`.
492    #[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/// The state of a scope's parent link.
541#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
542#[serde(rename_all = "snake_case")]
543pub enum ParentState {
544    /// The parent is live at the named epoch and the link was permitted.
545    Linked,
546    /// The parent's owner has not synced in this daemon incarnation, so the
547    /// link is unverified and grants nothing yet.
548    Pending,
549    /// The parent is gone or live at another epoch, or the link was refused
550    /// when the parent's owner synced. Final for this link.
551    Ended,
552}
553
554/// What a `scope.sync` or `scope.apply` did with one record.
555#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
556#[serde(rename_all = "snake_case")]
557pub enum ScopeRecordOutcome {
558    /// The ref was not live before; the scope was created.
559    Created,
560    /// The ref was live at a lower epoch; that scope ended and this one began.
561    Replaced,
562    /// The ref was live at this epoch and its content changed.
563    Updated,
564    /// The ref was live at this epoch with identical content; its `version`
565    /// did not move.
566    Unchanged,
567    /// The record was refused on its own merits (`code` says why). The refusal
568    /// itself does not change the ref or undo any expiry processing.
569    Refused,
570}
571
572/// The per-record result in a `scope.sync` or `scope.apply` reply, in request order.
573#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
574pub struct ScopeRecordResult {
575    #[serde(rename = "ref")]
576    pub scope_ref: String,
577    /// The epoch the record named, which for a refusal may differ from the
578    /// epoch still held.
579    pub scope_epoch: u64,
580    pub outcome: ScopeRecordOutcome,
581    /// The refusal code when `outcome` is `refused`.
582    #[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    /// The daemon's content counter for the scope held under this ref after
587    /// the sync; absent when no scope is live under it.
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    pub version: Option<u64>,
590    /// The parent link's state after the sync, for a scope with a parent.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub parent_state: Option<ParentState>,
593}
594
595/// A scope session of the calling owner that ended through omission from
596/// `scope.sync`, an explicit `scope.apply` end, replacement by a higher epoch
597/// for the same ref or expiry.
598#[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/// `scope.describe`'s answer about one `(owner, ref)`.
606#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
607#[serde(rename_all = "snake_case")]
608pub enum ScopeStatus {
609    Live,
610    /// Ended in this daemon incarnation, and still remembered.
611    Ended,
612    /// Neither live nor remembered as ended. With `owner_synced` true the scope
613    /// is gone: an owner's first sync of an incarnation is its full set. With
614    /// `owner_synced` false and `owner_configured` true the owner has not
615    /// re-synced since a daemon restart, so a reader waits. With
616    /// `owner_configured` false the owner will never sync.
617    NotLive,
618}
619
620/// The fields the daemon stamps for a live scope.
621/// Build with [`ScopeStamp::new`] and the setters so future fields are additive.
622#[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    /// Whether the owner is listed in the daemon's `scope_authority_owners`.
637    /// Providers decide on this flag and keep no copy of the list.
638    pub owner_authorized: bool,
639    /// Absolute Unix wall-clock deadline in milliseconds, fixed for this epoch.
640    /// On route binds the daemon sends this deadline only to targets declaring
641    /// [`crate::call_mode::CALL_MODES_CAPABILITY`], because older providers may
642    /// reject unfamiliar scope-stamp fields.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub expires_at_ms: Option<u64>,
645}
646
647impl ScopeStamp {
648    /// A stamp with no parent, attributes or deadline, and no owner authority.
649    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}