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