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