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 frame;
40pub mod machine_id;
41pub mod manifest;
42pub mod session;
43pub mod tool_call;
44
45/// Canonical error codes emitted while opening a client route.
46///
47/// Error frames remain extensible strings, but these daemon-owned route-open
48/// outcomes need identical spelling across the daemon and SDK retry policies.
49pub mod error_codes {
50    pub const UNKNOWN_MODULE: &str = "unknown_module";
51    pub const MODULE_REMOVED: &str = "module_removed";
52    /// The target module's endpoint is draining for a reload, restart or disable.
53    ///
54    /// On the data plane (an `ERROR` frame answering a `REQUEST` on a bound route)
55    /// this code is a PRE-SEND GUARANTEE: the daemon returns it only when the
56    /// request could not take a route credit because the endpoint is draining,
57    /// and it returns it BEFORE forwarding, so the module never received the
58    /// request. A caller may therefore re-dispatch the same request once the
59    /// route is reopened without risking a duplicated side effect, exactly as it
60    /// may after `unknown_channel`. The daemon keeps this guarantee:
61    /// `supervisor_reload_rejects_new_work_during_drain` asserts the module's
62    /// event journal never records the rejected request. A request the module
63    /// already received is answered by the module (or its route closes with
64    /// `route.closed`), never by this code.
65    pub const MODULE_RELOADING: &str = "module_reloading";
66    pub const MODULE_WARMING: &str = "module_warming";
67    pub const TARGET_UNAVAILABLE: &str = "target_unavailable";
68    pub const MODULE_TIMEOUT: &str = "module_timeout";
69    /// The target module is declared as speaking no subc wire protocol
70    /// (`protocol: "none"` in daemon config), so it has no control lane and can
71    /// never accept a route. The daemon supervises its process and nothing else.
72    ///
73    /// TERMINAL, and deliberately neither of its two neighbours. It is not
74    /// `unknown_module`, which means "no module of this id is registered or
75    /// supervised here" and is likewise terminal; retrying here would storm the
76    /// daemon forever, because the answer is a property of the module's
77    /// declaration rather than of its current state. It is not `module_removed` either: the module is configured,
78    /// running, and supervised. Only an edit to its configuration can change
79    /// this answer, and a caller cannot wait that out.
80    pub const MODULE_NO_PROTOCOL: &str = "module_no_protocol";
81
82    /// Whether a `route.open` refusal carrying `code` may be retried in place
83    /// within the caller's deadline, or is terminal for the target as named.
84    ///
85    /// This lives beside the codes because every consumer with its own
86    /// connection layer needs the same answer: a copied list breaks loudly on
87    /// a renamed code and silently on an added one. The SDKs call this; the
88    /// golden `decision_tables.json` (`route_open_retryable`) is the record
89    /// the daemon and every SDK are tested against, and the test in
90    /// `golden_json.rs` holds this function to it.
91    ///
92    /// Unknown codes are terminal: a refusal this crate has never heard of
93    /// must not be retried on the strength of a match-all arm.
94    ///
95    /// `unknown_module` is terminal: it now means only "no module of this id
96    /// is registered or supervised here" — a typo, or a peer not deployed on
97    /// this host. The daemon reports a configured-but-late target with its own
98    /// retryable codes (`module_warming`, `target_unavailable`), so a caller
99    /// that races an unsupervised module's HELLO owns its own retry; retrying
100    /// in place only papers over that race for one narrow window.
101    pub fn is_retryable_route_open(code: &str) -> bool {
102        matches!(
103            code,
104            MODULE_RELOADING | MODULE_WARMING | TARGET_UNAVAILABLE | MODULE_TIMEOUT
105        )
106    }
107}
108
109pub use frame::{Frame, FrameBuildError};
110
111/// Why subc is closing a module's client routes.
112#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
113#[serde(rename_all = "snake_case")]
114pub enum RouteCloseReason {
115    Reload,
116    Restart,
117    Disable,
118    Crash,
119    /// A live route became forbidden because newly attested capability metadata
120    /// matched its supervised opening module's deny edge.
121    CapabilityDenied,
122}
123
124/// Per-route bind identity shared by client-facing and module-facing control.
125///
126/// EVERY FIELD HERE IS CLIENT-SUPPLIED AND UNATTESTED. The daemon canonicalizes
127/// `project_root` as a path but does not verify that the caller has any relation
128/// to it, and `harness`, `session`, and `project_id` are strings the caller chose.
129/// A client holding the connection key can present any values it likes.
130///
131/// This sits directly above `Principal`, which is the opposite: stamped BY the
132/// daemon from a launch nonce it minted. The two travel together on every
133/// `route.bind`, so a module reading them side by side is reading one fact it can
134/// trust and four it cannot. THE DISTINCTION IS INVISIBLE FROM THE TYPES, which
135/// is why it is written here.
136///
137/// So these fields are for SCOPING AND ATTRIBUTION -- which project's state to
138/// open, which session to thread, what to log -- and never for authorization. A
139/// module that grants capability on `harness` or trusts `project_root` to bound
140/// what a caller may reach has built an authorization check on a value the caller
141/// controls. Gate on `Principal` instead, and where a module needs a caller fact
142/// subc does not stamp, it must establish that fact itself rather than believe
143/// this struct.
144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
145#[non_exhaustive]
146pub struct BindIdentity {
147    pub project_root: PathBuf,
148    pub harness: String,
149    pub session: String,
150    /// The entorhinal-registered project id (`pj-…`) for `project_root`, when
151    /// the root is a registered project. Aliases count as registered projects;
152    /// implicit roots do not. Absent means "no stable id, key on the triple",
153    /// not "unknown".
154    ///
155    /// A producer sends the id on every bind of a session or on none. A producer
156    /// that alternates between `Some(id)` and `None` across binds silently forks
157    /// the consumer's lineage into separate stores, with no error at either end.
158    /// Therefore, a producer that cannot answer consistently must answer `None`
159    /// consistently.
160    ///
161    /// Resolve this at most once per session, before its first bind, and persist
162    /// the outcome with the session. ALF's resolver has real `Resolved`, `Unavailable`,
163    /// and `Disabled` outcomes: if unavailable at cold start is re-resolved on a
164    /// later bind, the session can alternate from `None` to `Some(id)`. Send only
165    /// registered or alias resolutions, never implicit, unavailable, or disabled
166    /// fallback ids.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub project_id: Option<String>,
169}
170
171impl BindIdentity {
172    /// Constructs an identity with no registered project id.
173    ///
174    /// Use this instead of a struct literal so future additive identity fields do
175    /// not force construction-site migrations across the fleet.
176    pub fn new(
177        project_root: impl Into<PathBuf>,
178        harness: impl Into<String>,
179        session: impl Into<String>,
180    ) -> Self {
181        Self {
182            project_root: project_root.into(),
183            harness: harness.into(),
184            session: session.into(),
185            project_id: None,
186        }
187    }
188}
189
190/// Caller fact stamped by subc on each route.bind relayed to a module.
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
192#[serde(tag = "kind", rename_all = "snake_case")]
193pub enum Principal {
194    /// A daemon-spawned module proved possession of its launch nonce.
195    Reserved { module_id: String },
196    /// No consumer identity was presented; the caller is a direct key-holder.
197    Direct,
198    /// Reserved vocabulary for a future degraded/no-key-auth mode.
199    Unverified,
200}
201
202/// Explicit target for a route open/bind operation.
203///
204/// RouteTarget.kind ↔ ProviderRole mapping:
205///
206/// | RouteTarget.kind | required ProviderRole | disambiguator |
207/// |---|---|---|
208/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
209/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
210/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
211///
212/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
213/// are wired by an orchestrator rather than opened directly by clients.
214#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
215#[serde(tag = "kind", rename_all = "snake_case")]
216pub enum RouteTarget {
217    ToolProvider {
218        module_id: String,
219    },
220    ManagementSurface {
221        module_id: String,
222    },
223    InternalService {
224        module_id: String,
225        service_id: String,
226    },
227}
228
229/// Envelope protocol version this build speaks.
230pub const PROTOCOL_VERSION: u8 = 2;
231
232/// The version of THIS crate (`subc-protocol`) as compiled into the linking
233/// binary — the fleet's shared wire-vocabulary version, and the value
234/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
235/// module's own envelope or payload crates: those are different numbering
236/// spaces, and declaring one here produces a confident wrong answer at any
237/// version gate (insula shipped exactly that before the referent was written
238/// down). `env!` makes it a property of the compiled binary, not of whatever
239/// source tree sits beside it at run time.
240pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
241
242/// Oldest envelope protocol version this build accepts.
243pub const MIN_SUPPORTED_VERSION: u8 = 2;
244
245/// Env var subc sets on each supervised child telling it the module_id it is
246/// supervised under, so it can register under that id.
247pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
248
249/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
250/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
251/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
252/// last injected for that id. Non-reserved modules never receive it.
253pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
254
255/// Fixed header length for `PROTOCOL_VERSION` 2.
256pub const HEADER_LEN: usize = 21;
257
258/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
259/// every envelope version. A reader needs only these to learn the version and
260/// thus the full header length.
261pub const FROZEN_PREFIX_LEN: usize = 5;
262
263/// Maximum frame body accepted before allocation.
264///
265/// This 64 MiB starting cap prevents a malformed header from forcing an
266/// unbounded allocation. Future protocol versions can negotiate or encode a
267/// different cap while preserving the frozen prefix.
268pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
269
270/// Canonical JSON body for all subc-generated `ERROR` frames.
271///
272/// `detail` is an optional machine-parsable surface for refusals whose remedy
273/// needs more than a code (e.g. a producer-published backoff number, an
274/// observed-vs-configured size pair). Absent detail serializes to nothing, so
275/// bodies without it are byte-identical to the pre-detail wire and older
276/// readers simply never see the field. Producers document each code's detail
277/// fields where the code is defined; `detail` must never carry secrets.
278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
279pub struct ErrorBody {
280    pub code: String,
281    pub message: String,
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub detail: Option<serde_json::Value>,
284}
285
286impl ErrorBody {
287    /// A detail-less error body; the common case.
288    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
289        Self {
290            code: code.into(),
291            message: message.into(),
292            detail: None,
293        }
294    }
295
296    /// Attach a machine-parsable detail object to this error.
297    pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
298        self.detail = Some(detail);
299        self
300    }
301}
302
303/// Module-to-subc `HELLO` body used during module registration.
304#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
305pub struct ModuleHelloBody {
306    pub manifest: manifest::ModuleManifest,
307    pub protocol_ver: u8,
308    #[serde(default)]
309    pub control_ops: Option<Vec<String>>,
310    /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
311    /// variable the daemon injected when it spawned this process. Only a daemon-spawned
312    /// process for a `reserved` module receives a nonce; subc accepts a reserved
313    /// `module_id`'s HELLO only when this matches the nonce it last injected for that
314    /// id, so a different process cannot register as a reserved module while the real
315    /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
316    /// self-connecting providers, which are never nonce-checked.
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub launch_nonce: Option<String>,
319}
320
321/// subc-to-module `HELLO_ACK` body used during module registration.
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323pub struct ModuleHelloAckBody {
324    pub negotiated_ver: u8,
325    pub subc_ops: Vec<String>,
326    pub subc_capabilities: Vec<String>,
327    /// The module's resolved storage descriptor, when the daemon's central config
328    /// configures managed storage. Carried opaquely here (subc-protocol stays a
329    /// thin wire crate with no storage/database dependency); a module that uses
330    /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
331    /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
332    /// `serde(default)` so an older module simply ignores it.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub storage: Option<serde_json::Value>,
335    /// The daemon's machine id (see [`MachineId`]): a name for this machine,
336    /// never an authority. Nothing may admit a peer, grant trust or skip a check
337    /// because two messages carry the same value.
338    ///
339    /// Carried as a plain string so one malformed value cannot fail the whole
340    /// registration reply; a module validates it with [`MachineId::parse`].
341    /// Absent from a daemon that predates the machine id, which a module must
342    /// read as exactly that, never as "no machine" and never as a reason to mint
343    /// its own.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub machine_id: Option<String>,
346}
347
348/// Frame kind (`type` byte at offset 5).
349///
350/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
351/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353#[repr(u8)]
354pub enum FrameType {
355    Request = 0,
356    Response = 1,
357    Push = 2,
358    StreamData = 3,
359    StreamEnd = 4,
360    Error = 5,
361    Cancel = 6,
362    Ping = 7,
363    Pong = 8,
364    Hello = 9,
365    HelloAck = 10,
366    Goodbye = 11,
367}
368
369impl FrameType {
370    /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
371    pub fn from_u8(b: u8) -> Option<Self> {
372        Some(match b {
373            0 => Self::Request,
374            1 => Self::Response,
375            2 => Self::Push,
376            3 => Self::StreamData,
377            4 => Self::StreamEnd,
378            5 => Self::Error,
379            6 => Self::Cancel,
380            7 => Self::Ping,
381            8 => Self::Pong,
382            9 => Self::Hello,
383            10 => Self::HelloAck,
384            11 => Self::Goodbye,
385            _ => return None,
386        })
387    }
388
389    pub fn is_pure_header(self) -> bool {
390        matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
391    }
392}
393
394/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
395/// without parsing the body.
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397#[repr(u8)]
398pub enum Priority {
399    Passive = 0,
400    Interactive = 1,
401    Background = 2,
402}
403
404impl Priority {
405    fn from_bits(bits: u8) -> Option<Self> {
406        Some(match bits {
407            0 => Self::Passive,
408            1 => Self::Interactive,
409            2 => Self::Background,
410            _ => return None,
411        })
412    }
413}
414
415/// Admission behavior carried in `flags` bits 4-5.
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417#[repr(u8)]
418pub enum AdmissionClass {
419    Normal = 0,
420    Expedite = 1,
421    Sheddable = 2,
422}
423
424impl AdmissionClass {
425    fn from_bits(bits: u8) -> Option<Self> {
426        Some(match bits {
427            0 => Self::Normal,
428            1 => Self::Expedite,
429            2 => Self::Sheddable,
430            _ => return None,
431        })
432    }
433}
434
435const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
436const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
437const FLAG_PRIORITY_SHIFT: u8 = 1;
438const FLAG_LAST: u8 = 0b0000_1000; // bit 3
439const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
440const FLAG_ADMISSION_SHIFT: u8 = 4;
441pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
442/// A request credit the client explicitly declares as a held-open subscription.
443pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
444
445/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub struct Flags(pub u8);
448
449impl Flags {
450    /// Build flags with the default [`AdmissionClass::Normal`] class.
451    pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
452        let mut b = 0u8;
453        if binary {
454            b |= FLAG_BINARY;
455        }
456        b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
457        if last {
458            b |= FLAG_LAST;
459        }
460        Flags(b)
461    }
462
463    /// Return these flags with a typed admission class.
464    pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
465        self.0 =
466            (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
467        self
468    }
469
470    /// Body is raw bytes (bulk lane) rather than JSON-RPC.
471    pub fn is_binary(self) -> bool {
472        self.0 & FLAG_BINARY != 0
473    }
474
475    /// Final frame of a streamed message.
476    pub fn is_last(self) -> bool {
477        self.0 & FLAG_LAST != 0
478    }
479
480    /// Decode the priority bits, or `None` if they hold a reserved value.
481    pub fn priority(self) -> Option<Priority> {
482        Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
483    }
484
485    /// Decode the admission-class bits, or `None` if they hold `0b11`.
486    pub fn admission_class(self) -> Option<AdmissionClass> {
487        AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
488    }
489
490    /// True when a request was explicitly opened as a held-open subscription.
491    pub fn is_subscription(self) -> bool {
492        self.0 & FLAG_SUBSCRIPTION != 0
493    }
494
495    /// True when the frame was authored by the daemon.
496    pub fn is_daemon_origin(self) -> bool {
497        self.0 & FLAG_DAEMON_ORIGIN != 0
498    }
499
500    /// Return these flags with daemon origin asserted.
501    pub fn with_daemon_origin(mut self) -> Self {
502        self.0 |= FLAG_DAEMON_ORIGIN;
503        self
504    }
505
506    /// Return these flags with daemon origin cleared.
507    pub fn without_daemon_origin(self) -> Self {
508        Self(self.0 & !FLAG_DAEMON_ORIGIN)
509    }
510}
511
512/// A decoded envelope header. The body is the `len` bytes that follow it.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub struct EnvelopeHeader {
515    /// Number of body bytes after the header.
516    pub len: u32,
517    /// Envelope version.
518    pub ver: u8,
519    /// Frame kind.
520    pub ty: FrameType,
521    /// Flag bits.
522    pub flags: Flags,
523    /// Sender-local route slot; 0 is the control channel.
524    pub channel: u16,
525    /// Sender-local binding epoch; 0 is reserved for the control channel.
526    pub epoch: u32,
527    /// Correlation id.
528    pub corr: u64,
529}
530
531impl EnvelopeHeader {
532    /// Serialize the header to its fixed 21-byte little-endian form.
533    pub fn encode(&self) -> [u8; HEADER_LEN] {
534        let mut buf = [0u8; HEADER_LEN];
535        buf[0..4].copy_from_slice(&self.len.to_le_bytes());
536        buf[4] = self.ver;
537        buf[5] = self.ty as u8;
538        buf[6] = self.flags.0;
539        buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
540        buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
541        buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
542        buf
543    }
544}
545
546/// Why a header could not be decoded.
547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
548pub enum DecodeError {
549    /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
550    TooShortForPrefix { have: usize },
551    /// `ver` is not a version this build understands.
552    UnsupportedVersion { ver: u8 },
553    /// Version known but fewer than its header length is present.
554    TooShortForHeader { have: usize, need: usize },
555    /// `type` byte is not a known `FrameType`.
556    UnknownFrameType { byte: u8 },
557    /// A reserved flag bit is set (retained for older decoder error compatibility).
558    ReservedFlagBits { flags: u8 },
559    /// Priority bits 1-2 hold the reserved value `0b11`.
560    ReservedPriorityBits { flags: u8 },
561    /// Admission bits 4-5 hold the reserved value `0b11`.
562    ReservedAdmissionClass { flags: u8 },
563    /// SHEDDABLE is set on a frame type that must be delivered.
564    SheddableIllegalFrameType { ty: FrameType, flags: u8 },
565    /// Channel 0 carried an epoch other than its reserved epoch 0.
566    NonzeroEpochOnControlChannel { epoch: u32 },
567    /// A pure-header frame declared body bytes.
568    PureHeaderFrameWithBody { ty: FrameType, len: u32 },
569}
570
571impl fmt::Display for DecodeError {
572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573        match self {
574            Self::TooShortForPrefix { have } => {
575                write!(f, "header shorter than frozen prefix: have {have} bytes")
576            }
577            Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
578            Self::TooShortForHeader { have, need } => {
579                write!(
580                    f,
581                    "header too short for version: have {have} bytes, need {need}"
582                )
583            }
584            Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
585            Self::ReservedFlagBits { flags } => {
586                write!(f, "reserved flag bits set in flags 0b{flags:08b}")
587            }
588            Self::ReservedPriorityBits { flags } => {
589                write!(f, "reserved priority bits set in flags 0b{flags:08b}")
590            }
591            Self::ReservedAdmissionClass { flags } => {
592                write!(f, "reserved admission class set in flags 0b{flags:08b}")
593            }
594            Self::SheddableIllegalFrameType { ty, flags } => write!(
595                f,
596                "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
597            ),
598            Self::NonzeroEpochOnControlChannel { epoch } => {
599                write!(f, "control channel carried nonzero epoch {epoch}")
600            }
601            Self::PureHeaderFrameWithBody { ty, len } => {
602                write!(
603                    f,
604                    "pure-header frame {ty:?} declared non-zero body length {len}"
605                )
606            }
607        }
608    }
609}
610
611impl Error for DecodeError {}
612
613/// How many header bytes a given envelope version occupies. Driven by the
614/// frozen prefix: read `ver`, then learn the full header length here.
615fn header_len_for_version(ver: u8) -> Option<usize> {
616    match ver {
617        PROTOCOL_VERSION => Some(HEADER_LEN),
618        _ => None,
619    }
620}
621
622/// Decode an envelope header from the front of `bytes`, following the
623/// frozen-prefix discipline:
624/// 1. need at least the 5-byte prefix to read `len` + `ver`;
625/// 2. dispatch the full header length on `ver`;
626/// 3. need the full header present; then parse the rest.
627///
628/// Never panics on malformed input — returns a typed [`DecodeError`].
629pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
630    if bytes.len() < FROZEN_PREFIX_LEN {
631        return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
632    }
633    let ver = bytes[4];
634    let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
635    if bytes.len() < need {
636        return Err(DecodeError::TooShortForHeader {
637            have: bytes.len(),
638            need,
639        });
640    }
641
642    let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
643    let ty =
644        FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
645    let flags = Flags(bytes[6]);
646    if flags.priority().is_none() {
647        return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
648    }
649    let admission_class = flags
650        .admission_class()
651        .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
652    if admission_class == AdmissionClass::Sheddable
653        && !matches!(ty, FrameType::Push | FrameType::StreamData)
654    {
655        return Err(DecodeError::SheddableIllegalFrameType {
656            ty,
657            flags: bytes[6],
658        });
659    }
660    if ty.is_pure_header() && len != 0 {
661        return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
662    }
663    let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
664    let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
665    if channel == 0 && epoch != 0 {
666        return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
667    }
668    let corr = u64::from_le_bytes([
669        bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
670    ]);
671
672    Ok(EnvelopeHeader {
673        len,
674        ver,
675        ty,
676        flags,
677        channel,
678        epoch,
679        corr,
680    })
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
688        hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
689    }
690
691    fn hdr_with_epoch(
692        len: u32,
693        ty: FrameType,
694        flags: Flags,
695        channel: u16,
696        epoch: u32,
697        corr: u64,
698    ) -> EnvelopeHeader {
699        EnvelopeHeader {
700            len,
701            ver: PROTOCOL_VERSION,
702            ty,
703            flags,
704            channel,
705            epoch,
706            corr,
707        }
708    }
709
710    #[test]
711    fn bind_identity_with_project_id_round_trips_json() {
712        let mut identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
713        identity.project_id = Some("pj-a1b2c3d4".to_string());
714
715        let encoded = serde_json::to_vec(&identity).unwrap();
716        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
717
718        assert_eq!(decoded, identity);
719    }
720
721    #[test]
722    fn bind_identity_without_project_id_round_trips_json() {
723        let identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
724
725        let encoded = serde_json::to_vec(&identity).unwrap();
726        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
727
728        assert_eq!(decoded, identity);
729    }
730
731    #[test]
732    fn legacy_bind_identity_without_project_id_decodes() {
733        let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
734            "project_root": "/tmp/project",
735            "harness": "opencode",
736            "session": "session-1"
737        }))
738        .unwrap();
739
740        assert_eq!(decoded.project_id, None);
741    }
742
743    #[test]
744    fn bind_identity_none_omits_project_id_instead_of_serializing_null() {
745        let encoded =
746            serde_json::to_value(BindIdentity::new("/tmp/project", "opencode", "session-1"))
747                .unwrap();
748
749        assert!(encoded.get("project_id").is_none());
750    }
751
752    #[test]
753    fn wire_crate_version_is_a_numeric_three_component_version() {
754        let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
755
756        assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
757        assert_eq!(components.len(), 3);
758        assert!(components
759            .iter()
760            .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
761    }
762
763    #[test]
764    fn route_target_variants_round_trip_json() {
765        let targets = [
766            RouteTarget::ToolProvider {
767                module_id: "aft".to_string(),
768            },
769            RouteTarget::ManagementSurface {
770                module_id: "memory".to_string(),
771            },
772            RouteTarget::InternalService {
773                module_id: "bus".to_string(),
774                service_id: "dm".to_string(),
775            },
776        ];
777
778        for target in targets {
779            let encoded = serde_json::to_vec(&target).unwrap();
780            let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
781            assert_eq!(decoded, target);
782        }
783    }
784
785    #[test]
786    fn error_body_round_trips_json() {
787        let body = ErrorBody {
788            code: "config_divergence".to_string(),
789            message: "active config differs".to_string(),
790            detail: None,
791        };
792
793        let encoded = serde_json::to_vec(&body).unwrap();
794        let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
795
796        assert_eq!(decoded, body);
797    }
798
799    #[test]
800    fn round_trip_request() {
801        let h = hdr(
802            1234,
803            FrameType::Request,
804            Flags::new(false, Priority::Interactive, false),
805            42,
806            0xDEAD_BEEF_0000_0001,
807        );
808        let decoded = decode_header(&h.encode()).unwrap();
809        assert_eq!(h, decoded);
810    }
811
812    #[test]
813    fn round_trip_all_frame_types() {
814        for b in 0u8..=11 {
815            let ty = FrameType::from_u8(b).unwrap();
816            let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
817            assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
818        }
819    }
820
821    #[test]
822    fn pure_header_frame_has_zero_len() {
823        // CANCEL carries only header (len = 0) + the target corr.
824        let h = hdr(
825            0,
826            FrameType::Cancel,
827            Flags::new(false, Priority::Passive, false),
828            7,
829            99,
830        );
831        let d = decode_header(&h.encode()).unwrap();
832        assert_eq!(d.len, 0);
833        assert_eq!(d.corr, 99);
834    }
835
836    #[test]
837    fn flags_round_trip() {
838        let f = Flags::new(true, Priority::Background, true)
839            .with_admission_class(AdmissionClass::Expedite);
840        assert!(f.is_binary());
841        assert!(f.is_last());
842        assert_eq!(f.priority(), Some(Priority::Background));
843        assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
844        let h = hdr(8, FrameType::StreamData, f, 1, 1);
845        assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
846    }
847
848    #[test]
849    fn daemon_origin_flags_decode_and_round_trip() {
850        let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
851        let old_decoded = decode_header(&old.encode()).unwrap();
852        assert!(!old_decoded.flags.is_daemon_origin());
853
854        let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
855        let daemon_decoded = decode_header(&daemon.encode()).unwrap();
856        assert!(daemon_decoded.flags.is_daemon_origin());
857        assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
858        assert!(Flags(0).with_daemon_origin().is_daemon_origin());
859    }
860
861    #[test]
862    fn little_endian_and_frozen_prefix_layout() {
863        let h = hdr_with_epoch(
864            0x0403_0201,
865            FrameType::Request,
866            Flags(0),
867            0x0605,
868            0x0a09_0807,
869            0x1211_100f_0e0d_0c0b,
870        );
871        let buf = h.encode();
872        assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
873        assert_eq!(buf[4], PROTOCOL_VERSION);
874        assert_eq!(&buf[7..9], &[5, 6]);
875        assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
876        assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
877        assert_eq!(buf.len(), HEADER_LEN);
878    }
879
880    #[test]
881    fn reject_too_short_for_prefix() {
882        assert_eq!(
883            decode_header(&[0, 0, 0, 0]),
884            Err(DecodeError::TooShortForPrefix { have: 4 })
885        );
886    }
887
888    #[test]
889    fn reject_too_short_for_header() {
890        // Valid 5-byte prefix but the v2 header is truncated.
891        let mut b = [0u8; 10];
892        b[4] = PROTOCOL_VERSION;
893        assert_eq!(
894            decode_header(&b),
895            Err(DecodeError::TooShortForHeader {
896                have: 10,
897                need: HEADER_LEN
898            })
899        );
900    }
901
902    #[test]
903    fn reject_unsupported_version() {
904        let mut b = [0u8; HEADER_LEN];
905        b[4] = 1;
906        assert_eq!(
907            decode_header(&b),
908            Err(DecodeError::UnsupportedVersion { ver: 1 })
909        );
910    }
911
912    #[test]
913    fn reject_unknown_frame_type() {
914        let mut b = [0u8; HEADER_LEN];
915        b[4] = PROTOCOL_VERSION;
916        b[5] = 99;
917        assert_eq!(
918            decode_header(&b),
919            Err(DecodeError::UnknownFrameType { byte: 99 })
920        );
921    }
922
923    #[test]
924    fn subscription_flag_decodes_and_tags_the_request() {
925        let mut b = [0u8; HEADER_LEN];
926        b[4] = PROTOCOL_VERSION;
927        b[5] = FrameType::Request as u8;
928        b[6] = FLAG_SUBSCRIPTION;
929        let decoded = decode_header(&b).unwrap();
930        assert!(decoded.flags.is_subscription());
931    }
932
933    #[test]
934    fn reject_reserved_priority_bits() {
935        let mut b = [0u8; HEADER_LEN];
936        b[4] = PROTOCOL_VERSION;
937        b[5] = FrameType::Request as u8;
938        b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
939        assert_eq!(
940            decode_header(&b),
941            Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
942        );
943    }
944
945    #[test]
946    fn reject_pure_header_frame_with_body_len() {
947        let h = hdr(
948            1,
949            FrameType::Ping,
950            Flags::new(false, Priority::Passive, false),
951            0,
952            1,
953        );
954        assert_eq!(
955            decode_header(&h.encode()),
956            Err(DecodeError::PureHeaderFrameWithBody {
957                ty: FrameType::Ping,
958                len: 1
959            })
960        );
961    }
962
963    #[test]
964    fn epoch_boundaries_round_trip() {
965        for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
966            let h = hdr_with_epoch(
967                0,
968                FrameType::Request,
969                Flags::new(false, Priority::Passive, false),
970                channel,
971                epoch,
972                9,
973            );
974            assert_eq!(decode_header(&h.encode()).unwrap(), h);
975        }
976    }
977
978    #[test]
979    fn admission_classes_accept_three_values_and_reject_reserved_value() {
980        for (ty, admission_class) in [
981            (FrameType::Request, AdmissionClass::Normal),
982            (FrameType::Request, AdmissionClass::Expedite),
983            (FrameType::Push, AdmissionClass::Sheddable),
984            (FrameType::StreamData, AdmissionClass::Sheddable),
985        ] {
986            let flags = Flags::new(false, Priority::Interactive, false)
987                .with_admission_class(admission_class);
988            let h = hdr(0, ty, flags, 1, 2);
989            assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
990        }
991
992        let mut h = hdr(
993            0,
994            FrameType::Push,
995            Flags::new(false, Priority::Passive, false),
996            1,
997            2,
998        )
999        .encode();
1000        h[6] |= 0b0011_0000;
1001        assert_eq!(
1002            decode_header(&h),
1003            Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1004        );
1005    }
1006
1007    #[test]
1008    fn sheddable_rejected_on_every_illegal_frame_type() {
1009        let flags = Flags::new(false, Priority::Passive, false)
1010            .with_admission_class(AdmissionClass::Sheddable);
1011        for ty in [
1012            FrameType::Request,
1013            FrameType::Response,
1014            FrameType::StreamEnd,
1015            FrameType::Error,
1016            FrameType::Cancel,
1017            FrameType::Ping,
1018            FrameType::Pong,
1019            FrameType::Hello,
1020            FrameType::HelloAck,
1021            FrameType::Goodbye,
1022        ] {
1023            let h = hdr(0, ty, flags, 1, 2);
1024            assert_eq!(
1025                decode_header(&h.encode()),
1026                Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1027            );
1028        }
1029    }
1030
1031    #[test]
1032    fn nonzero_epoch_on_control_channel_is_rejected() {
1033        let h = hdr_with_epoch(
1034            0,
1035            FrameType::Request,
1036            Flags::new(false, Priority::Passive, false),
1037            0,
1038            u32::MAX,
1039            2,
1040        );
1041        assert_eq!(
1042            decode_header(&h.encode()),
1043            Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1044        );
1045    }
1046}