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