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