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