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