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