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