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