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