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
18mod federated;
19pub use federated::{FederatedAttributes, FederatedPeerClass, RemoteClaim};
20
21/// A reader declares this only after implementing the federated provider rules.
22pub const SCOPE_FEDERATED_CAPABILITY: &str = "scope-federated/v1";
23
24// Scope principals are authority-bearing input: an unrecognized constraint must
25// not silently widen a grant. Principal elsewhere is a forward-compatible caller
26// fact, so keep its general decoder lenient and enforce this only on scope input.
27#[derive(Deserialize)]
28#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
29enum ScopePrincipal {
30    Reserved { module_id: String },
31    Direct {},
32    Unverified {},
33}
34
35impl From<ScopePrincipal> for Principal {
36    fn from(value: ScopePrincipal) -> Self {
37        match value {
38            ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
39            ScopePrincipal::Direct {} => Self::Direct,
40            ScopePrincipal::Unverified {} => Self::Unverified,
41        }
42    }
43}
44
45fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
46    deserializer: D,
47) -> Result<Principal, D::Error> {
48    ScopePrincipal::deserialize(deserializer).map(Into::into)
49}
50
51fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
52    deserializer: D,
53) -> Result<Vec<Principal>, D::Error> {
54    Vec::<ScopePrincipal>::deserialize(deserializer)
55        .map(|principals| principals.into_iter().map(Into::into).collect())
56}
57
58/// A scope bind-proof hash is the lowercase hexadecimal SHA-256 digest.
59pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
60    if hash.len() == 64
61        && hash
62            .bytes()
63            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
64    {
65        Ok(())
66    } else {
67        Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
68    }
69}
70
71fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
72    deserializer: D,
73) -> Result<Option<String>, D::Error> {
74    let hash = Option::<String>::deserialize(deserializer)?;
75    if let Some(hash) = &hash {
76        validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
77    }
78    Ok(hash)
79}
80
81/// The `server.describe` capability a daemon advertises when it admits routes
82/// under scopes. A carrier that needs a scoped route and does not see it fails
83/// the call (`scope_unsupported`) instead of opening an unscoped route.
84pub const CAP_SCOPES_V1: &str = "scopes/v1";
85
86/// The `server.describe` capability a daemon advertises when it checks a
87/// `route.open`'s `role_versions` and forwards them on the module's bind. A
88/// daemon without it drops the field silently, so a consumer that relies on
89/// the provider seeing its role versions checks for this first.
90pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
91
92/// A target declares this in `capabilities.provides` once it no longer reads
93/// project fields from `route.bind` identities. Declaring it makes the daemon
94/// omit those identity fields, independently of [`SCOPE_WORKDIR_CAPABILITY`],
95/// which gates both `workdir` and `project_id` in the admitted [`ScopeStamp`].
96pub const BIND_NO_PROJECT_CAPABILITY: &str = "bind-no-project/v1";
97
98/// Module-to-subc op that registers an owner's full scope set.
99pub const SCOPE_SYNC_OP: &str = "scope.sync";
100/// Module-to-subc op that upserts or ends scopes without replacing the owner's
101/// full scope set.
102pub const SCOPE_APPLY_OP: &str = "scope.apply";
103/// Module-to-subc op that reads one scope's current state.
104pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
105
106/// Most live scopes one owner may hold. A sync naming more is refused whole.
107pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
108/// Most bytes one scope's `attributes` may take, measured as compact JSON. A
109/// sync carrying a larger record is refused whole.
110pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
111/// Most ended scopes the daemon remembers per owner. The oldest is forgotten
112/// first, and reaching the bound never refuses a sync.
113pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
114/// Most modules one targeted carrier entry may list.
115pub const MAX_CARRIER_TARGETS: usize = 16;
116/// Most milliseconds a new scope epoch's deadline may be ahead of the daemon's
117/// current Unix wall clock: 24 hours.
118pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
119
120/// What a scope stands for. Fixed for the life of one
121/// `scope_epoch`: a different kind needs a new epoch, which ends the old scope.
122#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
123#[serde(rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum ScopeKind {
126    Head,
127    Worker,
128    Ephemeral,
129    Federated,
130}
131
132/// A link from a scope to another scope, pinned to that scope's session by its
133/// epoch.
134#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
135#[serde(deny_unknown_fields)]
136#[non_exhaustive]
137pub struct ScopeParent {
138    #[serde(deserialize_with = "deserialize_scope_principal")]
139    pub owner: Principal,
140    #[serde(rename = "ref")]
141    pub scope_ref: String,
142    pub scope_epoch: u64,
143}
144
145impl ScopeParent {
146    pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
147        Self {
148            owner,
149            scope_ref: scope_ref.into(),
150            scope_epoch,
151        }
152    }
153}
154
155/// Who, besides the owner, may open routes under a scope.
156///
157/// `targets` absent means the carrier may open to any module. Present, it
158/// names the only module ids the carrier may open to, and must hold between 1
159/// and [`MAX_CARRIER_TARGETS`] entries: an empty list is refused rather than
160/// read as either "none" or "all".
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
162#[serde(deny_unknown_fields)]
163#[non_exhaustive]
164pub struct ScopeCarrier {
165    #[serde(deserialize_with = "deserialize_scope_principal")]
166    pub principal: Principal,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub targets: Option<Vec<String>>,
169}
170
171impl ScopeCarrier {
172    pub fn new(principal: Principal) -> Self {
173        Self {
174            principal,
175            targets: None,
176        }
177    }
178
179    #[must_use]
180    pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
181        self.targets = targets;
182        self
183    }
184}
185
186/// Declaring this in a manifest's `capabilities.provides` promises that the
187/// module recognises a scope carrying `flow_id` and applies flow behaviour:
188/// it never treats the flow as its owner agent.
189/// During migration, either this capability or
190/// [`crate::call_mode::CALL_MODES_CAPABILITY`] admits flow scopes.
191pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
192
193/// Declaring this capability promises that a reader accepts the installed flow
194/// identity fields in scope stamps. It does not replace flow-scope admission.
195pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
196
197/// Declaring this in a manifest's `capabilities.provides` promises that the
198/// module recognises `run_id` as one agent run and does not exercise the agent's
199/// delegated authority under that scope.
200/// During migration it admits non-delegating run scopes; delegating runs require
201/// [`crate::call_mode::CALL_MODES_CAPABILITY`] instead.
202pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
203
204/// Declaring this in a manifest's `capabilities.provides` promises that the
205/// module recognises `on_behalf_of_agent` as attribution only, never authority.
206/// The daemon also advertises this capability to scope-authority owners.
207pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
208
209/// A *worker run* is a codemode run scope with `run_id` and
210/// `on_behalf_of_agent` but no `agent_id`: it works for an agent without that
211/// agent's authority. Declaring this in a manifest's `capabilities.provides`
212/// promises that the module handles a codemode bind carrying `run_id` and no
213/// `agent_id` as attribution only, and never acts as, consents for, or hands out
214/// per-agent handles of the attributed agent. A worker run binds only to a
215/// target declaring it; `call-modes/v1` and `agent-run-scopes/v1` alone do not
216/// admit one, because those providers assume a run carries its agent's
217/// identity. A declarer receives `call_mode: codemode` and the stamp's
218/// `on_behalf_of_agent` on a worker-run bind even without
219/// [`SCOPE_ON_BEHALF_OF_CAPABILITY`]. The daemon also advertises this capability
220/// so owners register worker runs only with a daemon that accepts them.
221pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
222
223/// The daemon can answer whether a module acknowledged a bind under an owned scope epoch.
224pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
225
226/// The authority-controlled attributes the daemon copies into scope stamps,
227/// subject to each field's target capability gate.
228/// Only an owner module named in the daemon config's `scope_authority_owners`
229/// list (by default the module that owns agent sessions) may set them; a scope
230/// owned by any other module must leave them empty.
231/// The separate `federated` object is restricted to the configured federated
232/// owner instead, and never confers local-agent authority.
233#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
234#[serde(deny_unknown_fields)]
235#[non_exhaustive]
236pub struct ScopeAttributes {
237    /// Paired-peer facts, required only for a federated scope. Never local authority.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub federated: Option<FederatedAttributes>,
240    /// The agent the scope's session belongs to. Identity, never permission.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub agent_id: Option<String>,
243    /// Attribution only, never authority. A provider may use this to choose
244    /// identity-scoped presentation (bot choice, read budgets, bound
245    /// repositories) and for logging. It must never treat this as authority to
246    /// act as that agent, hand out the agent's per-agent handles or consent on
247    /// its strength, or treat it as `agent_id`.
248    ///
249    /// Set only by a scope-authority owner and validated with `agent_id`'s
250    /// token rule. Mutually exclusive with `agent_id`, `delegates` and `flow_id`.
251    /// With `run_id` and no `agent_id` it marks a worker run (see
252    /// [`WORKER_RUNS_CAPABILITY`]). Adding, changing or removing this within an
253    /// epoch increments the content version and closes routes with
254    /// `scope_delegation_changed`. Bind stamps include it only for targets
255    /// providing [`SCOPE_ON_BEHALF_OF_CAPABILITY`], except that a worker run's
256    /// bind, which reaches only a target providing [`WORKER_RUNS_CAPABILITY`],
257    /// always includes it. Describe replies include it only for callers
258    /// providing [`SCOPE_ON_BEHALF_OF_CAPABILITY`].
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub on_behalf_of_agent: Option<String>,
261    /// Whether a provider may act as `agent_id`. Refused without `agent_id`.
262    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
263    pub delegates: bool,
264    /// This scope belongs to the named flow, an automated workflow run on an
265    /// agent's behalf. Set only by an authority owner (see above), validated
266    /// with [`validate_flow_id`], and stamped verbatim. It needs neither
267    /// `agent_id` nor `delegates`. Providers treat a module other than the
268    /// owner that opens a route under a flow scope as the flow's carrier.
269    ///
270    /// Like an `agent_id` change, changing this within the same scope epoch is
271    /// accepted: the scope's content version increases (the number providers
272    /// compare to notice a change), and every route under the scope is closed
273    /// with the reason `scope_delegation_changed`, so no live route keeps the
274    /// old identity.
275    /// A target must provide [`FLOW_SCOPES_CAPABILITY`] or
276    /// [`crate::call_mode::CALL_MODES_CAPABILITY`] before the daemon may send a
277    /// bind stamped with this field. Decoding it alone is not enough:
278    /// the target must also apply flow behaviour instead of agent behaviour.
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub flow_id: Option<String>,
281    /// The approved installed version, from 1 through 2^53 - 1. Together with
282    /// `flow_code_hash` and `flow_install_id`, requires `flow_id` and is immutable
283    /// within an epoch (`scope_flow_identity_changed`). Stamped only for readers
284    /// providing [`FLOW_IDENTITY_SCOPES_CAPABILITY`].
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub flow_version: Option<u64>,
287    /// SHA-256 of the approved flow code: exactly 64 lowercase hex characters.
288    /// Present together with `flow_version` and `flow_install_id`, under the same
289    /// authority, immutability and capability rules.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub flow_code_hash: Option<String>,
292    /// Opaque installed-flow token, validated with [`validate_flow_install_id`].
293    /// Present together with `flow_version` and `flow_code_hash`, under the same
294    /// authority, immutability and capability rules.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub flow_install_id: Option<String>,
297    /// Identifies one run: an agent run on behalf of `agent_id`, or a worker run
298    /// attributed to `on_behalf_of_agent` without that agent's authority. A
299    /// record with `run_id` carries exactly one of the two, forbids `flow_id`,
300    /// and uses [`validate_run_id`]'s token rule.
301    /// Adding, changing or removing it within an epoch increments the scope's
302    /// content version and closes routes under the scope with
303    /// `scope_delegation_changed`. The daemon sends an agent run's bind only to
304    /// a target module providing [`AGENT_RUN_SCOPES_CAPABILITY`] or
305    /// [`crate::call_mode::CALL_MODES_CAPABILITY`]. A delegating run scope is
306    /// accepted as a record, but binds only to a target providing the latter.
307    /// A worker run binds only to a target providing [`WORKER_RUNS_CAPABILITY`].
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub run_id: Option<String>,
310}
311
312impl ScopeAttributes {
313    pub fn new() -> Self {
314        Self::default()
315    }
316
317    #[must_use]
318    pub fn with_federated(mut self, federated: Option<FederatedAttributes>) -> Self {
319        self.federated = federated;
320        self
321    }
322
323    #[must_use]
324    pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
325        self.agent_id = agent_id;
326        self
327    }
328
329    #[must_use]
330    pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
331        self.on_behalf_of_agent = on_behalf_of_agent;
332        self
333    }
334
335    #[must_use]
336    pub fn with_delegates(mut self, delegates: bool) -> Self {
337        self.delegates = delegates;
338        self
339    }
340
341    #[must_use]
342    pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
343        self.flow_id = flow_id;
344        self
345    }
346
347    #[must_use]
348    pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
349        self.flow_version = flow_version;
350        self
351    }
352
353    #[must_use]
354    pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
355        self.flow_code_hash = flow_code_hash;
356        self
357    }
358
359    #[must_use]
360    pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
361        self.flow_install_id = flow_install_id;
362        self
363    }
364
365    #[must_use]
366    pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
367        self.run_id = run_id;
368        self
369    }
370
371    pub fn is_empty(&self) -> bool {
372        self.federated.is_none()
373            && self.agent_id.is_none()
374            && self.on_behalf_of_agent.is_none()
375            && !self.delegates
376            && self.flow_id.is_none()
377            && self.flow_version.is_none()
378            && self.flow_code_hash.is_none()
379            && self.flow_install_id.is_none()
380            && self.run_id.is_none()
381    }
382}
383
384/// Check a flow id using the shared opaque-token rule: 1–256 printable,
385/// non-space ASCII bytes. Errors name `flow_id`. Scope refs remain opaque and
386/// are not subject to this token rule.
387pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
388    crate::tool_call::validate_opaque_field("flow_id", flow_id)
389}
390
391/// Check an installed flow version: 1 through 9007199254740991 (2^53 - 1), the
392/// largest integer every JSON reader, including JavaScript, decodes exactly.
393pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
394    if !(1..=9_007_199_254_740_991).contains(&flow_version) {
395        return Err("flow_version must be from 1 to 9007199254740991");
396    }
397    Ok(())
398}
399
400/// Check the approved flow code's SHA-256. Errors name `flow_code_hash`.
401pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
402    if flow_code_hash.len() != 64
403        || !flow_code_hash
404            .bytes()
405            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
406    {
407        return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
408    }
409    Ok(())
410}
411
412/// Check an installed flow token using the same opaque-token rule as `flow_id`.
413/// Errors name `flow_install_id`.
414pub fn validate_flow_install_id(
415    flow_install_id: &str,
416) -> Result<(), crate::tool_call::OpaqueFieldError> {
417    crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
418}
419
420/// Check a run id using the shared opaque-token rule: 1–256 ASCII bytes in
421/// `0x21`–`0x7E`. Errors name `run_id`.
422pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
423    crate::tool_call::validate_opaque_field("run_id", run_id)
424}
425
426/// Check attribution using the agent token rule: 1–256 printable, non-space
427/// ASCII bytes. Errors name `on_behalf_of_agent`.
428pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
429    crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
430}
431
432/// Capability declaring that a provider accepts session folder and project stamps.
433pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
434
435/// Check an Entorhinal project id without interpreting its opaque contents.
436pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
437    if value.is_empty() || value.len() > 128 {
438        return Err("project_id must contain 1 to 128 bytes");
439    }
440    if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
441        return Err("project_id must be printable ASCII without whitespace");
442    }
443    Ok(())
444}
445
446/// One scope as its owner registers it in `scope.sync` or `scope.apply`.
447#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
448#[serde(deny_unknown_fields)]
449#[non_exhaustive]
450pub struct ScopeRecord {
451    #[serde(rename = "ref")]
452    pub scope_ref: String,
453    /// Owner-supplied session number. The owner keeps it with its own record of
454    /// the session, re-sends the same value for the same session after any
455    /// restart, and uses a higher one when it reuses the ref for a new session.
456    pub scope_epoch: u64,
457    pub kind: ScopeKind,
458    /// Absolute session folder, canonicalized by the daemon and fixed per epoch.
459    /// Attribution only: this grants no authority.
460    #[serde(default, skip_serializing_if = "Option::is_none")]
461    pub workdir: Option<String>,
462    /// Opaque Entorhinal project id, fixed per epoch and never authority-gated.
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub project_id: Option<String>,
465    /// Only the holder of the scope's bind proof can bind it when this hash is
466    /// present. Without a hash, admission is unchanged and proofs are ignored.
467    #[serde(
468        default,
469        skip_serializing_if = "Option::is_none",
470        deserialize_with = "deserialize_bind_proof_sha256"
471    )]
472    pub bind_proof_sha256: Option<String>,
473    /// Refuse an epoch replacement or bind-proof change while routes are bound
474    /// to the live epoch, including binds admitted but not yet committed, or
475    /// connected presence holders remain. Send only after capability discovery.
476    /// This is a request condition, not a stored scope attribute.
477    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
478    pub replace_only_if_idle: bool,
479    /// Absolute Unix wall-clock deadline in milliseconds. It cannot be added,
480    /// changed or removed within this scope epoch; absent means no deadline.
481    /// This is not an authority attribute.
482    #[serde(default, skip_serializing_if = "Option::is_none")]
483    pub expires_at_ms: Option<u64>,
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub parent: Option<ScopeParent>,
486    /// Principals, other than the owner, allowed to register child scopes under
487    /// this one. Listing a principal here grants it nothing else.
488    #[serde(
489        default,
490        skip_serializing_if = "Vec::is_empty",
491        deserialize_with = "deserialize_scope_principals"
492    )]
493    pub child_owners: Vec<Principal>,
494    #[serde(default, skip_serializing_if = "Vec::is_empty")]
495    pub carriers: Vec<ScopeCarrier>,
496    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
497    pub attributes: ScopeAttributes,
498}
499
500impl ScopeRecord {
501    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
502        Self {
503            scope_ref: scope_ref.into(),
504            scope_epoch,
505            kind,
506            workdir: None,
507            project_id: None,
508            bind_proof_sha256: None,
509            replace_only_if_idle: false,
510            expires_at_ms: None,
511            parent: None,
512            child_owners: Vec::new(),
513            carriers: Vec::new(),
514            attributes: ScopeAttributes::default(),
515        }
516    }
517
518    #[must_use]
519    pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
520        self.workdir = workdir;
521        self
522    }
523
524    #[must_use]
525    pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
526        self.project_id = project_id;
527        self
528    }
529
530    #[must_use]
531    pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
532        self.bind_proof_sha256 = hash;
533        self
534    }
535
536    #[must_use]
537    pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
538        self.replace_only_if_idle = replace_only_if_idle;
539        self
540    }
541
542    #[must_use]
543    pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
544        self.expires_at_ms = expires_at_ms;
545        self
546    }
547
548    #[must_use]
549    pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
550        self.parent = parent;
551        self
552    }
553
554    #[must_use]
555    pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
556        self.child_owners = child_owners;
557        self
558    }
559
560    #[must_use]
561    pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
562        self.carriers = carriers;
563        self
564    }
565
566    #[must_use]
567    pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
568        self.attributes = attributes;
569        self
570    }
571}
572
573/// A request to end one scope session in `scope.apply`.
574#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
575#[serde(deny_unknown_fields)]
576#[non_exhaustive]
577pub struct ScopeEnd {
578    #[serde(rename = "ref")]
579    pub scope_ref: String,
580    pub scope_epoch: u64,
581}
582
583impl ScopeEnd {
584    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
585        Self {
586            scope_ref: scope_ref.into(),
587            scope_epoch,
588        }
589    }
590}
591
592/// What `scope.apply` did with one requested end.
593#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
594#[serde(rename_all = "snake_case")]
595pub enum ScopeEndOutcome {
596    /// The named scope ref was live at this epoch and was ended.
597    Ended,
598    /// The named scope ref was not live at this epoch; this end request changed
599    /// nothing.
600    NotLive,
601}
602
603/// The per-end result in a `scope.apply` reply, in request order.
604#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
605#[serde(deny_unknown_fields)]
606#[non_exhaustive]
607pub struct ScopeEndResult {
608    #[serde(rename = "ref")]
609    pub scope_ref: String,
610    pub scope_epoch: u64,
611    pub outcome: ScopeEndOutcome,
612}
613
614impl ScopeEndResult {
615    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
616        Self {
617            scope_ref: scope_ref.into(),
618            scope_epoch,
619            outcome,
620        }
621    }
622}
623
624/// The scope a `route.open` asks to be admitted under.
625///
626/// `scope_epoch` is optional on the wire only so that leaving it out is
627/// refused by name (`scope_epoch_required`) rather than as a malformed body:
628/// every opener must name it, the owner included.
629#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
630#[serde(deny_unknown_fields)]
631#[non_exhaustive]
632pub struct ScopeSelector {
633    #[serde(deserialize_with = "deserialize_scope_principal")]
634    pub owner: Principal,
635    #[serde(rename = "ref")]
636    pub scope_ref: String,
637    #[serde(default, skip_serializing_if = "Option::is_none")]
638    pub scope_epoch: Option<u64>,
639    /// Base64url-encoded 32-byte secret, without padding. Ignored for records
640    /// without a bind-proof hash, so holders may always send their proof.
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub bind_proof: Option<String>,
643    /// Keep connection-held presence after an admitted open, even if its route
644    /// closes. Send only to daemons advertising `scope-replace-if-idle/v1`.
645    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
646    pub hold_presence: bool,
647}
648
649impl ScopeSelector {
650    pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
651        Self {
652            owner,
653            scope_ref: scope_ref.into(),
654            scope_epoch,
655            bind_proof: None,
656            hold_presence: false,
657        }
658    }
659
660    #[must_use]
661    pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
662        self.bind_proof = proof;
663        self
664    }
665
666    #[must_use]
667    pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
668        self.hold_presence = hold_presence;
669        self
670    }
671}
672
673impl std::fmt::Debug for ScopeSelector {
674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675        f.debug_struct("ScopeSelector")
676            .field("owner", &self.owner)
677            .field("scope_ref", &self.scope_ref)
678            .field("scope_epoch", &self.scope_epoch)
679            .field(
680                "bind_proof",
681                &self.bind_proof.as_ref().map(|_| "<redacted>"),
682            )
683            .finish()
684    }
685}
686
687impl std::fmt::Display for ScopeSelector {
688    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
689        std::fmt::Debug::fmt(self, f)
690    }
691}
692
693/// The state of a scope's parent link.
694#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
695#[serde(rename_all = "snake_case")]
696pub enum ParentState {
697    /// The parent is live at the named epoch and the link was permitted.
698    Linked,
699    /// The parent's owner has not synced in this daemon incarnation, so the
700    /// link is unverified and grants nothing yet.
701    Pending,
702    /// The parent is gone or live at another epoch, or the link was refused
703    /// when the parent's owner synced. Final for this link.
704    Ended,
705}
706
707/// What a `scope.sync` or `scope.apply` did with one record.
708#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
709#[serde(rename_all = "snake_case")]
710pub enum ScopeRecordOutcome {
711    /// The ref was not live before; the scope was created.
712    Created,
713    /// The ref was live at a lower epoch; that scope ended and this one began.
714    Replaced,
715    /// The ref was live at this epoch and its content changed.
716    Updated,
717    /// The ref was live at this epoch with identical content; its `version`
718    /// did not move.
719    Unchanged,
720    /// The record was refused on its own merits (`code` says why). The refusal
721    /// itself does not change the ref or undo any expiry processing.
722    Refused,
723}
724
725/// The per-record result in a `scope.sync` or `scope.apply` reply, in request order.
726#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
727pub struct ScopeRecordResult {
728    #[serde(rename = "ref")]
729    pub scope_ref: String,
730    /// The epoch the record named, which for a refusal may differ from the
731    /// epoch still held.
732    pub scope_epoch: u64,
733    pub outcome: ScopeRecordOutcome,
734    /// The refusal code when `outcome` is `refused`.
735    #[serde(default, skip_serializing_if = "Option::is_none")]
736    pub code: Option<String>,
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub message: Option<String>,
739    /// The daemon's content counter for the scope held under this ref after
740    /// the sync; absent when no scope is live under it.
741    #[serde(default, skip_serializing_if = "Option::is_none")]
742    pub version: Option<u64>,
743    /// The parent link's state after the sync, for a scope with a parent.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub parent_state: Option<ParentState>,
746}
747
748/// A scope session of the calling owner that ended through omission from
749/// `scope.sync`, an explicit `scope.apply` end, replacement by a higher epoch
750/// for the same ref or expiry.
751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
752pub struct ScopeEnded {
753    #[serde(rename = "ref")]
754    pub scope_ref: String,
755    pub scope_epoch: u64,
756}
757
758/// `scope.describe`'s answer about one `(owner, ref)`.
759#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
760#[serde(rename_all = "snake_case")]
761pub enum ScopeStatus {
762    Live,
763    /// Ended in this daemon incarnation, and still remembered.
764    Ended,
765    /// Neither live nor remembered as ended. With `owner_synced` true the scope
766    /// is gone: an owner's first sync of an incarnation is its full set. With
767    /// `owner_synced` false and `owner_configured` true the owner has not
768    /// re-synced since a daemon restart, so a reader waits. With
769    /// `owner_configured` false the owner will never sync.
770    NotLive,
771}
772
773/// The fields the daemon stamps for a live scope.
774/// Build with [`ScopeStamp::new`] and the setters so future fields are additive.
775#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
776#[non_exhaustive]
777pub struct ScopeStamp {
778    pub owner: Principal,
779    #[serde(rename = "ref")]
780    pub scope_ref: String,
781    pub scope_epoch: u64,
782    pub kind: ScopeKind,
783    /// Canonical session folder. Sent on binds only to providers declaring
784    /// [`SCOPE_WORKDIR_CAPABILITY`]; absent fields keep older binds unchanged.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub workdir: Option<String>,
787    /// Entorhinal project id for attribution, never authority.
788    #[serde(default, skip_serializing_if = "Option::is_none")]
789    pub project_id: Option<String>,
790    #[serde(default, skip_serializing_if = "Option::is_none")]
791    pub parent: Option<ScopeParent>,
792    #[serde(default, skip_serializing_if = "Option::is_none")]
793    pub parent_state: Option<ParentState>,
794    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
795    pub attributes: ScopeAttributes,
796    /// Whether the owner is listed in the daemon's `scope_authority_owners`.
797    /// Providers decide on this flag and keep no copy of the list.
798    /// Always false for the configured federated owner, even if it is listed.
799    pub owner_authorized: bool,
800    /// Absolute Unix wall-clock deadline in milliseconds, fixed for this epoch.
801    /// On route binds the daemon sends this deadline only to targets declaring
802    /// [`crate::call_mode::CALL_MODES_CAPABILITY`], because older providers may
803    /// reject unfamiliar scope-stamp fields.
804    #[serde(default, skip_serializing_if = "Option::is_none")]
805    pub expires_at_ms: Option<u64>,
806}
807
808impl ScopeStamp {
809    /// A stamp with no parent, attributes or deadline, and no owner authority.
810    pub fn new(
811        owner: Principal,
812        scope_ref: impl Into<String>,
813        scope_epoch: u64,
814        kind: ScopeKind,
815    ) -> Self {
816        Self {
817            owner,
818            scope_ref: scope_ref.into(),
819            scope_epoch,
820            kind,
821            workdir: None,
822            project_id: None,
823            parent: None,
824            parent_state: None,
825            attributes: ScopeAttributes::new(),
826            owner_authorized: false,
827            expires_at_ms: None,
828        }
829    }
830
831    #[must_use]
832    pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
833        self.workdir = workdir;
834        self
835    }
836
837    #[must_use]
838    pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
839        self.project_id = project_id;
840        self
841    }
842
843    #[must_use]
844    pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
845        self.parent = parent;
846        self
847    }
848
849    #[must_use]
850    pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
851        self.parent_state = parent_state;
852        self
853    }
854
855    #[must_use]
856    pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
857        self.attributes = attributes;
858        self
859    }
860
861    #[must_use]
862    pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
863        self.owner_authorized = owner_authorized;
864        self
865    }
866
867    #[must_use]
868    pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
869        self.expires_at_ms = expires_at_ms;
870        self
871    }
872}
873
874#[cfg(test)]
875mod tests {
876    use super::*;
877    use crate::tool_call::OpaqueFieldError;
878
879    #[test]
880    fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
881        for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
882            assert_eq!(validate_project_id(valid), Ok(()));
883        }
884        for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
885            assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
886        }
887    }
888
889    #[test]
890    fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
891        let record = ScopeRecord::new("session", 1, ScopeKind::Head);
892        assert_eq!(
893            serde_json::to_string(&record).unwrap(),
894            r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
895        );
896        let record = record
897            .with_workdir(Some("/folder".into()))
898            .with_project_id(Some("project:1".into()));
899        let encoded = serde_json::to_string(&record).unwrap();
900        assert_eq!(
901            serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
902            record
903        );
904        let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
905        assert_eq!(
906            serde_json::to_string(&stamp).unwrap(),
907            r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
908        );
909        let stamp = stamp
910            .with_workdir(record.workdir)
911            .with_project_id(record.project_id);
912        let encoded = serde_json::to_string(&stamp).unwrap();
913        assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
914    }
915
916    #[test]
917    fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
918        let field = "flow_id";
919        assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
920        assert_eq!(validate_flow_id("f"), Ok(()));
921        assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
922        assert_eq!(
923            validate_flow_id(&"f".repeat(257)),
924            Err(OpaqueFieldError::TooLong { field, length: 257 })
925        );
926        assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
927        for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
928            let error = validate_flow_id(bad).unwrap_err();
929            assert_eq!(
930                error,
931                OpaqueFieldError::InvalidCharacter { field, index: 1 }
932            );
933            assert_eq!(error.field(), "flow_id");
934        }
935    }
936
937    #[test]
938    fn flow_identity_validators_enforce_boundaries_and_name_fields() {
939        for valid in [1, 9_007_199_254_740_991] {
940            assert_eq!(validate_flow_version(valid), Ok(()));
941        }
942        for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
943            assert!(validate_flow_version(invalid)
944                .unwrap_err()
945                .contains("flow_version"));
946        }
947        assert_eq!(
948            validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
949            Ok(())
950        );
951        for invalid in [
952            "a".repeat(63),
953            "a".repeat(65),
954            "A".repeat(64),
955            "g".repeat(64),
956        ] {
957            assert!(validate_flow_code_hash(&invalid)
958                .unwrap_err()
959                .contains("flow_code_hash"));
960        }
961        for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
962            assert_eq!(validate_flow_install_id(valid), Ok(()));
963        }
964        for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
965            assert_eq!(
966                validate_flow_install_id(invalid).unwrap_err().field(),
967                "flow_install_id"
968            );
969        }
970    }
971
972    #[test]
973    fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
974        let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
975        let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
976            .with_attributes(attributes.clone());
977        assert_eq!(
978            serde_json::to_string(&stamp).unwrap(),
979            r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
980        );
981        let attributes = attributes
982            .with_flow_version(Some(9_007_199_254_740_991))
983            .with_flow_code_hash(Some("a".repeat(64)))
984            .with_flow_install_id(Some("install:7".into()));
985        let stamp = stamp.with_attributes(attributes.clone());
986        let encoded = serde_json::to_string(&stamp).unwrap();
987        assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
988        assert_eq!(
989            serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
990                .unwrap(),
991            attributes
992        );
993        assert!(
994            serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
995                .is_err()
996        );
997        assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
998        assert!(!ScopeAttributes::new()
999            .with_flow_code_hash(Some("a".repeat(64)))
1000            .is_empty());
1001        assert!(!ScopeAttributes::new()
1002            .with_flow_install_id(Some("i".into()))
1003            .is_empty());
1004    }
1005
1006    #[test]
1007    fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
1008        let attributes = ScopeAttributes::default();
1009        assert!(attributes.is_empty());
1010        assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
1011        assert_eq!(
1012            serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
1013            attributes
1014        );
1015        let attributes = ScopeAttributes {
1016            flow_id: Some("flow:7".to_string()),
1017            ..ScopeAttributes::default()
1018        };
1019        assert!(!attributes.is_empty());
1020        let encoded = serde_json::to_string(&attributes).unwrap();
1021        assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1022        assert_eq!(
1023            serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1024            attributes
1025        );
1026        assert!(
1027            serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1028                .is_err()
1029        );
1030    }
1031}