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