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