Skip to main content

subc_protocol/
lib.rs

1//! subc wire contract.
2//!
3//! This crate is the single source of truth for the subc <-> module wire,
4//! shared by subc-core and AFT. It defines the **envelope** (the fixed
5//! 21-byte routing header subc splices on), the canonical subc-generated body
6//! schemas such as [`ErrorBody`], and the capability manifest. JSON-RPC request
7//! and response bodies remain module-owned opaque payloads to subc.
8//!
9//! ## The envelope (locked — see docs/subc-core-architecture.md §4.8)
10//!
11//! ```text
12//!  offset  size  field     type    purpose
13//!    0      4    len       u32     # of BODY bytes after this 21-byte header
14//!    4      1    ver       u8      envelope version
15//!    5      1    type      u8      frame kind (see FrameType)
16//!    6      1    flags     u8     bit0 BINARY · bits1-2 PRIORITY · bit3 LAST · bits4-5 ADMISSION · bit6 DAEMON_ORIGIN · bit7 SUBSCRIPTION
17//!    7      2    channel   u16     route = (component, session); 0 = subc itself
18//!    9      4    epoch     u32     per-slot binding epoch; 0 on channel 0
19//!   13      8    corr      u64     correlation id; CANCEL carries the target call's corr
20//!   21 -> body
21//! ```
22//!
23//! Little-endian (same-machine, native, no byte-swap on the hot path).
24//!
25//! **Frozen prefix (the versioning invariant):** `len` (u32 @ 0) and `ver`
26//! (u8 @ 4) keep fixed meaning + position in *every* future version. A reader
27//! of any version can therefore always read the first 5 bytes, learn `ver`,
28//! look up that version's header length, read the rest, and splice `len` body
29//! bytes. `decode_header` enforces this discipline.
30
31#![forbid(unsafe_code)]
32
33use std::{error::Error, fmt, path::PathBuf};
34
35use serde::{Deserialize, Serialize};
36
37pub use machine_id::{MachineId, MachineIdError};
38
39pub mod call_mode;
40pub mod frame;
41pub mod framed_body;
42pub mod machine_id;
43pub mod manifest;
44pub mod scope;
45pub mod session;
46pub mod tool_call;
47
48/// Canonical error codes emitted by subc.
49///
50/// Error frames remain extensible strings, but these daemon-owned route-open
51/// outcomes need identical spelling across the daemon and SDK retry policies.
52pub mod error_codes {
53    use crate::Flags;
54
55    pub const UNKNOWN_CHANNEL: &str = "unknown_channel";
56    pub const STALE_ROUTE_EPOCH: &str = "stale_route_epoch";
57    /// A module reply exceeds the client connection's whole egress byte budget.
58    /// TERMINAL for this request: the module already received it, and retrying
59    /// unchanged would produce the same oversized reply. The route stays open.
60    pub const FRAME_TOO_LARGE: &str = "frame_too_large";
61    pub const UNKNOWN_MODULE: &str = "unknown_module";
62    pub const MODULE_REMOVED: &str = "module_removed";
63    /// The target module's endpoint is draining for a reload, restart or disable.
64    ///
65    /// On the data plane (an `ERROR` frame answering a `REQUEST` on a bound route)
66    /// this code is a PRE-SEND GUARANTEE: the daemon returns it only when the
67    /// request could not take a route credit because the endpoint is draining,
68    /// and it returns it BEFORE forwarding, so the module never received the
69    /// request. A caller may therefore re-dispatch the same request once the
70    /// route is reopened without risking a duplicated side effect, exactly as it
71    /// may after `unknown_channel`. The daemon keeps this guarantee:
72    /// `supervisor_reload_rejects_new_work_during_drain` asserts the module's
73    /// event journal never records the rejected request. A request the module
74    /// already received is answered by the module (or its route closes with
75    /// `route.closed`), never by this code.
76    pub const MODULE_RELOADING: &str = "module_reloading";
77    pub const MODULE_WARMING: &str = "module_warming";
78    pub const TARGET_UNAVAILABLE: &str = "target_unavailable";
79    /// A flow-scoped route targets a module that does not provide
80    /// either `flow-scopes/v1` or `call-modes/v1`. TERMINAL: decoding `flow_id`
81    /// alone does not promise flow behaviour, and removing it would silently
82    /// change the identity.
83    pub const TARGET_FLOW_UNSUPPORTED: &str = "target_flow_unsupported";
84    /// An agent-run-scoped route targets a module providing neither
85    /// `agent-run-scopes/v1` nor `call-modes/v1`, or a delegating run targets a
86    /// module without `call-modes/v1`. TERMINAL: removing `run_id` or delegation
87    /// would silently change the identity or authority under which the route acts.
88    pub const TARGET_AGENT_RUN_UNSUPPORTED: &str = "target_agent_run_unsupported";
89    pub const MODULE_TIMEOUT: &str = "module_timeout";
90    /// The target module is declared as speaking no subc wire protocol
91    /// (`protocol: "none"` in daemon config), so it has no control lane and can
92    /// never accept a route. The daemon supervises its process and nothing else.
93    ///
94    /// TERMINAL, and deliberately neither of its two neighbours. It is not
95    /// `unknown_module`, which means "no module of this id is registered or
96    /// supervised here" and is likewise terminal; retrying here would storm the
97    /// daemon forever, because the answer is a property of the module's
98    /// declaration rather than of its current state. It is not `module_removed` either: the module is configured,
99    /// running, and supervised. Only an edit to its configuration can change
100    /// this answer, and a caller cannot wait that out.
101    pub const MODULE_NO_PROTOCOL: &str = "module_no_protocol";
102    /// A request field is malformed. The error's `detail.field` names the field
103    /// (for a `route.open`, `role_versions`). TERMINAL: the same request will be
104    /// refused the same way every time, so only a corrected request can succeed.
105    pub const INVALID_REQUEST: &str = "invalid_request";
106
107    /// A `route.open` named a scope whose owner is configured but has not
108    /// synced since this daemon incarnation started. RETRYABLE: after a daemon
109    /// restart a carrier's open can arrive before the owner re-syncs, and the
110    /// carrier waits within its own deadline. See `docs/designs/daemon-scopes.md`.
111    pub const SCOPE_NOT_SYNCED: &str = "scope_not_synced";
112    /// A scoped `route.open` was admitted, but the scope record changed before
113    /// the module's bind committed. Nothing was sent on the route, so the caller
114    /// may re-open against the current record: RETRYABLE.
115    pub const SCOPE_CHANGED: &str = "scope_changed";
116    /// A scoped `route.open` named no `scope_epoch`. Every opener names one,
117    /// the owner included, so an old call can never be carried into a newer
118    /// session that reused the ref. TERMINAL.
119    pub const SCOPE_EPOCH_REQUIRED: &str = "scope_epoch_required";
120    /// A scoped `route.open` named a ref the owner's synced set does not hold,
121    /// or an owner that is not a configured module. TERMINAL.
122    pub const SCOPE_NOT_LIVE: &str = "scope_not_live";
123    /// A scoped `route.open` named a `scope_epoch` that is not the live one, or
124    /// the scope ended between admission and commit. TERMINAL.
125    pub const SCOPE_ENDED: &str = "scope_ended";
126    /// The opener of a scoped `route.open` is neither the scope's owner nor a
127    /// listed carrier, or it is a targeted carrier and the target module is not
128    /// in its list. TERMINAL.
129    pub const SCOPE_NOT_CARRIER: &str = "scope_not_carrier";
130    /// A scope with a bind-proof hash requires every opener, including its
131    /// owner, to present the proof. TERMINAL.
132    pub const SCOPE_BIND_PROOF_REQUIRED: &str = "scope_bind_proof_required";
133    /// The proof is malformed or does not match the scope's hash. TERMINAL.
134    pub const SCOPE_BIND_PROOF_MISMATCH: &str = "scope_bind_proof_mismatch";
135    /// An idle-only epoch/proof replacement found routes, admitted binds or
136    /// connected presence under the live epoch. Per-record refusal. TERMINAL.
137    pub const SCOPE_EPOCH_IN_USE: &str = "scope_epoch_in_use";
138    /// Raised by a carrier, never by the daemon: the daemon does not advertise
139    /// `scopes/v1`, so the carrier fails the call instead of opening an
140    /// unscoped route.
141    pub const SCOPE_UNSUPPORTED: &str = "scope_unsupported";
142
143    /// `scope.sync` or `scope.apply` came from a connection that is not the
144    /// owner's sync authority: another connection of the same launch holds it,
145    /// or this connection's launch is no longer the owner's current one (a
146    /// blue/green swap candidate before cutover, or an incumbent after it).
147    pub const SCOPE_SYNC_NOT_AUTHORITY: &str = "scope_sync_not_authority";
148    /// `scope.apply` came from a connection that has not taken sync authority
149    /// through an accepted full `scope.sync`. The whole call changes nothing.
150    pub const SCOPE_SYNC_REQUIRED: &str = "scope_sync_required";
151    /// `scope.sync` or `scope.apply` carried a generation no larger than the last
152    /// one the authority accepted. The whole call is refused and nothing changes.
153    pub const SCOPE_SYNC_STALE: &str = "scope_sync_stale";
154    /// `scope.sync` or `scope.apply` exceeds the owner's live-scope limit.
155    /// The whole call is refused and nothing changes.
156    pub const SCOPE_LIVE_LIMIT_EXCEEDED: &str = "scope_live_limit_exceeded";
157    /// One record in a `scope.sync` or `scope.apply` carried more attribute bytes
158    /// than a scope may hold. The whole call is refused and nothing changes.
159    pub const SCOPE_ATTRIBUTES_TOO_LARGE: &str = "scope_attributes_too_large";
160
161    // Per-record refusals: each is reported against one record in the
162    // `scope.sync` or `scope.apply` reply. A refusal itself does not change the
163    // ref or undo expiry processing; other records in the call still apply.
164
165    /// The record lowers the `scope_epoch` the daemon holds for its ref.
166    pub const SCOPE_EPOCH_REGRESSED: &str = "scope_epoch_regressed";
167    /// The record names an `(owner, ref, scope_epoch)` that already ended in
168    /// this daemon incarnation; an ended session cannot come back.
169    pub const SCOPE_EPOCH_ENDED: &str = "scope_epoch_ended";
170    /// The record's deadline has passed, or this ref at this epoch was ended by
171    /// expiry and its tombstone is still held. The same session epoch cannot
172    /// return.
173    pub const SCOPE_EXPIRED: &str = "scope_expired";
174    /// The record adds, removes or changes the deadline of a live scope at the
175    /// same epoch. A different deadline requires a new session epoch.
176    pub const SCOPE_EXPIRY_IMMUTABLE: &str = "scope_expiry_immutable";
177    /// The record's deadline is more than `scope::MAX_SCOPE_EXPIRY_AHEAD_MS`
178    /// ahead of the daemon's current Unix wall clock.
179    pub const SCOPE_EXPIRY_TOO_FAR: &str = "scope_expiry_too_far";
180    /// The record changes `kind` at the same `scope_epoch`.
181    pub const SCOPE_KIND_CHANGED: &str = "scope_kind_changed";
182    pub const INVALID_WORKDIR: &str = "invalid_workdir";
183    pub const SCOPE_WORKDIR_CHANGED: &str = "scope_workdir_changed";
184    /// Installed flow identity cannot be added, changed or removed within an epoch.
185    pub const SCOPE_FLOW_IDENTITY_CHANGED: &str = "scope_flow_identity_changed";
186    pub const SCOPE_PROJECT_CHANGED: &str = "scope_project_changed";
187    /// The record sets authority-controlled attributes and its owner is not
188    /// listed in `scope_authority_owners`, or combines `on_behalf_of_agent` with
189    /// `agent_id`, `delegates`, `flow_id` or `run_id`, or supplies an incomplete
190    /// installed flow identity or one without `flow_id`.
191    pub const SCOPE_ATTRIBUTE_NOT_PERMITTED: &str = "scope_attribute_not_permitted";
192    /// The record's parent link is not permitted: the parent's owner has synced
193    /// and the parent is not live at the named epoch, the syncing owner is
194    /// neither the parent's owner nor in its `child_owners`, or the link would
195    /// close a cycle.
196    pub const SCOPE_PARENT_NOT_PERMITTED: &str = "scope_parent_not_permitted";
197    /// A targeted carrier entry lists no target modules, or more than
198    /// `scope::MAX_CARRIER_TARGETS`.
199    pub const SCOPE_CARRIER_TARGETS_INVALID: &str = "scope_carrier_targets_invalid";
200    /// The record sets `delegates` without an `agent_id` to delegate.
201    pub const SCOPE_DELEGATES_WITHOUT_AGENT: &str = "scope_delegates_without_agent";
202    /// The record sets `run_id` without `agent_id`, the agent this run is on
203    /// behalf of.
204    pub const SCOPE_RUN_ID_WITHOUT_AGENT: &str = "scope_run_id_without_agent";
205    /// The record sets both `run_id` and `flow_id`; a run scope is not a flow scope.
206    pub const SCOPE_RUN_ID_WITH_FLOW_ID: &str = "scope_run_id_with_flow_id";
207    /// Legacy refusal for a record setting `run_id` with `delegates`.
208    /// No longer emitted by validation: run records may delegate, and route
209    /// admission instead requires a target providing `call-modes/v1`.
210    pub const SCOPE_RUN_ID_DELEGATES: &str = "scope_run_id_delegates";
211
212    /// An `operator.confirm` was declined or withdrawn. `detail.reason` is
213    /// `person`, `backoff`, `route_closed`, `module_closed` or `caller_cancelled`.
214    pub const OPERATOR_DECLINED: &str = "operator_declined";
215    /// An `operator.confirm` could not prompt or complete. `detail.reason` is
216    /// `no_presence`, `timeout`, `module_limit`, `queue_full`, `queue_wait`,
217    /// `provider_stuck`, `unsupported_platform` or `provider_error`.
218    pub const OPERATOR_PRESENCE_UNAVAILABLE: &str = "operator_presence_unavailable";
219    /// The summary of an `operator.confirm` breaks the daemon's summary rules.
220    pub const OPERATOR_SUMMARY_INVALID: &str = "operator_summary_invalid";
221    /// An `operator.confirm` is not from a nonce-proven module connection for
222    /// an open route with a verified opener on that connection.
223    pub const OPERATOR_REQUEST_NOT_PERMITTED: &str = "operator_request_not_permitted";
224
225    /// Whether a `route.open` refusal carrying `code` may be retried in place
226    /// within the caller's deadline, or is terminal for the target as named.
227    ///
228    /// This lives beside the codes because every consumer with its own
229    /// connection layer needs the same answer: a copied list breaks loudly on
230    /// a renamed code and silently on an added one. The SDKs call this; the
231    /// golden `decision_tables.json` (`route_open_retryable`) is the record
232    /// the daemon and every SDK are tested against, and the test in
233    /// `golden_json.rs` holds this function to it.
234    ///
235    /// Unknown codes are terminal: a refusal this crate has never heard of
236    /// must not be retried on the strength of a match-all arm.
237    ///
238    /// `unknown_module` is terminal: it now means only "no module of this id
239    /// is registered or supervised here" — a typo, or a peer not deployed on
240    /// this host. The daemon reports a configured-but-late target with its own
241    /// retryable codes (`module_warming`, `target_unavailable`), so a caller
242    /// that races an unsupervised module's HELLO owns its own retry; retrying
243    /// in place only papers over that race for one narrow window.
244    pub fn is_retryable_route_open(code: &str) -> bool {
245        if matches!(
246            code,
247            TARGET_FLOW_UNSUPPORTED
248                | TARGET_AGENT_RUN_UNSUPPORTED
249                | SCOPE_BIND_PROOF_REQUIRED
250                | SCOPE_BIND_PROOF_MISMATCH
251                | SCOPE_EPOCH_IN_USE
252        ) {
253            return false;
254        }
255        matches!(
256            code,
257            MODULE_RELOADING
258                | MODULE_WARMING
259                | TARGET_UNAVAILABLE
260                | MODULE_TIMEOUT
261                | SCOPE_NOT_SYNCED
262                | SCOPE_CHANGED
263        )
264    }
265
266    /// Whether the caller should evict this established route, reopen it, and
267    /// resend the request once. Consumers mapping route death to their own
268    /// custody, provider, or suspect verdict keep their own named code lists;
269    /// sharing this predicate for those meanings can change a verdict on a
270    /// protocol bump (prefrontal#59).
271    ///
272    /// Takes envelope flags so the daemon-origin check can be enabled here in
273    /// one place. Phase 2 requires first that every daemon a consumer can meet
274    /// sets DAEMON_ORIGIN on these error frames, both landed and deployed;
275    /// only then may this predicate require the bit. Requiring it sooner makes
276    /// a new SDK against an older daemon stop evicting on a genuine
277    /// `stale_route_epoch` — the failure this predicate is meant to prevent.
278    ///
279    /// The daemon emits these codes in `RouterError::to_error_frame` at
280    /// `crates/subc-daemon/src/router.rs` (UnknownChannel and StaleRouteEpoch).
281    pub fn is_established_route_dead(_flags: Flags, code: &str) -> bool {
282        matches!(code, UNKNOWN_CHANNEL | STALE_ROUTE_EPOCH)
283    }
284}
285
286pub use frame::{Frame, FrameBuildError};
287
288/// Why subc is closing a module's client routes.
289#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
290#[serde(rename_all = "snake_case")]
291pub enum RouteCloseReason {
292    Reload,
293    Restart,
294    Disable,
295    Crash,
296    /// A live route became forbidden because newly attested capability metadata
297    /// matched its supervised opening module's deny edge.
298    CapabilityDenied,
299    /// The route's scope ended: it expired, its owner ended it, or replaced it
300    /// with a higher `scope_epoch` (a new session under the same ref).
301    ScopeEnded,
302    /// The route's opener is no longer a listed carrier of its scope, or the
303    /// route's target was removed from that carrier's target list.
304    ScopeCarrierRemoved,
305    /// The scope's `delegates` went from true to false, or its `agent_id`,
306    /// `on_behalf_of_agent`, `flow_id` or `run_id` changed.
307    ScopeDelegationChanged,
308    /// The scope's parent ended, so its stamp no longer names a live parent.
309    ScopeParentEnded,
310}
311
312/// Per-route bind identity shared by client-facing and module-facing control.
313///
314/// EVERY FIELD HERE IS CLIENT-SUPPLIED AND UNATTESTED. The daemon canonicalizes
315/// `project_root` as a path but does not verify that the caller has any relation
316/// to it, and `harness`, `session`, and `project_id` are strings the caller chose.
317/// A client holding the connection key can present any values it likes.
318///
319/// This sits directly above `Principal`, which is the opposite: stamped BY the
320/// daemon from a launch nonce it minted. The two travel together on every
321/// `route.bind`, so a module reading them side by side is reading one fact it can
322/// trust and four it cannot. THE DISTINCTION IS INVISIBLE FROM THE TYPES, which
323/// is why it is written here.
324///
325/// So these fields are for SCOPING AND ATTRIBUTION -- which project's state to
326/// open, which session to thread, what to log -- and never for authorization. A
327/// module that grants capability on `harness` or trusts `project_root` to bound
328/// what a caller may reach has built an authorization check on a value the caller
329/// controls. Gate on `Principal` instead, and where a module needs a caller fact
330/// subc does not stamp, it must establish that fact itself rather than believe
331/// this struct.
332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
333#[non_exhaustive]
334pub struct BindIdentity {
335    pub project_root: PathBuf,
336    pub harness: String,
337    pub session: String,
338    /// The entorhinal-registered project id (`pj-…`) for `project_root`, when
339    /// the root is a registered project. Aliases count as registered projects;
340    /// implicit roots do not. Absent means "no stable id, key on the triple",
341    /// not "unknown".
342    ///
343    /// A producer sends the id on every bind of a session or on none. A producer
344    /// that alternates between `Some(id)` and `None` across binds silently forks
345    /// the consumer's lineage into separate stores, with no error at either end.
346    /// Therefore, a producer that cannot answer consistently must answer `None`
347    /// consistently.
348    ///
349    /// Resolve this at most once per session, before its first bind, and persist
350    /// the outcome with the session. ALF's resolver has real `Resolved`, `Unavailable`,
351    /// and `Disabled` outcomes: if unavailable at cold start is re-resolved on a
352    /// later bind, the session can alternate from `None` to `Some(id)`. Send only
353    /// registered or alias resolutions, never implicit, unavailable, or disabled
354    /// fallback ids.
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub project_id: Option<String>,
357}
358
359impl BindIdentity {
360    /// Constructs an identity with no registered project id.
361    ///
362    /// Use this instead of a struct literal so future additive identity fields do
363    /// not force construction-site migrations across the fleet.
364    pub fn new(
365        project_root: impl Into<PathBuf>,
366        harness: impl Into<String>,
367        session: impl Into<String>,
368    ) -> Self {
369        Self {
370            project_root: project_root.into(),
371            harness: harness.into(),
372            session: session.into(),
373            project_id: None,
374        }
375    }
376}
377
378/// Caller fact stamped by subc on each route.bind relayed to a module.
379#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
380#[serde(tag = "kind", rename_all = "snake_case")]
381pub enum Principal {
382    /// A daemon-spawned module proved possession of its launch nonce.
383    Reserved { module_id: String },
384    /// No consumer identity was presented; the caller is a direct key-holder.
385    Direct,
386    /// Reserved vocabulary for a future degraded/no-key-auth mode.
387    Unverified,
388}
389
390/// Explicit target for a route open/bind operation.
391///
392/// RouteTarget.kind ↔ ProviderRole mapping:
393///
394/// | RouteTarget.kind | required ProviderRole | disambiguator |
395/// |---|---|---|
396/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
397/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
398/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
399///
400/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
401/// are wired by an orchestrator rather than opened directly by clients.
402#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
403#[serde(tag = "kind", rename_all = "snake_case")]
404pub enum RouteTarget {
405    ToolProvider {
406        module_id: String,
407    },
408    ManagementSurface {
409        module_id: String,
410    },
411    InternalService {
412        module_id: String,
413        service_id: String,
414    },
415}
416
417/// Envelope protocol version this build speaks.
418pub const PROTOCOL_VERSION: u8 = 2;
419
420/// The version of THIS crate (`subc-protocol`) as compiled into the linking
421/// binary — the fleet's shared wire-vocabulary version, and the value
422/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
423/// module's own envelope or payload crates: those are different numbering
424/// spaces, and declaring one here produces a confident wrong answer at any
425/// version gate (insula shipped exactly that before the referent was written
426/// down). `env!` makes it a property of the compiled binary, not of whatever
427/// source tree sits beside it at run time.
428pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
429
430/// Oldest envelope protocol version this build accepts.
431pub const MIN_SUPPORTED_VERSION: u8 = 2;
432
433/// Env var subc sets on each supervised child telling it the module_id it is
434/// supervised under, so it can register under that id.
435pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
436
437/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
438/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
439/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
440/// last injected for that id. Non-reserved modules never receive it.
441pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
442
443/// Fixed header length for `PROTOCOL_VERSION` 2.
444pub const HEADER_LEN: usize = 21;
445
446/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
447/// every envelope version. A reader needs only these to learn the version and
448/// thus the full header length.
449pub const FROZEN_PREFIX_LEN: usize = 5;
450
451/// Maximum frame body accepted before allocation.
452///
453/// This 64 MiB starting cap prevents a malformed header from forcing an
454/// unbounded allocation. Future protocol versions can negotiate or encode a
455/// different cap while preserving the frozen prefix.
456pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
457
458/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
459/// to a client: a reply, stream frame, error, reverse request or push. A module
460/// sizes what it sends to a client against this, not against
461/// `MAX_FRAME_BODY_LEN`.
462///
463/// A larger module frame is never forwarded to the client. A reply, stream
464/// frame or error that is too large ends its request with a `frame_too_large`
465/// error; a reverse request that is too large is answered with an error to the
466/// module; an unsolicited push that is too large closes the client connection.
467///
468/// Requests from a client to a module are not held to this limit; they are
469/// bounded only by `MAX_FRAME_BODY_LEN`.
470pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
471
472/// Canonical JSON body for all subc-generated `ERROR` frames.
473///
474/// `detail` is an optional machine-parsable surface for refusals whose remedy
475/// needs more than a code (e.g. a producer-published backoff number, an
476/// observed-vs-configured size pair). Absent detail serializes to nothing, so
477/// bodies without it are byte-identical to the pre-detail wire and older
478/// readers simply never see the field. Producers document each code's detail
479/// fields where the code is defined; `detail` must never carry secrets.
480#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
481pub struct ErrorBody {
482    pub code: String,
483    pub message: String,
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub detail: Option<serde_json::Value>,
486}
487
488impl ErrorBody {
489    /// A detail-less error body; the common case.
490    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
491        Self {
492            code: code.into(),
493            message: message.into(),
494            detail: None,
495        }
496    }
497
498    /// Attach a machine-parsable detail object to this error.
499    pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
500        self.detail = Some(detail);
501        self
502    }
503}
504
505/// Module-to-subc `HELLO` body used during module registration.
506#[derive(Clone, Serialize, Deserialize, PartialEq)]
507pub struct ModuleHelloBody {
508    pub manifest: manifest::ModuleManifest,
509    pub protocol_ver: u8,
510    #[serde(default)]
511    pub control_ops: Option<Vec<String>>,
512    /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
513    /// variable the daemon injected when it spawned this process. Only a daemon-spawned
514    /// process for a `reserved` module receives a nonce; subc accepts a reserved
515    /// `module_id`'s HELLO only when this matches the nonce it last injected for that
516    /// id, so a different process cannot register as a reserved module while the real
517    /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
518    /// self-connecting providers, which are never nonce-checked.
519    #[serde(default, skip_serializing_if = "Option::is_none")]
520    pub launch_nonce: Option<String>,
521}
522
523// Hand-written so the launch nonce is never printed. The nonce is the credential
524// that attributes a connection to a supervised module, and a derived Debug would
525// write it into any log line or panic message that formats this value. Same
526// reasoning as ConnectionInfo's Debug in subc-transport.
527impl fmt::Debug for ModuleHelloBody {
528    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529        f.debug_struct("ModuleHelloBody")
530            .field("manifest", &self.manifest)
531            .field("protocol_ver", &self.protocol_ver)
532            .field("control_ops", &self.control_ops)
533            .field(
534                "launch_nonce",
535                &self
536                    .launch_nonce
537                    .as_ref()
538                    .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
539            )
540            .finish()
541    }
542}
543
544/// subc-to-module `HELLO_ACK` body used during module registration.
545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
546pub struct ModuleHelloAckBody {
547    pub negotiated_ver: u8,
548    pub subc_ops: Vec<String>,
549    pub subc_capabilities: Vec<String>,
550    /// The module's resolved storage descriptor, when the daemon's central config
551    /// configures managed storage. Carried opaquely here (subc-protocol stays a
552    /// thin wire crate with no storage/database dependency); a module that uses
553    /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
554    /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
555    /// `serde(default)` so an older module simply ignores it.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub storage: Option<serde_json::Value>,
558    /// The daemon's machine id (see [`MachineId`]): a name for this machine,
559    /// never an authority. Nothing may admit a peer, grant trust or skip a check
560    /// because two messages carry the same value.
561    ///
562    /// Carried as a plain string so one malformed value cannot fail the whole
563    /// registration reply; a module validates it with [`MachineId::parse`].
564    /// Absent from a daemon that predates the machine id, which a module must
565    /// read as exactly that, never as "no machine" and never as a reason to mint
566    /// its own.
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub machine_id: Option<String>,
569}
570
571/// Frame kind (`type` byte at offset 5).
572///
573/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
574/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576#[repr(u8)]
577pub enum FrameType {
578    Request = 0,
579    Response = 1,
580    Push = 2,
581    StreamData = 3,
582    StreamEnd = 4,
583    Error = 5,
584    Cancel = 6,
585    Ping = 7,
586    Pong = 8,
587    Hello = 9,
588    HelloAck = 10,
589    Goodbye = 11,
590}
591
592impl FrameType {
593    /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
594    pub fn from_u8(b: u8) -> Option<Self> {
595        Some(match b {
596            0 => Self::Request,
597            1 => Self::Response,
598            2 => Self::Push,
599            3 => Self::StreamData,
600            4 => Self::StreamEnd,
601            5 => Self::Error,
602            6 => Self::Cancel,
603            7 => Self::Ping,
604            8 => Self::Pong,
605            9 => Self::Hello,
606            10 => Self::HelloAck,
607            11 => Self::Goodbye,
608            _ => return None,
609        })
610    }
611
612    pub fn is_pure_header(self) -> bool {
613        matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
614    }
615}
616
617/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
618/// without parsing the body.
619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
620#[repr(u8)]
621pub enum Priority {
622    Passive = 0,
623    Interactive = 1,
624    Background = 2,
625}
626
627impl Priority {
628    fn from_bits(bits: u8) -> Option<Self> {
629        Some(match bits {
630            0 => Self::Passive,
631            1 => Self::Interactive,
632            2 => Self::Background,
633            _ => return None,
634        })
635    }
636}
637
638/// Admission behavior carried in `flags` bits 4-5.
639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
640#[repr(u8)]
641pub enum AdmissionClass {
642    Normal = 0,
643    Expedite = 1,
644    Sheddable = 2,
645}
646
647impl AdmissionClass {
648    fn from_bits(bits: u8) -> Option<Self> {
649        Some(match bits {
650            0 => Self::Normal,
651            1 => Self::Expedite,
652            2 => Self::Sheddable,
653            _ => return None,
654        })
655    }
656}
657
658const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
659const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
660const FLAG_PRIORITY_SHIFT: u8 = 1;
661const FLAG_LAST: u8 = 0b0000_1000; // bit 3
662const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
663const FLAG_ADMISSION_SHIFT: u8 = 4;
664pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
665/// A request credit the client explicitly declares as a held-open subscription.
666pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
667
668/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
670pub struct Flags(pub u8);
671
672impl Flags {
673    /// Build flags with the default [`AdmissionClass::Normal`] class.
674    pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
675        let mut b = 0u8;
676        if binary {
677            b |= FLAG_BINARY;
678        }
679        b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
680        if last {
681            b |= FLAG_LAST;
682        }
683        Flags(b)
684    }
685
686    /// Return these flags with a typed admission class.
687    pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
688        self.0 =
689            (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
690        self
691    }
692
693    /// Body is raw bytes (bulk lane) rather than JSON-RPC.
694    pub fn is_binary(self) -> bool {
695        self.0 & FLAG_BINARY != 0
696    }
697
698    /// Final frame of a streamed message.
699    pub fn is_last(self) -> bool {
700        self.0 & FLAG_LAST != 0
701    }
702
703    /// Decode the priority bits, or `None` if they hold a reserved value.
704    pub fn priority(self) -> Option<Priority> {
705        Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
706    }
707
708    /// Decode the admission-class bits, or `None` if they hold `0b11`.
709    pub fn admission_class(self) -> Option<AdmissionClass> {
710        AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
711    }
712
713    /// True when a request was explicitly opened as a held-open subscription.
714    pub fn is_subscription(self) -> bool {
715        self.0 & FLAG_SUBSCRIPTION != 0
716    }
717
718    /// True when the frame was authored by the daemon.
719    pub fn is_daemon_origin(self) -> bool {
720        self.0 & FLAG_DAEMON_ORIGIN != 0
721    }
722
723    /// Return these flags with daemon origin asserted.
724    pub fn with_daemon_origin(mut self) -> Self {
725        self.0 |= FLAG_DAEMON_ORIGIN;
726        self
727    }
728
729    /// Return these flags with daemon origin cleared.
730    pub fn without_daemon_origin(self) -> Self {
731        Self(self.0 & !FLAG_DAEMON_ORIGIN)
732    }
733}
734
735/// A decoded envelope header. The body is the `len` bytes that follow it.
736#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737pub struct EnvelopeHeader {
738    /// Number of body bytes after the header.
739    pub len: u32,
740    /// Envelope version.
741    pub ver: u8,
742    /// Frame kind.
743    pub ty: FrameType,
744    /// Flag bits.
745    pub flags: Flags,
746    /// Sender-local route slot; 0 is the control channel.
747    pub channel: u16,
748    /// Sender-local binding epoch; 0 is reserved for the control channel.
749    pub epoch: u32,
750    /// Correlation id.
751    pub corr: u64,
752}
753
754impl EnvelopeHeader {
755    /// Serialize the header to its fixed 21-byte little-endian form.
756    pub fn encode(&self) -> [u8; HEADER_LEN] {
757        let mut buf = [0u8; HEADER_LEN];
758        buf[0..4].copy_from_slice(&self.len.to_le_bytes());
759        buf[4] = self.ver;
760        buf[5] = self.ty as u8;
761        buf[6] = self.flags.0;
762        buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
763        buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
764        buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
765        buf
766    }
767}
768
769/// Why a header could not be decoded.
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
771pub enum DecodeError {
772    /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
773    TooShortForPrefix { have: usize },
774    /// `ver` is not a version this build understands.
775    UnsupportedVersion { ver: u8 },
776    /// Version known but fewer than its header length is present.
777    TooShortForHeader { have: usize, need: usize },
778    /// `type` byte is not a known `FrameType`.
779    UnknownFrameType { byte: u8 },
780    /// A reserved flag bit is set (retained for older decoder error compatibility).
781    ReservedFlagBits { flags: u8 },
782    /// Priority bits 1-2 hold the reserved value `0b11`.
783    ReservedPriorityBits { flags: u8 },
784    /// Admission bits 4-5 hold the reserved value `0b11`.
785    ReservedAdmissionClass { flags: u8 },
786    /// SHEDDABLE is set on a frame type that must be delivered.
787    SheddableIllegalFrameType { ty: FrameType, flags: u8 },
788    /// Channel 0 carried an epoch other than its reserved epoch 0.
789    NonzeroEpochOnControlChannel { epoch: u32 },
790    /// A pure-header frame declared body bytes.
791    PureHeaderFrameWithBody { ty: FrameType, len: u32 },
792}
793
794impl fmt::Display for DecodeError {
795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796        match self {
797            Self::TooShortForPrefix { have } => {
798                write!(f, "header shorter than frozen prefix: have {have} bytes")
799            }
800            Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
801            Self::TooShortForHeader { have, need } => {
802                write!(
803                    f,
804                    "header too short for version: have {have} bytes, need {need}"
805                )
806            }
807            Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
808            Self::ReservedFlagBits { flags } => {
809                write!(f, "reserved flag bits set in flags 0b{flags:08b}")
810            }
811            Self::ReservedPriorityBits { flags } => {
812                write!(f, "reserved priority bits set in flags 0b{flags:08b}")
813            }
814            Self::ReservedAdmissionClass { flags } => {
815                write!(f, "reserved admission class set in flags 0b{flags:08b}")
816            }
817            Self::SheddableIllegalFrameType { ty, flags } => write!(
818                f,
819                "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
820            ),
821            Self::NonzeroEpochOnControlChannel { epoch } => {
822                write!(f, "control channel carried nonzero epoch {epoch}")
823            }
824            Self::PureHeaderFrameWithBody { ty, len } => {
825                write!(
826                    f,
827                    "pure-header frame {ty:?} declared non-zero body length {len}"
828                )
829            }
830        }
831    }
832}
833
834impl Error for DecodeError {}
835
836/// How many header bytes a given envelope version occupies. Driven by the
837/// frozen prefix: read `ver`, then learn the full header length here.
838fn header_len_for_version(ver: u8) -> Option<usize> {
839    match ver {
840        PROTOCOL_VERSION => Some(HEADER_LEN),
841        _ => None,
842    }
843}
844
845/// Decode an envelope header from the front of `bytes`, following the
846/// frozen-prefix discipline:
847/// 1. need at least the 5-byte prefix to read `len` + `ver`;
848/// 2. dispatch the full header length on `ver`;
849/// 3. need the full header present; then parse the rest.
850///
851/// Never panics on malformed input — returns a typed [`DecodeError`].
852pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
853    if bytes.len() < FROZEN_PREFIX_LEN {
854        return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
855    }
856    let ver = bytes[4];
857    let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
858    if bytes.len() < need {
859        return Err(DecodeError::TooShortForHeader {
860            have: bytes.len(),
861            need,
862        });
863    }
864
865    let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
866    let ty =
867        FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
868    let flags = Flags(bytes[6]);
869    if flags.priority().is_none() {
870        return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
871    }
872    let admission_class = flags
873        .admission_class()
874        .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
875    if admission_class == AdmissionClass::Sheddable
876        && !matches!(ty, FrameType::Push | FrameType::StreamData)
877    {
878        return Err(DecodeError::SheddableIllegalFrameType {
879            ty,
880            flags: bytes[6],
881        });
882    }
883    if ty.is_pure_header() && len != 0 {
884        return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
885    }
886    let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
887    let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
888    if channel == 0 && epoch != 0 {
889        return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
890    }
891    let corr = u64::from_le_bytes([
892        bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
893    ]);
894
895    Ok(EnvelopeHeader {
896        len,
897        ver,
898        ty,
899        flags,
900        channel,
901        epoch,
902        corr,
903    })
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909
910    fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
911        hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
912    }
913
914    fn hdr_with_epoch(
915        len: u32,
916        ty: FrameType,
917        flags: Flags,
918        channel: u16,
919        epoch: u32,
920        corr: u64,
921    ) -> EnvelopeHeader {
922        EnvelopeHeader {
923            len,
924            ver: PROTOCOL_VERSION,
925            ty,
926            flags,
927            channel,
928            epoch,
929            corr,
930        }
931    }
932
933    /// Modules size their replies against this limit and the TypeScript and
934    /// Swift clients mirror it, so changing it must be a deliberate edit here
935    /// as well as in the constant.
936    #[test]
937    fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
938        assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
939    }
940
941    #[test]
942    fn bind_identity_with_project_id_round_trips_json() {
943        let mut identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
944        identity.project_id = Some("pj-a1b2c3d4".to_string());
945
946        let encoded = serde_json::to_vec(&identity).unwrap();
947        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
948
949        assert_eq!(decoded, identity);
950    }
951
952    #[test]
953    fn bind_identity_without_project_id_round_trips_json() {
954        let identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
955
956        let encoded = serde_json::to_vec(&identity).unwrap();
957        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
958
959        assert_eq!(decoded, identity);
960    }
961
962    #[test]
963    fn legacy_bind_identity_without_project_id_decodes() {
964        let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
965            "project_root": "/tmp/project",
966            "harness": "opencode",
967            "session": "session-1"
968        }))
969        .unwrap();
970
971        assert_eq!(decoded.project_id, None);
972    }
973
974    #[test]
975    fn bind_identity_none_omits_project_id_instead_of_serializing_null() {
976        let encoded =
977            serde_json::to_value(BindIdentity::new("/tmp/project", "opencode", "session-1"))
978                .unwrap();
979
980        assert!(encoded.get("project_id").is_none());
981    }
982
983    #[test]
984    fn wire_crate_version_is_a_numeric_three_component_version() {
985        let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
986
987        assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
988        assert_eq!(components.len(), 3);
989        assert!(components
990            .iter()
991            .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
992    }
993
994    #[test]
995    fn route_target_variants_round_trip_json() {
996        let targets = [
997            RouteTarget::ToolProvider {
998                module_id: "aft".to_string(),
999            },
1000            RouteTarget::ManagementSurface {
1001                module_id: "memory".to_string(),
1002            },
1003            RouteTarget::InternalService {
1004                module_id: "bus".to_string(),
1005                service_id: "dm".to_string(),
1006            },
1007        ];
1008
1009        for target in targets {
1010            let encoded = serde_json::to_vec(&target).unwrap();
1011            let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
1012            assert_eq!(decoded, target);
1013        }
1014    }
1015
1016    #[test]
1017    fn error_body_round_trips_json() {
1018        let body = ErrorBody {
1019            code: "config_divergence".to_string(),
1020            message: "active config differs".to_string(),
1021            detail: None,
1022        };
1023
1024        let encoded = serde_json::to_vec(&body).unwrap();
1025        let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1026
1027        assert_eq!(decoded, body);
1028    }
1029
1030    #[test]
1031    fn round_trip_request() {
1032        let h = hdr(
1033            1234,
1034            FrameType::Request,
1035            Flags::new(false, Priority::Interactive, false),
1036            42,
1037            0xDEAD_BEEF_0000_0001,
1038        );
1039        let decoded = decode_header(&h.encode()).unwrap();
1040        assert_eq!(h, decoded);
1041    }
1042
1043    #[test]
1044    fn round_trip_all_frame_types() {
1045        for b in 0u8..=11 {
1046            let ty = FrameType::from_u8(b).unwrap();
1047            let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1048            assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1049        }
1050    }
1051
1052    #[test]
1053    fn pure_header_frame_has_zero_len() {
1054        // CANCEL carries only header (len = 0) + the target corr.
1055        let h = hdr(
1056            0,
1057            FrameType::Cancel,
1058            Flags::new(false, Priority::Passive, false),
1059            7,
1060            99,
1061        );
1062        let d = decode_header(&h.encode()).unwrap();
1063        assert_eq!(d.len, 0);
1064        assert_eq!(d.corr, 99);
1065    }
1066
1067    #[test]
1068    fn flags_round_trip() {
1069        let f = Flags::new(true, Priority::Background, true)
1070            .with_admission_class(AdmissionClass::Expedite);
1071        assert!(f.is_binary());
1072        assert!(f.is_last());
1073        assert_eq!(f.priority(), Some(Priority::Background));
1074        assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1075        let h = hdr(8, FrameType::StreamData, f, 1, 1);
1076        assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1077    }
1078
1079    #[test]
1080    fn daemon_origin_flags_decode_and_round_trip() {
1081        let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1082        let old_decoded = decode_header(&old.encode()).unwrap();
1083        assert!(!old_decoded.flags.is_daemon_origin());
1084
1085        let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1086        let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1087        assert!(daemon_decoded.flags.is_daemon_origin());
1088        assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1089        assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1090    }
1091
1092    #[test]
1093    fn little_endian_and_frozen_prefix_layout() {
1094        let h = hdr_with_epoch(
1095            0x0403_0201,
1096            FrameType::Request,
1097            Flags(0),
1098            0x0605,
1099            0x0a09_0807,
1100            0x1211_100f_0e0d_0c0b,
1101        );
1102        let buf = h.encode();
1103        assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1104        assert_eq!(buf[4], PROTOCOL_VERSION);
1105        assert_eq!(&buf[7..9], &[5, 6]);
1106        assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1107        assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1108        assert_eq!(buf.len(), HEADER_LEN);
1109    }
1110
1111    #[test]
1112    fn reject_too_short_for_prefix() {
1113        assert_eq!(
1114            decode_header(&[0, 0, 0, 0]),
1115            Err(DecodeError::TooShortForPrefix { have: 4 })
1116        );
1117    }
1118
1119    #[test]
1120    fn reject_too_short_for_header() {
1121        // Valid 5-byte prefix but the v2 header is truncated.
1122        let mut b = [0u8; 10];
1123        b[4] = PROTOCOL_VERSION;
1124        assert_eq!(
1125            decode_header(&b),
1126            Err(DecodeError::TooShortForHeader {
1127                have: 10,
1128                need: HEADER_LEN
1129            })
1130        );
1131    }
1132
1133    #[test]
1134    fn reject_unsupported_version() {
1135        let mut b = [0u8; HEADER_LEN];
1136        b[4] = 1;
1137        assert_eq!(
1138            decode_header(&b),
1139            Err(DecodeError::UnsupportedVersion { ver: 1 })
1140        );
1141    }
1142
1143    #[test]
1144    fn reject_unknown_frame_type() {
1145        let mut b = [0u8; HEADER_LEN];
1146        b[4] = PROTOCOL_VERSION;
1147        b[5] = 99;
1148        assert_eq!(
1149            decode_header(&b),
1150            Err(DecodeError::UnknownFrameType { byte: 99 })
1151        );
1152    }
1153
1154    #[test]
1155    fn subscription_flag_decodes_and_tags_the_request() {
1156        let mut b = [0u8; HEADER_LEN];
1157        b[4] = PROTOCOL_VERSION;
1158        b[5] = FrameType::Request as u8;
1159        b[6] = FLAG_SUBSCRIPTION;
1160        let decoded = decode_header(&b).unwrap();
1161        assert!(decoded.flags.is_subscription());
1162    }
1163
1164    #[test]
1165    fn reject_reserved_priority_bits() {
1166        let mut b = [0u8; HEADER_LEN];
1167        b[4] = PROTOCOL_VERSION;
1168        b[5] = FrameType::Request as u8;
1169        b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1170        assert_eq!(
1171            decode_header(&b),
1172            Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1173        );
1174    }
1175
1176    #[test]
1177    fn reject_pure_header_frame_with_body_len() {
1178        let h = hdr(
1179            1,
1180            FrameType::Ping,
1181            Flags::new(false, Priority::Passive, false),
1182            0,
1183            1,
1184        );
1185        assert_eq!(
1186            decode_header(&h.encode()),
1187            Err(DecodeError::PureHeaderFrameWithBody {
1188                ty: FrameType::Ping,
1189                len: 1
1190            })
1191        );
1192    }
1193
1194    #[test]
1195    fn epoch_boundaries_round_trip() {
1196        for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1197            let h = hdr_with_epoch(
1198                0,
1199                FrameType::Request,
1200                Flags::new(false, Priority::Passive, false),
1201                channel,
1202                epoch,
1203                9,
1204            );
1205            assert_eq!(decode_header(&h.encode()).unwrap(), h);
1206        }
1207    }
1208
1209    #[test]
1210    fn admission_classes_accept_three_values_and_reject_reserved_value() {
1211        for (ty, admission_class) in [
1212            (FrameType::Request, AdmissionClass::Normal),
1213            (FrameType::Request, AdmissionClass::Expedite),
1214            (FrameType::Push, AdmissionClass::Sheddable),
1215            (FrameType::StreamData, AdmissionClass::Sheddable),
1216        ] {
1217            let flags = Flags::new(false, Priority::Interactive, false)
1218                .with_admission_class(admission_class);
1219            let h = hdr(0, ty, flags, 1, 2);
1220            assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1221        }
1222
1223        let mut h = hdr(
1224            0,
1225            FrameType::Push,
1226            Flags::new(false, Priority::Passive, false),
1227            1,
1228            2,
1229        )
1230        .encode();
1231        h[6] |= 0b0011_0000;
1232        assert_eq!(
1233            decode_header(&h),
1234            Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1235        );
1236    }
1237
1238    #[test]
1239    fn sheddable_rejected_on_every_illegal_frame_type() {
1240        let flags = Flags::new(false, Priority::Passive, false)
1241            .with_admission_class(AdmissionClass::Sheddable);
1242        for ty in [
1243            FrameType::Request,
1244            FrameType::Response,
1245            FrameType::StreamEnd,
1246            FrameType::Error,
1247            FrameType::Cancel,
1248            FrameType::Ping,
1249            FrameType::Pong,
1250            FrameType::Hello,
1251            FrameType::HelloAck,
1252            FrameType::Goodbye,
1253        ] {
1254            let h = hdr(0, ty, flags, 1, 2);
1255            assert_eq!(
1256                decode_header(&h.encode()),
1257                Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1258            );
1259        }
1260    }
1261
1262    #[test]
1263    fn nonzero_epoch_on_control_channel_is_rejected() {
1264        let h = hdr_with_epoch(
1265            0,
1266            FrameType::Request,
1267            Flags::new(false, Priority::Passive, false),
1268            0,
1269            u32::MAX,
1270            2,
1271        );
1272        assert_eq!(
1273            decode_header(&h.encode()),
1274            Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1275        );
1276    }
1277}
1278
1279#[cfg(test)]
1280mod launch_nonce_redaction_tests {
1281    use super::*;
1282
1283    #[test]
1284    fn hello_body_debug_never_prints_the_nonce() {
1285        let body = ModuleHelloBody {
1286            manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1287            protocol_ver: 2,
1288            control_ops: None,
1289            launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1290        };
1291        let printed = format!("{body:?}");
1292        assert!(printed.contains("broca"), "{printed}");
1293        assert!(
1294            !printed.contains("nonce-f00dfeed1234abcd"),
1295            "launch nonce printed: {printed}"
1296        );
1297    }
1298}