Skip to main content

subc_protocol/
session.rs

1//! Session route control wire contract.
2//!
3//! subc has two distinct channel-0 handshakes. Module registration is the
4//! module-to-subc `HELLO`/`HELLO_ACK` handshake that registers the manifest and
5//! liveness. Route bind is the client-to-subc-to-module request/response
6//! handshake that binds one client route to a module route channel.
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::{
14    call_mode::CallMode,
15    manifest::{CapabilityDeclarations, ProviderRole},
16    scope::{
17        ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
18        ScopeStatus,
19    },
20    BindIdentity, Principal, RouteCloseReason, RouteTarget,
21};
22
23pub const MODULE_CONTROL_OP_HEALTH_CHECK: &str = "health.check";
24pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE: &str = "catalog.update";
25pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS: &str =
26    "catalog.update_role_declarations";
27
28#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(rename_all = "snake_case")]
30pub enum HealthStatus {
31    Ok,
32    Degraded,
33    Failing,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub struct HealthReport {
38    pub status: HealthStatus,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub detail: Option<String>,
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub metrics: Option<Value>,
43}
44
45impl HealthReport {
46    pub fn ok() -> Self {
47        Self {
48            status: HealthStatus::Ok,
49            detail: None,
50            metrics: None,
51        }
52    }
53}
54
55/// subc-to-module channel-0 control RPC body.
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[serde(tag = "op")]
58// RouteBind carries the complete bind metadata, while HealthCheck is a marker;
59// preserving the direct wire shape is more useful than boxing every bind field.
60#[allow(clippy::large_enum_variant)]
61pub enum ModuleControlRequest {
62    #[serde(rename = "route.bind")]
63    RouteBind {
64        route_channel: u16,
65        epoch: u32,
66        target: RouteTarget,
67        identity: BindIdentity,
68        /// The daemon's attestation of the consumer, and the only field here a
69        /// provider may grant privilege on.
70        ///
71        /// `Reserved` is minted at exactly one place in the daemon, on the branch
72        /// where the consumer's launch nonce matched a supervised spawn — the
73        /// function that checks is the function that mints, so the value cannot
74        /// exist without the check having run. That property is what a provider is
75        /// relying on, and it is the reason to key authority on this rather than on
76        /// `identity`, which is client-supplied and unattested (see BindIdentity).
77        ///
78        /// Absent means the daemon made no attestation, which is not the same as a
79        /// denial: it is the shape a pre-attestation peer sends. Treat it as
80        /// unattested rather than as trusted-by-default.
81        #[serde(default, skip_serializing_if = "Option::is_none")]
82        principal: Option<Principal>,
83        /// Consumer-declared reverse-request families and provider-contract
84        /// capabilities for the route. For example, `content/v1` declares that
85        /// the consumer understands the tool-provider content result format.
86        /// This remains an unverified declaration that grants nothing; a provider
87        /// that over-trusts it may still send reverse requests that later time
88        /// out or deny. Providers must treat an absent field as no declared
89        /// capability. The vocabulary is open strings; known MCP method-family
90        /// values today are "elicitation", "sampling", and "roots".
91        #[serde(default, skip_serializing_if = "Option::is_none")]
92        consumer_capabilities: Option<Vec<String>>,
93        /// The versions of provider roles the consumer speaks on this route,
94        /// role name to version (`{"tool-provider": "v1"}`), copied from the
95        /// consumer's `route.open` unchanged. Like `consumer_capabilities` it
96        /// is the consumer's unverified declaration and grants nothing; a
97        /// provider uses it to choose which version of a role's wire shape to
98        /// speak. The daemon has checked it with [`validate_role_versions`] and
99        /// never sends an empty map. Absent means the consumer declared none:
100        /// a legacy consumer, or a daemon that predates the field.
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        role_versions: Option<BTreeMap<String, String>>,
103        /// Opaque admission facts supplied by the configured carrier module.
104        #[serde(default, skip_serializing_if = "Option::is_none")]
105        admission_facts: Option<Value>,
106        /// The daemon's stamp of the scope the route was admitted under, taken
107        /// from the owner's synced record at admission. Like `principal`, it is
108        /// the daemon's, never the opener's: a provider may act on it (on
109        /// `owner_authorized`, `delegates` and `agent_id` together), and must
110        /// treat it as fixed for the route's life, because a change that
111        /// revokes authority closes the route.
112        ///
113        /// Absent means the route was opened without a scope, or by a daemon
114        /// that predates scopes. A provider that needs a scope refuses the bind.
115        #[serde(default, skip_serializing_if = "Option::is_none")]
116        scope: Option<ScopeStamp>,
117        /// The daemon-derived mode, sent only to targets declaring
118        /// [`crate::call_mode::CALL_MODES_CAPABILITY`]. If absent, readers derive
119        /// the mode from `scope` with [`crate::call_mode::derive_call_mode`].
120        /// Providers must refuse an unknown mode.
121        #[serde(default, skip_serializing_if = "Option::is_none")]
122        call_mode: Option<CallMode>,
123    },
124    #[serde(rename = "health.check")]
125    HealthCheck {},
126}
127
128/// One-way subc-to-module channel-0 control command.
129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
130#[serde(tag = "op")]
131pub enum ModuleControlCommand {
132    #[serde(rename = "module.draining")]
133    Draining {
134        reason: RouteCloseReason,
135        /// Absolute Unix-millisecond deadline for this drain.
136        ///
137        /// WALL CLOCK, WHILE THE DAEMON ENFORCES THE CEILING ON A
138        /// SUSPEND-EXCLUDING MONOTONIC CLOCK (`Instant`, supervise.rs). Both
139        /// processes share one host so `CLOCK_REALTIME` agrees exactly, and the
140        /// two clocks diverge only across host sleep: `Instant` stops, wall does
141        /// not. So a module that sleeps mid-drain wakes to a deadline further in
142        /// the past than the daemon's own ceiling, computes LESS remaining time
143        /// than it has, and seals early.
144        ///
145        /// That direction is deliberate and is the safe one — a module stopping
146        /// early loses nothing, since the daemon kills at its own ceiling
147        /// regardless. The reverse (a module believing it has time the daemon
148        /// has already spent) is the failure this ordering avoids. A module must
149        /// therefore treat this as "no later than", never as a grant.
150        deadline_ms: u64,
151    },
152    /// Sent only to modules that declared [`LIVE_UPGRADE_CAPABILITY`].
153    #[serde(rename = "module.upgrading")]
154    Upgrading {
155        /// Absolute Unix-millisecond reconnect deadline. Convert it once on
156        /// receipt to a monotonic deadline and treat it as a ceiling, not a grant.
157        reconnect_by_ms: u64,
158    },
159}
160
161/// Opt-in to staying alive and reconnecting across an in-place daemon upgrade.
162pub const LIVE_UPGRADE_CAPABILITY: &str = "live-upgrade/v1";
163
164/// Opt-in to keeping route admission open during a module restart's long-work phase.
165pub const ACCEPTING_DRAIN_CAPABILITY: &str = "accepting-drain/v1";
166
167/// Module-to-daemon channel-0 request and acknowledgement op.
168pub const MODULE_DRAIN_READY_OP: &str = "module.drain_ready";
169
170/// Empty request and acknowledgement body for `module.drain_ready`.
171#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
172#[serde(tag = "op", deny_unknown_fields)]
173pub enum ModuleDrainReady {
174    #[serde(rename = "module.drain_ready")]
175    Ready {},
176}
177
178/// `module.draining` with the accepting-phase marker, sent only to opted-in modules.
179#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
180#[serde(tag = "op")]
181pub enum AcceptingDrainCommand {
182    #[serde(rename = "module.draining")]
183    Draining {
184        reason: RouteCloseReason,
185        /// Absolute Unix-millisecond ceiling for the accepting phase.
186        deadline_ms: u64,
187        accepting: bool,
188    },
189}
190
191/// Module-to-subc channel-0 response body.
192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
193#[serde(tag = "op")]
194pub enum ModuleControlResponse {
195    /// ACK-only success. Rejections use the `FrameType::Error` lane.
196    #[serde(rename = "route.bind")]
197    RouteBindAck {},
198    #[serde(rename = "health.check")]
199    HealthCheck {
200        status: HealthStatus,
201        #[serde(default, skip_serializing_if = "Option::is_none")]
202        detail: Option<String>,
203        #[serde(default, skip_serializing_if = "Option::is_none")]
204        metrics: Option<Value>,
205    },
206}
207
208/// Module-originated channel-0 control RPC body.
209///
210/// This is intentionally separate from [`ModuleControlRequest`]: that enum is the
211/// daemon-to-module direction (`route.bind`, `health.check`), while these bodies
212/// are sent by an already-registered module to subc on a `REQUEST` frame.
213#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
214#[serde(tag = "op")]
215#[non_exhaustive]
216pub enum ModuleControlRequestFromModule {
217    /// Ask the daemon whether a stored source may still open its route.
218    #[serde(rename = "route.authorize")]
219    RouteAuthorize {
220        principal: Principal,
221        scope: crate::scope::RouteAuthorizeScope,
222        target: String,
223        expected: crate::scope::RouteAuthorizeExpected,
224    },
225    #[serde(rename = "catalog.update")]
226    CatalogUpdate {
227        provides: Vec<ProviderRole>,
228        /// An attested replacement for the static capability declaration emitted
229        /// by the module's current manifest. `None` preserves the prior
230        /// declaration so existing role-only catalog updates remain byte-identical.
231        #[serde(default, skip_serializing_if = "Option::is_none")]
232        capabilities: Option<CapabilityDeclarations>,
233        /// Updates readiness without re-registering. `None` leaves it unchanged.
234        ///
235        /// Both directions are allowed, but repeatedly flapping readiness looks
236        /// like a restart storm to callers and is a defect in the module.
237        #[serde(default, skip_serializing_if = "Option::is_none")]
238        ready: Option<bool>,
239    },
240    /// Replace the complete role-declaration map; an empty object clears it.
241    #[serde(rename = "catalog.update_role_declarations")]
242    CatalogUpdateRoleDeclarations {
243        /// Kept raw so malformed maps receive a reasoned daemon refusal rather
244        /// than being dropped by the manifest's lenient HELLO decoding.
245        #[serde(deserialize_with = "Value::deserialize")]
246        role_declarations: Value,
247    },
248    #[serde(rename = "supervisor.live_roots")]
249    LiveRoots {},
250    #[serde(rename = "policy_root.get")]
251    PolicyRoot(crate::policy_root::GetPolicyRoot),
252    #[serde(rename = "policy_root.rotate")]
253    PolicyRootRotate(crate::policy_root::RotatePolicyRoot),
254    /// Attribute agent-requested command roots to the declaring module.
255    /// Only the module's supervised connection may send this operation.
256    /// `known`, when present, replaces its complete live root set. The reply
257    /// is an empty object; invalid roots are ignored independently.
258    #[serde(rename = "supervisor.agent_commands")]
259    AgentCommands {
260        started: Vec<AgentCommandRoot>,
261        finished: Vec<AgentCommandFinished>,
262        #[serde(default, skip_serializing_if = "Option::is_none")]
263        known: Option<Vec<AgentCommandRoot>>,
264    },
265    /// Register this module's full scope set. The owner is the module whose
266    /// registered connection sends it; nothing in the body names the owner.
267    /// Per-record refusals come back in the reply; a refusal of the whole sync
268    /// (not the owner's sync authority, a stale generation, a bound exceeded)
269    /// is an `Error` frame and changes nothing.
270    #[serde(rename = "scope.sync")]
271    ScopeSync {
272        generation: u64,
273        scopes: Vec<ScopeRecord>,
274    },
275    /// Change selected scopes after the daemon accepts a full `scope.sync` from
276    /// this connection. Shares the full sync's generation sequence. Unlike a
277    /// full sync, omitting a scope does not end it; expiry processing still runs.
278    /// A whole-call refusal is an `Error` frame and changes nothing.
279    #[serde(rename = "scope.apply")]
280    ScopeApply {
281        generation: u64,
282        upsert: Vec<ScopeRecord>,
283        end: Vec<ScopeEnd>,
284    },
285    /// Read one scope's current state.
286    #[serde(rename = "scope.describe")]
287    ScopeDescribe {
288        owner: Principal,
289        #[serde(rename = "ref")]
290        scope_ref: String,
291    },
292}
293
294/// A command's PID and kernel start time in milliseconds since the Unix epoch.
295/// Obtain the time through `subc_os::process_start_time_ms`, not a wall clock.
296#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
297pub struct AgentCommandRoot {
298    pub pid: u32,
299    pub start_time_ms: u64,
300}
301
302/// A completed declared root. CPU includes reaped descendants where available.
303#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
304pub struct AgentCommandFinished {
305    pub pid: u32,
306    pub start_time_ms: u64,
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub cpu_ms: Option<u64>,
309}
310
311/// Counts of routes for one canonical project root.
312#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313pub struct LiveRoot {
314    pub project_root: std::path::PathBuf,
315    pub bound: u64,
316    pub pending: u64,
317}
318
319/// subc's channel-0 response body for module-originated control RPCs.
320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
321#[serde(tag = "op")]
322// ScopeDescribe carries a complete stamp. Keep its public fields inline to
323// preserve the response construction API instead of boxing a single variant.
324#[allow(clippy::large_enum_variant)]
325pub enum ModuleControlResponseToModule {
326    #[serde(rename = "catalog.update")]
327    CatalogUpdate {},
328    #[serde(rename = "catalog.update_role_declarations")]
329    CatalogUpdateRoleDeclarations {},
330    #[serde(rename = "supervisor.live_roots")]
331    LiveRoots {
332        roots: Vec<LiveRoot>,
333        unknown_root_bindings: u64,
334        total_bindings: u64,
335    },
336    #[serde(rename = "policy_root.get")]
337    PolicyRoot(crate::policy_root::PolicyRoot),
338    #[serde(rename = "policy_root.rotate")]
339    PolicyRootRotate(crate::policy_root::PolicyRootChange),
340    #[serde(rename = "scope.sync")]
341    ScopeSync {
342        generation: u64,
343        results: Vec<ScopeRecordResult>,
344        #[serde(default, skip_serializing_if = "Vec::is_empty")]
345        ended: Vec<ScopeEnded>,
346    },
347    #[serde(rename = "scope.apply")]
348    ScopeApply {
349        generation: u64,
350        results: Vec<ScopeRecordResult>,
351        end_results: Vec<ScopeEndResult>,
352        #[serde(default, skip_serializing_if = "Vec::is_empty")]
353        ended: Vec<ScopeEnded>,
354    },
355    #[serde(rename = "scope.describe")]
356    ScopeDescribe {
357        status: ScopeStatus,
358        /// The live epoch, or for `ended` the most recent epoch that ended.
359        #[serde(default, skip_serializing_if = "Option::is_none")]
360        scope_epoch: Option<u64>,
361        daemon_incarnation: String,
362        /// Whether the owner has synced since this daemon incarnation started.
363        owner_synced: bool,
364        /// Whether the owner is a module in the daemon's supervised roster.
365        owner_configured: bool,
366        /// The stamp fields, present only when `status` is `live`.
367        #[serde(default, skip_serializing_if = "Option::is_none")]
368        scope: Option<ScopeStamp>,
369    },
370}
371
372/// A module's channel-0 request to confirm one in-flight write with the person.
373///
374/// This standalone body keeps the existing exhaustive module-control enums
375/// unchanged. The daemon validates the summary and the asking connection's
376/// permission before showing a prompt; constructing a request grants nothing.
377#[non_exhaustive]
378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
379pub struct OperatorConfirmRequest {
380    op: OperatorConfirmOp,
381    pub summary: String,
382    /// The caller's route channel as seen on the asking module's connection.
383    pub route_channel: u16,
384    /// The epoch of that route on the asking module's connection.
385    pub route_epoch: u32,
386    /// What the asking module says it is confirming. Absent (an older module)
387    /// means the same as an unrecognised kind: the person is prompted. Only
388    /// [`OperatorConfirmKind::Operation`] can ever be answered without a
389    /// prompt; [`OperatorConfirmKind::Enrollment`] always prompts.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub kind: Option<OperatorConfirmKind>,
392    /// The management operation being confirmed, as the asking module's
393    /// manifest names it in `confirm_operations`. Meaningful only with
394    /// [`OperatorConfirmKind::Operation`]; absent means the person is prompted.
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub operation: Option<String>,
397}
398
399impl OperatorConfirmRequest {
400    /// A request with neither `kind` nor `operation`, whose bytes match what
401    /// modules sent before those fields existed.
402    pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
403        Self {
404            op: OperatorConfirmOp::Confirm,
405            summary: summary.into(),
406            route_channel,
407            route_epoch,
408            kind: None,
409            operation: None,
410        }
411    }
412
413    /// Set or clear `kind`.
414    #[must_use]
415    pub fn with_kind(mut self, kind: Option<OperatorConfirmKind>) -> Self {
416        self.kind = kind;
417        self
418    }
419
420    /// Set or clear `operation`.
421    #[must_use]
422    pub fn with_operation(mut self, operation: Option<String>) -> Self {
423        self.operation = operation;
424        self
425    }
426}
427
428/// The `kind` of an [`OperatorConfirmRequest`].
429///
430/// A value from a newer module decodes as [`OperatorConfirmKind::Unknown`],
431/// keeping its spelling, rather than refusing the request. The daemon prompts
432/// for every kind except an explicit `operation`.
433#[derive(Debug, Clone, PartialEq, Eq)]
434pub enum OperatorConfirmKind {
435    /// A management operation the module declares in `confirm_operations`.
436    Operation,
437    /// Pairing or enrolling a device or credential. Always prompts.
438    Enrollment,
439    Unknown(String),
440}
441
442impl Serialize for OperatorConfirmKind {
443    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
444        serializer.serialize_str(match self {
445            Self::Operation => "operation",
446            Self::Enrollment => "enrollment",
447            Self::Unknown(value) => value,
448        })
449    }
450}
451
452impl<'de> Deserialize<'de> for OperatorConfirmKind {
453    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
454        Ok(match String::deserialize(deserializer)?.as_str() {
455            "operation" => Self::Operation,
456            "enrollment" => Self::Enrollment,
457            value => Self::Unknown(value.to_owned()),
458        })
459    }
460}
461
462/// A successful channel-0 reply to an [`OperatorConfirmRequest`].
463///
464/// Only `outcome: "confirmed"` confirms the write. Refusals use [`crate::ErrorBody`]
465/// instead. Readers must not treat an unknown outcome as confirmation.
466#[non_exhaustive]
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
468pub struct OperatorConfirmReply {
469    op: OperatorConfirmOp,
470    pub outcome: String,
471}
472
473impl OperatorConfirmReply {
474    pub fn confirmed() -> Self {
475        Self {
476            op: OperatorConfirmOp::Confirm,
477            outcome: "confirmed".to_string(),
478        }
479    }
480}
481
482// A required, single-valued field both emits the op and refuses a missing or
483// different op when decoding, without exposing a caller-editable tag.
484#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
485enum OperatorConfirmOp {
486    #[serde(rename = "operator.confirm")]
487    Confirm,
488}
489
490impl From<HealthReport> for ModuleControlResponse {
491    fn from(report: HealthReport) -> Self {
492        Self::HealthCheck {
493            status: report.status,
494            detail: report.detail,
495            metrics: report.metrics,
496        }
497    }
498}
499
500impl ModuleControlResponse {
501    pub fn health_report(&self) -> Option<HealthReport> {
502        match self {
503            Self::HealthCheck {
504                status,
505                detail,
506                metrics,
507            } => Some(HealthReport {
508                status: *status,
509                detail: detail.clone(),
510                metrics: metrics.clone(),
511            }),
512            Self::RouteBindAck {} => None,
513        }
514    }
515}
516
517/// Module-to-subc channel-0 push body.
518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
519#[serde(tag = "op")]
520pub enum ModuleControlPush {
521    #[serde(rename = "route.status")]
522    RouteStatus {
523        route_channel: u16,
524        route_epoch: u32,
525        status: String,
526    },
527}
528
529/// The wire name of the `role_versions` field on `route.open` and
530/// `route.bind`, for the `detail.field` of the `invalid_request` error that
531/// refuses a malformed one.
532pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
533
534/// Most entries a `role_versions` map may hold.
535pub const MAX_ROLE_VERSIONS: usize = 8;
536
537/// The longest role name accepted in `role_versions`, in bytes.
538pub const MAX_ROLE_NAME_LEN: usize = 64;
539
540/// Why a `role_versions` map was refused.
541#[derive(Clone, Debug, PartialEq, Eq)]
542#[non_exhaustive]
543pub enum RoleVersionsError {
544    /// The map has more than [`MAX_ROLE_VERSIONS`] entries.
545    TooMany { count: usize },
546    /// A role name is not lowercase ASCII letters and digits in words joined
547    /// by single hyphens (`tool-provider`), or is longer than
548    /// [`MAX_ROLE_NAME_LEN`] bytes.
549    InvalidRole { role: String },
550    /// A version is not `v` followed by a positive integer without leading
551    /// zeros (`v1`, `v12`).
552    InvalidVersion { role: String, version: String },
553}
554
555impl RoleVersionsError {
556    /// The request field the error is about: always [`ROLE_VERSIONS_FIELD`].
557    pub fn field(&self) -> &'static str {
558        ROLE_VERSIONS_FIELD
559    }
560}
561
562impl std::fmt::Display for RoleVersionsError {
563    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564        match self {
565            Self::TooMany { count } => write!(
566                f,
567                "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
568            ),
569            Self::InvalidRole { role } => write!(
570                f,
571                "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
572                 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
573            ),
574            Self::InvalidVersion { role, version } => write!(
575                f,
576                "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
577                 followed by a positive integer without leading zeros"
578            ),
579        }
580    }
581}
582
583impl std::error::Error for RoleVersionsError {}
584
585/// Check a `role_versions` map: at most [`MAX_ROLE_VERSIONS`] entries, each
586/// role name matching `^[a-z0-9]+(-[a-z0-9]+)*$` in at most
587/// [`MAX_ROLE_NAME_LEN`] bytes, and each version matching `^v[1-9][0-9]*$`.
588///
589/// The daemon refuses a `route.open` that fails this, so a consumer can run
590/// the same check before sending. An empty map passes; the daemon treats it
591/// as no declaration at all.
592pub fn validate_role_versions(
593    role_versions: &BTreeMap<String, String>,
594) -> Result<(), RoleVersionsError> {
595    if role_versions.len() > MAX_ROLE_VERSIONS {
596        return Err(RoleVersionsError::TooMany {
597            count: role_versions.len(),
598        });
599    }
600    for (role, version) in role_versions {
601        if !is_role_name(role) {
602            return Err(RoleVersionsError::InvalidRole { role: role.clone() });
603        }
604        if !is_role_version(version) {
605            return Err(RoleVersionsError::InvalidVersion {
606                role: role.clone(),
607                version: version.clone(),
608            });
609        }
610    }
611    Ok(())
612}
613
614fn is_role_name(role: &str) -> bool {
615    !role.is_empty()
616        && role.len() <= MAX_ROLE_NAME_LEN
617        && role.split('-').all(|word| {
618            !word.is_empty()
619                && word
620                    .bytes()
621                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
622        })
623}
624
625fn is_role_version(version: &str) -> bool {
626    let bytes = version.as_bytes();
627    bytes.len() >= 2
628        && bytes[0] == b'v'
629        && (b'1'..=b'9').contains(&bytes[1])
630        && bytes[2..].iter().all(u8::is_ascii_digit)
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn accepting_drain_wire_bodies_are_additive() {
639        let wire = br#"{"op":"module.drain_ready"}"#;
640        assert_eq!(
641            serde_json::to_vec(&ModuleDrainReady::Ready {}).unwrap(),
642            wire
643        );
644        assert_eq!(
645            serde_json::from_slice::<ModuleDrainReady>(wire).unwrap(),
646            ModuleDrainReady::Ready {}
647        );
648        assert!(serde_json::from_slice::<ModuleDrainReady>(
649            br#"{"op":"module.drain_ready","module_id":"other"}"#
650        )
651        .is_err());
652        let accepting = AcceptingDrainCommand::Draining {
653            reason: RouteCloseReason::Restart,
654            deadline_ms: 1000,
655            accepting: true,
656        };
657        let notice = serde_json::to_vec(&accepting).unwrap();
658        assert_eq!(
659            notice,
660            br#"{"op":"module.draining","reason":"restart","deadline_ms":1000,"accepting":true}"#
661        );
662        let legacy = ModuleControlCommand::Draining {
663            reason: RouteCloseReason::Restart,
664            deadline_ms: 1000,
665        };
666        assert_eq!(
667            serde_json::from_slice::<ModuleControlCommand>(&notice).unwrap(),
668            legacy
669        );
670        assert_eq!(
671            serde_json::to_vec(&legacy).unwrap(),
672            br#"{"op":"module.draining","reason":"restart","deadline_ms":1000}"#
673        );
674    }
675    #[test]
676    fn catalog_update_role_declarations_wire_round_trip() {
677        for declarations in [
678            serde_json::json!({"media-provider/v1": {"engines": ["image"]}}),
679            serde_json::json!({}),
680        ] {
681            let body = serde_json::json!({
682                "op": "catalog.update_role_declarations",
683                "role_declarations": declarations,
684            });
685            let request: ModuleControlRequestFromModule =
686                serde_json::from_value(body.clone()).unwrap();
687            assert_eq!(serde_json::to_value(request).unwrap(), body);
688        }
689        let body = serde_json::json!({"op": "catalog.update_role_declarations"});
690        let response: ModuleControlResponseToModule = serde_json::from_value(body.clone()).unwrap();
691        assert_eq!(serde_json::to_value(response).unwrap(), body);
692        assert!(serde_json::from_value::<ModuleControlRequestFromModule>(body).is_err());
693    }
694
695    fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
696        entries
697            .iter()
698            .map(|(role, version)| (role.to_string(), version.to_string()))
699            .collect()
700    }
701
702    #[test]
703    fn role_versions_accept_role_names_and_positive_versions() {
704        for entries in [
705            vec![],
706            vec![("tool-provider", "v1")],
707            vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
708        ] {
709            assert_eq!(
710                validate_role_versions(&map(&entries)),
711                Ok(()),
712                "{entries:?}"
713            );
714        }
715        let longest = "a".repeat(MAX_ROLE_NAME_LEN);
716        assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
717        let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
718            .map(|index| (format!("role-{index}"), "v1".to_string()))
719            .collect();
720        assert_eq!(validate_role_versions(&full), Ok(()));
721    }
722
723    #[test]
724    fn role_versions_refuse_malformed_role_names() {
725        let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
726        for role in [
727            "",
728            "Tool-provider",
729            "tool_provider",
730            "tool provider",
731            "-tool",
732            "tool-",
733            "tool--provider",
734            "tool.provider",
735            "outil-é",
736            too_long.as_str(),
737        ] {
738            let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
739            assert_eq!(
740                error,
741                RoleVersionsError::InvalidRole {
742                    role: role.to_string()
743                },
744                "{role:?}"
745            );
746            assert_eq!(error.field(), "role_versions");
747        }
748    }
749
750    #[test]
751    fn role_versions_refuse_malformed_versions() {
752        for version in [
753            "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
754        ] {
755            let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
756            assert_eq!(
757                error,
758                RoleVersionsError::InvalidVersion {
759                    role: "tool-provider".to_string(),
760                    version: version.to_string(),
761                },
762                "{version:?}"
763            );
764            assert_eq!(error.field(), "role_versions");
765        }
766    }
767
768    #[test]
769    fn role_versions_refuse_more_than_eight_entries() {
770        let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
771            .map(|index| (format!("role-{index}"), "v1".to_string()))
772            .collect();
773        let error = validate_role_versions(&nine).unwrap_err();
774        assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
775        assert_eq!(error.field(), "role_versions");
776        assert!(error.to_string().starts_with("role_versions"), "{error}");
777    }
778
779    #[test]
780    fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
781        let bind = |role_versions| ModuleControlRequest::RouteBind {
782            route_channel: 1,
783            epoch: 1,
784            target: crate::RouteTarget::ToolProvider {
785                module_id: "aft".to_string(),
786            },
787            identity: crate::BindIdentity::new("h", "s"),
788            principal: None,
789            consumer_capabilities: None,
790            role_versions,
791            admission_facts: None,
792            scope: None,
793            call_mode: None,
794        };
795        let absent = serde_json::to_value(bind(None)).unwrap();
796        assert!(absent.get("role_versions").is_none(), "{absent}");
797        let present = bind(Some(map(&[("tool-provider", "v1")])));
798        let encoded = serde_json::to_value(&present).unwrap();
799        assert_eq!(
800            encoded["role_versions"],
801            serde_json::json!({ "tool-provider": "v1" })
802        );
803        let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
804        assert_eq!(decoded, present);
805    }
806}
807
808#[cfg(test)]
809mod agent_command_tests {
810    use super::*;
811
812    #[test]
813    fn agent_commands_round_trip_start_finish_and_known_snapshot() {
814        let root = AgentCommandRoot {
815            pid: 42,
816            start_time_ms: 1_700_000_000_123,
817        };
818        let request = ModuleControlRequestFromModule::AgentCommands {
819            started: vec![root],
820            finished: vec![AgentCommandFinished {
821                pid: 43,
822                start_time_ms: root.start_time_ms,
823                cpu_ms: Some(100),
824            }],
825            known: Some(vec![root]),
826        };
827        let value = serde_json::to_value(&request).unwrap();
828        assert_eq!(
829            value,
830            serde_json::json!({"op":"supervisor.agent_commands",
831            "started":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}],
832            "finished":[{"pid":43,"start_time_ms":1_700_000_000_123_u64,"cpu_ms":100}],
833            "known":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}]})
834        );
835        assert_eq!(
836            serde_json::from_value::<ModuleControlRequestFromModule>(value).unwrap(),
837            request
838        );
839        let absent = ModuleControlRequestFromModule::AgentCommands {
840            started: Vec::new(),
841            finished: vec![AgentCommandFinished {
842                pid: 1,
843                start_time_ms: 2,
844                cpu_ms: None,
845            }],
846            known: None,
847        };
848        assert_eq!(
849            serde_json::to_value(absent).unwrap(),
850            serde_json::json!({"op":"supervisor.agent_commands",
851            "started":[],"finished":[{"pid":1,"start_time_ms":2}]})
852        );
853    }
854}