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.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/// The `server.describe` capability a daemon advertises when it admits routes
53/// under scopes. A carrier that needs a scoped route and does not see it fails
54/// the call (`scope_unsupported`) instead of opening an unscoped route.
55pub const CAP_SCOPES_V1: &str = "scopes/v1";
56
57/// The `server.describe` capability a daemon advertises when it checks a
58/// `route.open`'s `role_versions` and forwards them on the module's bind. A
59/// daemon without it drops the field silently, so a consumer that relies on
60/// the provider seeing its role versions checks for this first.
61pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
62
63/// Module-to-subc op that registers an owner's full scope set.
64pub const SCOPE_SYNC_OP: &str = "scope.sync";
65/// Module-to-subc op that reads one scope's current state.
66pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
67
68/// Most live scopes one owner may hold. A sync naming more is refused whole.
69pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
70/// Most bytes one scope's `attributes` may take, measured as compact JSON. A
71/// sync carrying a larger record is refused whole.
72pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
73/// Most ended scopes the daemon remembers per owner. The oldest is forgotten
74/// first, and reaching the bound never refuses a sync.
75pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
76/// Most modules one targeted carrier entry may list.
77pub const MAX_CARRIER_TARGETS: usize = 16;
78
79/// What a scope stands for. Closed, and fixed for the life of one
80/// `scope_epoch`: a different kind needs a new epoch, which ends the old scope.
81#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
82#[serde(rename_all = "snake_case")]
83pub enum ScopeKind {
84    Head,
85    Worker,
86    Ephemeral,
87}
88
89/// A link from a scope to another scope, pinned to that scope's session by its
90/// epoch.
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
92#[serde(deny_unknown_fields)]
93pub struct ScopeParent {
94    #[serde(deserialize_with = "deserialize_scope_principal")]
95    pub owner: Principal,
96    #[serde(rename = "ref")]
97    pub scope_ref: String,
98    pub scope_epoch: u64,
99}
100
101/// Who, besides the owner, may open routes under a scope.
102///
103/// `targets` absent means the carrier may open to any module. Present, it
104/// names the only module ids the carrier may open to, and must hold between 1
105/// and [`MAX_CARRIER_TARGETS`] entries: an empty list is refused rather than
106/// read as either "none" or "all".
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
108#[serde(deny_unknown_fields)]
109pub struct ScopeCarrier {
110    #[serde(deserialize_with = "deserialize_scope_principal")]
111    pub principal: Principal,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub targets: Option<Vec<String>>,
114}
115
116/// Declaring this in a manifest's `capabilities.provides` promises that the
117/// module recognises a scope carrying `flow_id` and applies flow behaviour:
118/// it never treats the flow as its owner agent.
119pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
120
121/// The attributes the daemon stamps without interpreting. They bear authority,
122/// so only an owner module named in the daemon config's `scope_authority_owners`
123/// list (by default the module that owns agent sessions) may set them; a scope
124/// owned by any other module must leave them empty.
125#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
126#[serde(deny_unknown_fields)]
127pub struct ScopeAttributes {
128    /// The agent the scope's session belongs to. Identity, never permission.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub agent_id: Option<String>,
131    /// Whether a provider may act as `agent_id`. Refused without `agent_id`.
132    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
133    pub delegates: bool,
134    /// This scope belongs to the named flow, an automated workflow run on an
135    /// agent's behalf. Set only by an authority owner (see above), validated
136    /// with [`validate_flow_id`], and stamped verbatim. It needs neither
137    /// `agent_id` nor `delegates`. Providers treat a module other than the
138    /// owner that opens a route under a flow scope as the flow's carrier.
139    ///
140    /// Like an `agent_id` change, changing this within the same scope epoch is
141    /// accepted: the scope's content version increases (the number providers
142    /// compare to notice a change), and every route under the scope is closed
143    /// with the reason `scope_delegation_changed`, so no live route keeps the
144    /// old identity.
145    /// A target must provide [`FLOW_SCOPES_CAPABILITY`] before the daemon may
146    /// send a bind stamped with this field. Decoding it alone is not enough:
147    /// the target must also apply flow behaviour instead of agent behaviour.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub flow_id: Option<String>,
150}
151
152impl ScopeAttributes {
153    pub fn is_empty(&self) -> bool {
154        self.agent_id.is_none() && !self.delegates && self.flow_id.is_none()
155    }
156}
157
158/// Check a flow id using the shared opaque-token rule: 1–256 printable,
159/// non-space ASCII bytes. Errors name `flow_id`. Scope refs remain opaque and
160/// are not subject to this token rule.
161pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
162    crate::tool_call::validate_opaque_field("flow_id", flow_id)
163}
164
165/// One scope as its owner registers it in `scope.sync`.
166#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
167#[serde(deny_unknown_fields)]
168pub struct ScopeRecord {
169    #[serde(rename = "ref")]
170    pub scope_ref: String,
171    /// Owner-supplied session number. The owner keeps it with its own record of
172    /// the session, re-sends the same value for the same session after any
173    /// restart, and uses a higher one when it reuses the ref for a new session.
174    pub scope_epoch: u64,
175    pub kind: ScopeKind,
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub parent: Option<ScopeParent>,
178    /// Principals, other than the owner, allowed to register child scopes under
179    /// this one. Listing a principal here grants it nothing else.
180    #[serde(
181        default,
182        skip_serializing_if = "Vec::is_empty",
183        deserialize_with = "deserialize_scope_principals"
184    )]
185    pub child_owners: Vec<Principal>,
186    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187    pub carriers: Vec<ScopeCarrier>,
188    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
189    pub attributes: ScopeAttributes,
190}
191
192/// The scope a `route.open` asks to be admitted under.
193///
194/// `scope_epoch` is optional on the wire only so that leaving it out is
195/// refused by name (`scope_epoch_required`) rather than as a malformed body:
196/// every opener must name it, the owner included.
197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(deny_unknown_fields)]
199pub struct ScopeSelector {
200    #[serde(deserialize_with = "deserialize_scope_principal")]
201    pub owner: Principal,
202    #[serde(rename = "ref")]
203    pub scope_ref: String,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub scope_epoch: Option<u64>,
206}
207
208/// The state of a scope's parent link.
209#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
210#[serde(rename_all = "snake_case")]
211pub enum ParentState {
212    /// The parent is live at the named epoch and the link was permitted.
213    Linked,
214    /// The parent's owner has not synced in this daemon incarnation, so the
215    /// link is unverified and grants nothing yet.
216    Pending,
217    /// The parent is gone or live at another epoch, or the link was refused
218    /// when the parent's owner synced. Final for this link.
219    Ended,
220}
221
222/// What a `scope.sync` did with one record.
223#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
224#[serde(rename_all = "snake_case")]
225pub enum ScopeRecordOutcome {
226    /// The ref was not live before; the scope was created.
227    Created,
228    /// The ref was live at a lower epoch; that scope ended and this one began.
229    Replaced,
230    /// The ref was live at this epoch and its content changed.
231    Updated,
232    /// The ref was live at this epoch with identical content; its `version`
233    /// did not move.
234    Unchanged,
235    /// The record was refused on its own merits (`code` says why) and the ref
236    /// keeps whatever state it had before this sync.
237    Refused,
238}
239
240/// The per-record result in a `scope.sync` reply, in request order.
241#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
242pub struct ScopeRecordResult {
243    #[serde(rename = "ref")]
244    pub scope_ref: String,
245    /// The epoch the record named, which for a refusal may differ from the
246    /// epoch still held.
247    pub scope_epoch: u64,
248    pub outcome: ScopeRecordOutcome,
249    /// The refusal code when `outcome` is `refused`.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub code: Option<String>,
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub message: Option<String>,
254    /// The daemon's content counter for the scope held under this ref after
255    /// the sync; absent when no scope is live under it.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub version: Option<u64>,
258    /// The parent link's state after the sync, for a scope with a parent.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub parent_state: Option<ParentState>,
261}
262
263/// A scope of the syncing owner that the sync ended, by removal or by a
264/// higher epoch for the same ref.
265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
266pub struct ScopeEnded {
267    #[serde(rename = "ref")]
268    pub scope_ref: String,
269    pub scope_epoch: u64,
270}
271
272/// `scope.describe`'s answer about one `(owner, ref)`.
273#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
274#[serde(rename_all = "snake_case")]
275pub enum ScopeStatus {
276    Live,
277    /// Ended in this daemon incarnation, and still remembered.
278    Ended,
279    /// Neither live nor remembered as ended. With `owner_synced` true the scope
280    /// is gone: an owner's first sync of an incarnation is its full set. With
281    /// `owner_synced` false and `owner_configured` true the owner has not
282    /// re-synced since a daemon restart, so a reader waits. With
283    /// `owner_configured` false the owner will never sync.
284    NotLive,
285}
286
287/// The fields the daemon stamps for a live scope.
288#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
289pub struct ScopeStamp {
290    pub owner: Principal,
291    #[serde(rename = "ref")]
292    pub scope_ref: String,
293    pub scope_epoch: u64,
294    pub kind: ScopeKind,
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub parent: Option<ScopeParent>,
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub parent_state: Option<ParentState>,
299    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
300    pub attributes: ScopeAttributes,
301    /// Whether the owner is listed in the daemon's `scope_authority_owners`.
302    /// Providers decide on this flag and keep no copy of the list.
303    pub owner_authorized: bool,
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::tool_call::OpaqueFieldError;
310
311    #[test]
312    fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
313        let field = "flow_id";
314        assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
315        assert_eq!(validate_flow_id("f"), Ok(()));
316        assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
317        assert_eq!(
318            validate_flow_id(&"f".repeat(257)),
319            Err(OpaqueFieldError::TooLong { field, length: 257 })
320        );
321        assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
322        for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
323            let error = validate_flow_id(bad).unwrap_err();
324            assert_eq!(
325                error,
326                OpaqueFieldError::InvalidCharacter { field, index: 1 }
327            );
328            assert_eq!(error.field(), "flow_id");
329        }
330    }
331
332    #[test]
333    fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
334        let attributes = ScopeAttributes::default();
335        assert!(attributes.is_empty());
336        assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
337        assert_eq!(
338            serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
339            attributes
340        );
341        let attributes = ScopeAttributes {
342            flow_id: Some("flow:7".to_string()),
343            ..ScopeAttributes::default()
344        };
345        assert!(!attributes.is_empty());
346        let encoded = serde_json::to_string(&attributes).unwrap();
347        assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
348        assert_eq!(
349            serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
350            attributes
351        );
352        assert!(
353            serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
354                .is_err()
355        );
356    }
357}