Skip to main content

microsandbox_protocol/
message.rs

1//! Message envelope and type definitions for the agent protocol.
2
3use serde::{Deserialize, Serialize, de::DeserializeOwned};
4
5use crate::error::ProtocolResult;
6
7//--------------------------------------------------------------------------------------------------
8// Constants
9//--------------------------------------------------------------------------------------------------
10
11/// Current protocol version.
12pub const PROTOCOL_VERSION: u8 = 9;
13
14/// Frame flag: this is the last message for the given correlation ID.
15///
16/// Set on terminal message types such as `ExecExited`, `FsResponse`, and `TcpClosed`.
17pub const FLAG_TERMINAL: u8 = 0b0000_0001;
18
19/// Frame flag: this is the first message of a new session.
20///
21/// Set on session-initiating message types such as `ExecRequest`, `FsRequest`, and `TcpConnect`.
22pub const FLAG_SESSION_START: u8 = 0b0000_0010;
23
24/// Frame flag: this message requests sandbox shutdown.
25///
26/// Set on `Shutdown` messages. The sandbox-process relay uses this to trigger
27/// drain escalation (SIGTERM → SIGKILL) if the guest doesn't exit voluntarily.
28pub const FLAG_SHUTDOWN: u8 = 0b0000_0100;
29
30/// Frame flag: the body is a generation-8 raw bulk record rather than CBOR.
31pub const FLAG_BULK: u8 = 0b0000_1000;
32
33/// Size of the frame header fields that sit between the length prefix and the
34/// control or raw body: `[id: u32 BE][flags: u8]` = 5 bytes.
35pub const FRAME_HEADER_SIZE: usize = 5;
36
37//--------------------------------------------------------------------------------------------------
38// Types
39//--------------------------------------------------------------------------------------------------
40
41/// The message envelope sent over the wire.
42///
43/// Each message contains a version, type, correlation ID, flags, and a CBOR payload.
44///
45/// Wire format: `[len: u32 BE][id: u32 BE][flags: u8][CBOR(v, t, p)]`
46///
47/// The `id` and `flags` fields live in the binary frame header (outside CBOR)
48/// so that relay intermediaries can route frames without CBOR parsing.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Message {
51    /// Protocol generation, echoed into the frame.
52    ///
53    /// This is the single protocol version axis (see `VERSIONING.md`), the same
54    /// number negotiated once at the handshake — not a second, message-local
55    /// version. It is carried here so a frame is self-describing for debugging
56    /// and telemetry; behavior is gated on the negotiated generation, not on
57    /// reading this field per message.
58    pub v: u8,
59
60    /// Message type.
61    pub t: MessageType,
62
63    /// Correlation ID used to associate requests with responses and
64    /// to identify exec sessions.
65    ///
66    /// Serialized in the binary frame header, not in CBOR.
67    #[serde(skip)]
68    pub id: u32,
69
70    /// Frame flags computed from the message type.
71    ///
72    /// Serialized in the binary frame header, not in CBOR.
73    #[serde(skip)]
74    pub flags: u8,
75
76    /// The CBOR-encoded payload bytes.
77    #[serde(with = "serde_bytes")]
78    pub p: Vec<u8>,
79}
80
81/// Identifies the type of a protocol message.
82///
83/// The `#[strum(serialize = ...)]` attribute on each variant is the single
84/// source for its wire string: [`as_str`](Self::as_str) and
85/// [`from_wire_str`](Self::from_wire_str) are derived from it, and
86/// [`strum::IntoEnumIterator`] yields every variant for exhaustive iteration
87/// (the schema snapshot) without a hand-maintained list.
88#[derive(
89    Debug,
90    Clone,
91    Copy,
92    PartialEq,
93    Eq,
94    Hash,
95    strum::IntoStaticStr,
96    strum::AsRefStr,
97    strum::EnumString,
98    strum::EnumIter,
99)]
100pub enum MessageType {
101    /// Guest agent is ready.
102    #[strum(serialize = "core.ready")]
103    Ready,
104
105    /// Guest reports init context before user mounts.
106    #[strum(serialize = "core.init.resolved")]
107    InitResolved,
108
109    /// Host acknowledges init-context setup.
110    #[strum(serialize = "core.init.ack")]
111    InitAck,
112
113    /// Host requests shutdown.
114    #[strum(serialize = "core.shutdown")]
115    Shutdown,
116
117    /// Host relay reports that one SDK client disconnected.
118    #[strum(serialize = "core.relay.client.disconnected")]
119    RelayClientDisconnected,
120
121    /// Host asks the guest to synchronize `CLOCK_REALTIME`.
122    #[strum(serialize = "core.clock.sync")]
123    ClockSync,
124
125    /// Host checks whether the guest agent is reachable.
126    #[strum(serialize = "core.ping")]
127    Ping,
128
129    /// Guest confirms that the guest agent is reachable.
130    #[strum(serialize = "core.pong")]
131    Pong,
132
133    /// Host explicitly records sandbox activity.
134    #[strum(serialize = "core.touch")]
135    Touch,
136
137    /// Guest confirms that sandbox activity was recorded.
138    #[strum(serialize = "core.touched")]
139    Touched,
140
141    /// Host asks agentd to freeze all agent-managed workload processes.
142    #[strum(serialize = "core.workload.freeze")]
143    WorkloadFreeze,
144
145    /// Guest confirms that every agent-managed workload process is frozen.
146    #[strum(serialize = "core.workload.frozen")]
147    WorkloadFrozen,
148
149    /// Host asks agentd to release a previously established workload freeze.
150    #[strum(serialize = "core.workload.thaw")]
151    WorkloadThaw,
152
153    /// Guest confirms that agent-managed workload processes may run again.
154    #[strum(serialize = "core.workload.thawed")]
155    WorkloadThawed,
156
157    /// Guest grants cumulative ordinary input capacity to its host relay.
158    #[strum(serialize = "core.workload.transport.credit")]
159    WorkloadTransportCredit,
160
161    /// Host checks mounted root-filesystem growth before changing block capacity.
162    #[strum(serialize = "core.root_disk.prepare")]
163    RootDiskPrepare,
164
165    /// Host requests mounted root-filesystem expansion after block capacity changed.
166    #[strum(serialize = "core.root_disk.grow")]
167    RootDiskGrow,
168
169    /// Guest reports the root filesystem and device capacities.
170    #[strum(serialize = "core.root_disk.state")]
171    RootDiskState,
172
173    /// Peer reports a recoverable protocol-level error.
174    #[strum(serialize = "core.error")]
175    CoreError,
176
177    /// Guest accepts the raw-bulk offer on an opening operation.
178    #[strum(serialize = "core.bulk.accepted")]
179    BulkAccepted,
180
181    /// Receiver grants an absolute send limit for one bulk flow.
182    #[strum(serialize = "core.bulk.credit")]
183    BulkCredit,
184
185    /// Sender declares the exact final offset of one bulk flow.
186    #[strum(serialize = "core.bulk.finish")]
187    BulkFinish,
188
189    /// Peer asks to stop an entire bulk correlation.
190    #[strum(serialize = "core.bulk.cancel")]
191    BulkCancel,
192
193    /// Host requests command execution.
194    #[strum(serialize = "core.exec.request")]
195    ExecRequest,
196
197    /// Guest confirms command started.
198    #[strum(serialize = "core.exec.started")]
199    ExecStarted,
200
201    /// Host sends stdin data.
202    #[strum(serialize = "core.exec.stdin")]
203    ExecStdin,
204
205    /// Guest reports that a prior `ExecStdin` write to the child's
206    /// stdin failed (e.g. the child closed its read end). Non-terminal:
207    /// the session continues and may still produce stdout/stderr and
208    /// an exit code.
209    #[strum(serialize = "core.exec.stdin.error")]
210    ExecStdinError,
211
212    /// Guest sends stdout data.
213    #[strum(serialize = "core.exec.stdout")]
214    ExecStdout,
215
216    /// Guest sends stderr data.
217    #[strum(serialize = "core.exec.stderr")]
218    ExecStderr,
219
220    /// Guest reports command exit.
221    #[strum(serialize = "core.exec.exited")]
222    ExecExited,
223
224    /// Guest reports command failed to spawn (binary not found,
225    /// permission denied, etc.). Distinct from `ExecExited` —
226    /// `ExecFailed` means the user code never ran. Terminal.
227    #[strum(serialize = "core.exec.failed")]
228    ExecFailed,
229
230    /// Host requests PTY resize.
231    #[strum(serialize = "core.exec.resize")]
232    ExecResize,
233
234    /// Host sends signal to process.
235    #[strum(serialize = "core.exec.signal")]
236    ExecSignal,
237
238    /// Host requests a filesystem operation.
239    #[strum(serialize = "core.fs.request")]
240    FsRequest,
241
242    /// Guest sends a terminal filesystem response.
243    #[strum(serialize = "core.fs.response")]
244    FsResponse,
245
246    /// Streaming file data chunk (bidirectional).
247    #[strum(serialize = "core.fs.data")]
248    FsData,
249
250    /// Host requests a TCP connection from inside the guest.
251    #[strum(serialize = "core.tcp.connect")]
252    TcpConnect,
253
254    /// Guest confirms that a TCP connection was opened.
255    #[strum(serialize = "core.tcp.connected")]
256    TcpConnected,
257
258    /// TCP stream data chunk (bidirectional).
259    #[strum(serialize = "core.tcp.data")]
260    TcpData,
261
262    /// One TCP stream side has closed its write half.
263    #[strum(serialize = "core.tcp.eof")]
264    TcpEof,
265
266    /// Host requests a TCP session close.
267    #[strum(serialize = "core.tcp.close")]
268    TcpClose,
269
270    /// Guest reports that a TCP session is closed. Terminal.
271    #[strum(serialize = "core.tcp.closed")]
272    TcpClosed,
273
274    /// Guest reports that a TCP session failed. Terminal.
275    #[strum(serialize = "core.tcp.failed")]
276    TcpFailed,
277
278    /// Host supplies one-shot guest bootstrap configuration.
279    #[strum(serialize = "core.bootstrap")]
280    Bootstrap,
281}
282
283//--------------------------------------------------------------------------------------------------
284// Methods
285//--------------------------------------------------------------------------------------------------
286
287impl Message {
288    /// Creates a new message with the current protocol version and raw payload bytes.
289    pub fn new(t: MessageType, id: u32, p: Vec<u8>) -> Self {
290        let flags = t.flags();
291        Self {
292            v: PROTOCOL_VERSION,
293            t,
294            id,
295            flags,
296            p,
297        }
298    }
299
300    /// Creates a new message by serializing the given payload to CBOR.
301    pub fn with_payload<T: Serialize>(
302        t: MessageType,
303        id: u32,
304        payload: &T,
305    ) -> ProtocolResult<Self> {
306        let mut p = Vec::new();
307        ciborium::into_writer(payload, &mut p)?;
308        let flags = t.flags();
309        Ok(Self {
310            v: PROTOCOL_VERSION,
311            t,
312            id,
313            flags,
314            p,
315        })
316    }
317
318    /// Deserializes the payload bytes into the given type.
319    pub fn payload<T: DeserializeOwned>(&self) -> ProtocolResult<T> {
320        Ok(ciborium::from_reader(&self.p[..])?)
321    }
322}
323
324impl MessageType {
325    /// Whether host-to-guest delivery can retain payload credit behind a workload consumer.
326    ///
327    /// The bundled workload barrier uses logical classes, not physical console ports. Payload
328    /// messages (including ordered EOF) share data credit with raw bulk records, leaving control
329    /// capacity available for fresh commands when restored stdin has not yet been consumed.
330    pub fn uses_workload_data_credit(self) -> bool {
331        matches!(
332            self,
333            Self::ExecStdin | Self::FsData | Self::TcpData | Self::TcpEof
334        )
335    }
336
337    /// Computes the frame flags byte for this message type.
338    pub fn flags(&self) -> u8 {
339        match self {
340            Self::Pong
341            | Self::Touched
342            | Self::WorkloadFrozen
343            | Self::WorkloadThawed
344            | Self::RootDiskState
345            | Self::CoreError
346            | Self::ExecExited
347            | Self::ExecFailed
348            | Self::FsResponse
349            | Self::TcpClosed
350            | Self::TcpFailed => FLAG_TERMINAL,
351            Self::ExecRequest | Self::FsRequest | Self::TcpConnect => FLAG_SESSION_START,
352            Self::Shutdown => FLAG_SHUTDOWN,
353            _ => 0,
354        }
355    }
356
357    /// The protocol generation that introduced this message type.
358    ///
359    /// A per-type label on the single protocol generation axis (see
360    /// `VERSIONING.md`), not a separate version counter. The send path gates on
361    /// it: a type whose generation exceeds the peer's negotiated generation is
362    /// rejected locally with a typed error instead of being sent to a peer that
363    /// cannot handle it, so only that one feature fails rather than the session.
364    ///
365    /// Core and exec types belong to the generation-1 baseline; they work on
366    /// every runtime we still talk to, including the pre-0.5 legacy one.
367    /// Filesystem streaming did not exist in the pre-0.5 legacy protocol
368    /// (generation 1), so the `Fs*` types require generation 2 or newer.
369    /// TCP forwarding was introduced in generation 4. `core.error` was
370    /// introduced in generation 5. Reachability checks and explicit idle
371    /// refreshes were introduced in generation 6.
372    ///
373    /// There is deliberately no wildcard arm: adding a new `MessageType` must
374    /// force a conscious choice of the generation that introduced it (and a
375    /// matching `PROTOCOL_VERSION` bump). Message types are append-only — never
376    /// lower or re-purpose an existing value.
377    pub fn min_protocol_version(&self) -> u8 {
378        match self {
379            Self::Ready
380            | Self::InitResolved
381            | Self::InitAck
382            | Self::Shutdown
383            | Self::RelayClientDisconnected
384            | Self::ClockSync
385            | Self::ExecRequest
386            | Self::ExecStarted
387            | Self::ExecStdin
388            | Self::ExecStdinError
389            | Self::ExecStdout
390            | Self::ExecStderr
391            | Self::ExecExited
392            | Self::ExecFailed
393            | Self::ExecResize
394            | Self::ExecSignal => 1,
395            Self::FsRequest | Self::FsResponse | Self::FsData => 2,
396            Self::CoreError => 5,
397            Self::Ping | Self::Pong | Self::Touch | Self::Touched => 6,
398            Self::Bootstrap => 7,
399            Self::WorkloadFreeze
400            | Self::WorkloadFrozen
401            | Self::WorkloadThaw
402            | Self::WorkloadThawed
403            | Self::WorkloadTransportCredit => 9,
404            Self::RootDiskPrepare | Self::RootDiskGrow | Self::RootDiskState => 9,
405            Self::BulkAccepted | Self::BulkCredit | Self::BulkFinish | Self::BulkCancel => 8,
406            Self::TcpConnect
407            | Self::TcpConnected
408            | Self::TcpData
409            | Self::TcpEof
410            | Self::TcpClose
411            | Self::TcpClosed
412            | Self::TcpFailed => 4,
413        }
414    }
415
416    /// Whether a peer that speaks `peer_generation` is new enough to handle this
417    /// message type.
418    ///
419    /// The shared version-compatibility primitive for both directions. The host
420    /// gates its sends on it (`AgentClient::ensure_version_compat`); the guest
421    /// can gate a guest-initiated message the same way, reading the peer's
422    /// generation from the `v` field of the request that established the session.
423    /// See `VERSIONING.md`.
424    pub fn is_available_at(&self, peer_generation: u8) -> bool {
425        self.min_protocol_version() <= peer_generation
426    }
427
428    /// Returns the wire string representation.
429    ///
430    /// Backed by the per-variant `#[strum(serialize = ...)]` attribute, the
431    /// single source of truth for wire strings.
432    pub fn as_str(&self) -> &'static str {
433        (*self).into()
434    }
435
436    /// Parses a wire string into a message type, the inverse of
437    /// [`as_str`](Self::as_str). Returns `None` for an unknown string.
438    pub fn from_wire_str(s: &str) -> Option<Self> {
439        s.parse().ok()
440    }
441}
442
443//--------------------------------------------------------------------------------------------------
444// Trait Implementations
445//--------------------------------------------------------------------------------------------------
446
447impl Serialize for MessageType {
448    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
449    where
450        S: serde::Serializer,
451    {
452        serializer.serialize_str(self.as_str())
453    }
454}
455
456impl<'de> Deserialize<'de> for MessageType {
457    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
458    where
459        D: serde::Deserializer<'de>,
460    {
461        let s = String::deserialize(deserializer)?;
462        Self::from_wire_str(&s)
463            .ok_or_else(|| serde::de::Error::custom(format!("unknown message type: {s}")))
464    }
465}
466
467//--------------------------------------------------------------------------------------------------
468// Tests
469//--------------------------------------------------------------------------------------------------
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[test]
476    fn retained_payload_and_eof_use_data_credit_without_changing_frame_flags() {
477        for message in [
478            MessageType::ExecStdin,
479            MessageType::FsData,
480            MessageType::TcpData,
481            MessageType::TcpEof,
482        ] {
483            assert!(message.uses_workload_data_credit());
484            assert_eq!(
485                message.flags(),
486                0,
487                "logical admission must not change the wire header"
488            );
489        }
490        for message in [
491            MessageType::ExecRequest,
492            MessageType::Ping,
493            MessageType::FsRequest,
494            MessageType::TcpConnect,
495            MessageType::ExecSignal,
496            MessageType::BulkFinish,
497            MessageType::BulkCancel,
498            MessageType::RelayClientDisconnected,
499        ] {
500            assert!(!message.uses_workload_data_credit());
501        }
502    }
503
504    #[test]
505    fn test_message_type_roundtrip() {
506        let types = [
507            (MessageType::Bootstrap, "core.bootstrap"),
508            (MessageType::Ready, "core.ready"),
509            (MessageType::InitResolved, "core.init.resolved"),
510            (MessageType::InitAck, "core.init.ack"),
511            (MessageType::Shutdown, "core.shutdown"),
512            (
513                MessageType::RelayClientDisconnected,
514                "core.relay.client.disconnected",
515            ),
516            (MessageType::ClockSync, "core.clock.sync"),
517            (MessageType::Ping, "core.ping"),
518            (MessageType::Pong, "core.pong"),
519            (MessageType::Touch, "core.touch"),
520            (MessageType::Touched, "core.touched"),
521            (MessageType::WorkloadFreeze, "core.workload.freeze"),
522            (MessageType::WorkloadFrozen, "core.workload.frozen"),
523            (MessageType::WorkloadThaw, "core.workload.thaw"),
524            (MessageType::WorkloadThawed, "core.workload.thawed"),
525            (
526                MessageType::WorkloadTransportCredit,
527                "core.workload.transport.credit",
528            ),
529            (MessageType::CoreError, "core.error"),
530            (MessageType::BulkAccepted, "core.bulk.accepted"),
531            (MessageType::BulkCredit, "core.bulk.credit"),
532            (MessageType::BulkFinish, "core.bulk.finish"),
533            (MessageType::BulkCancel, "core.bulk.cancel"),
534            (MessageType::ExecRequest, "core.exec.request"),
535            (MessageType::ExecStarted, "core.exec.started"),
536            (MessageType::ExecStdin, "core.exec.stdin"),
537            (MessageType::ExecStdinError, "core.exec.stdin.error"),
538            (MessageType::ExecStdout, "core.exec.stdout"),
539            (MessageType::ExecStderr, "core.exec.stderr"),
540            (MessageType::ExecExited, "core.exec.exited"),
541            (MessageType::ExecFailed, "core.exec.failed"),
542            (MessageType::ExecResize, "core.exec.resize"),
543            (MessageType::ExecSignal, "core.exec.signal"),
544            (MessageType::FsRequest, "core.fs.request"),
545            (MessageType::FsResponse, "core.fs.response"),
546            (MessageType::FsData, "core.fs.data"),
547            (MessageType::TcpConnect, "core.tcp.connect"),
548            (MessageType::TcpConnected, "core.tcp.connected"),
549            (MessageType::TcpData, "core.tcp.data"),
550            (MessageType::TcpEof, "core.tcp.eof"),
551            (MessageType::TcpClose, "core.tcp.close"),
552            (MessageType::TcpClosed, "core.tcp.closed"),
553            (MessageType::TcpFailed, "core.tcp.failed"),
554        ];
555
556        for (mt, expected_str) in &types {
557            assert_eq!(mt.as_str(), *expected_str);
558            assert_eq!(MessageType::from_wire_str(expected_str).unwrap(), *mt);
559        }
560    }
561
562    #[test]
563    fn test_message_type_serde_roundtrip() {
564        let types = [
565            MessageType::Bootstrap,
566            MessageType::Ready,
567            MessageType::InitResolved,
568            MessageType::InitAck,
569            MessageType::Shutdown,
570            MessageType::RelayClientDisconnected,
571            MessageType::ClockSync,
572            MessageType::Ping,
573            MessageType::Pong,
574            MessageType::Touch,
575            MessageType::Touched,
576            MessageType::WorkloadFreeze,
577            MessageType::WorkloadFrozen,
578            MessageType::WorkloadThaw,
579            MessageType::WorkloadThawed,
580            MessageType::WorkloadTransportCredit,
581            MessageType::CoreError,
582            MessageType::BulkAccepted,
583            MessageType::BulkCredit,
584            MessageType::BulkFinish,
585            MessageType::BulkCancel,
586            MessageType::ExecRequest,
587            MessageType::ExecStarted,
588            MessageType::ExecStdin,
589            MessageType::ExecStdinError,
590            MessageType::ExecStdout,
591            MessageType::ExecStderr,
592            MessageType::ExecExited,
593            MessageType::ExecFailed,
594            MessageType::ExecResize,
595            MessageType::ExecSignal,
596            MessageType::FsRequest,
597            MessageType::FsResponse,
598            MessageType::FsData,
599            MessageType::TcpConnect,
600            MessageType::TcpConnected,
601            MessageType::TcpData,
602            MessageType::TcpEof,
603            MessageType::TcpClose,
604            MessageType::TcpClosed,
605            MessageType::TcpFailed,
606        ];
607
608        for mt in &types {
609            let mut buf = Vec::new();
610            ciborium::into_writer(mt, &mut buf).unwrap();
611            let decoded: MessageType = ciborium::from_reader(&buf[..]).unwrap();
612            assert_eq!(&decoded, mt);
613        }
614    }
615
616    #[test]
617    fn test_unknown_message_type() {
618        assert!(MessageType::from_wire_str("core.unknown").is_none());
619    }
620
621    #[test]
622    fn test_message_with_payload_roundtrip() {
623        use crate::exec::ExecExited;
624
625        let msg =
626            Message::with_payload(MessageType::ExecExited, 7, &ExecExited { code: 42 }).unwrap();
627
628        assert_eq!(msg.t, MessageType::ExecExited);
629        assert_eq!(msg.id, 7);
630        assert_eq!(msg.flags, FLAG_TERMINAL);
631
632        let payload: ExecExited = msg.payload().unwrap();
633        assert_eq!(payload.code, 42);
634    }
635
636    #[test]
637    fn test_message_type_flags() {
638        assert_eq!(MessageType::ExecExited.flags(), FLAG_TERMINAL);
639        assert_eq!(MessageType::ExecFailed.flags(), FLAG_TERMINAL);
640        assert_eq!(MessageType::FsResponse.flags(), FLAG_TERMINAL);
641        assert_eq!(MessageType::TcpClosed.flags(), FLAG_TERMINAL);
642        assert_eq!(MessageType::TcpFailed.flags(), FLAG_TERMINAL);
643        assert_eq!(MessageType::Pong.flags(), FLAG_TERMINAL);
644        assert_eq!(MessageType::Touched.flags(), FLAG_TERMINAL);
645        assert_eq!(MessageType::WorkloadFrozen.flags(), FLAG_TERMINAL);
646        assert_eq!(MessageType::WorkloadThawed.flags(), FLAG_TERMINAL);
647        assert_eq!(MessageType::ExecRequest.flags(), FLAG_SESSION_START);
648        assert_eq!(MessageType::FsRequest.flags(), FLAG_SESSION_START);
649        assert_eq!(MessageType::TcpConnect.flags(), FLAG_SESSION_START);
650        assert_eq!(MessageType::Ready.flags(), 0);
651        assert_eq!(MessageType::Bootstrap.flags(), 0);
652        assert_eq!(MessageType::InitResolved.flags(), 0);
653        assert_eq!(MessageType::InitAck.flags(), 0);
654        assert_eq!(MessageType::Shutdown.flags(), FLAG_SHUTDOWN);
655        assert_eq!(MessageType::ClockSync.flags(), 0);
656        assert_eq!(MessageType::Ping.flags(), 0);
657        assert_eq!(MessageType::Touch.flags(), 0);
658        assert_eq!(MessageType::WorkloadFreeze.flags(), 0);
659        assert_eq!(MessageType::WorkloadThaw.flags(), 0);
660        assert_eq!(MessageType::BulkAccepted.flags(), 0);
661        assert_eq!(MessageType::BulkCredit.flags(), 0);
662        assert_eq!(MessageType::BulkFinish.flags(), 0);
663        assert_eq!(MessageType::BulkCancel.flags(), 0);
664        assert_eq!(MessageType::ExecStarted.flags(), 0);
665        assert_eq!(MessageType::ExecStdin.flags(), 0);
666        assert_eq!(MessageType::ExecStdout.flags(), 0);
667        assert_eq!(MessageType::ExecStderr.flags(), 0);
668        assert_eq!(MessageType::ExecResize.flags(), 0);
669        assert_eq!(MessageType::ExecSignal.flags(), 0);
670        assert_eq!(MessageType::FsData.flags(), 0);
671        assert_eq!(MessageType::TcpConnected.flags(), 0);
672        assert_eq!(MessageType::TcpData.flags(), 0);
673        assert_eq!(MessageType::TcpEof.flags(), 0);
674        assert_eq!(MessageType::TcpClose.flags(), 0);
675    }
676
677    #[test]
678    fn test_additive_fields_keep_old_and_new_compatible() {
679        // The core backward-compatibility guarantee from VERSIONING.md: a new,
680        // always-optional field is safe in both directions across a version skew.
681        use serde::{Deserialize, Serialize};
682
683        // A payload as it existed at an older generation.
684        #[derive(Serialize, Deserialize)]
685        struct Old {
686            a: u32,
687            b: u32,
688        }
689
690        // The same payload after a later generation added `c` (optional).
691        #[derive(Serialize, Deserialize, Debug, PartialEq)]
692        struct New {
693            a: u32,
694            b: u32,
695            #[serde(default)]
696            c: u32,
697        }
698
699        // New sender -> old receiver: the unknown `c` is ignored, not an error.
700        let mut new_bytes = Vec::new();
701        ciborium::into_writer(&New { a: 1, b: 2, c: 3 }, &mut new_bytes).unwrap();
702        let as_old: Old = ciborium::from_reader(&new_bytes[..]).unwrap();
703        assert_eq!((as_old.a, as_old.b), (1, 2));
704
705        // Old sender -> new receiver: the missing `c` falls back to its default.
706        let mut old_bytes = Vec::new();
707        ciborium::into_writer(&Old { a: 1, b: 2 }, &mut old_bytes).unwrap();
708        let as_new: New = ciborium::from_reader(&old_bytes[..]).unwrap();
709        assert_eq!(as_new, New { a: 1, b: 2, c: 0 });
710    }
711
712    #[test]
713    fn test_is_available_at() {
714        // Exec is in the generation-1 baseline: available to every peer.
715        assert!(MessageType::ExecRequest.is_available_at(1));
716        assert!(MessageType::ExecRequest.is_available_at(2));
717        assert!(MessageType::ExecRequest.is_available_at(PROTOCOL_VERSION));
718        // Filesystem requires generation 2: unavailable to a legacy (gen 1) peer.
719        assert!(!MessageType::FsRequest.is_available_at(1));
720        assert!(MessageType::FsRequest.is_available_at(2));
721        assert!(MessageType::FsRequest.is_available_at(PROTOCOL_VERSION));
722        // Ping/touch are generation-6 core capabilities.
723        assert!(!MessageType::Ping.is_available_at(5));
724        assert!(MessageType::Ping.is_available_at(6));
725        assert!(MessageType::Ping.is_available_at(PROTOCOL_VERSION));
726        // Bootstrap is internal to generation-7 host/agent boot.
727        assert!(!MessageType::Bootstrap.is_available_at(6));
728        // Released generation-8 agents support bulk I/O, not workload latching.
729        assert!(!MessageType::WorkloadFreeze.is_available_at(8));
730        assert!(MessageType::WorkloadFreeze.is_available_at(PROTOCOL_VERSION));
731        assert!(MessageType::Bootstrap.is_available_at(7));
732        // Raw bulk controls are generation-8 only. A bootstrap-capable
733        // generation-7 peer must remain on the framed compatibility path.
734        assert!(!MessageType::BulkAccepted.is_available_at(7));
735        assert!(MessageType::BulkAccepted.is_available_at(8));
736    }
737
738    #[test]
739    fn test_min_protocol_version_per_type() {
740        // Core and exec types are the generation-1 baseline: usable on every
741        // runtime we still talk to, including the pre-0.5 legacy one.
742        let baseline = [
743            MessageType::Ready,
744            MessageType::InitResolved,
745            MessageType::InitAck,
746            MessageType::Shutdown,
747            MessageType::RelayClientDisconnected,
748            MessageType::ClockSync,
749            MessageType::ExecRequest,
750            MessageType::ExecStarted,
751            MessageType::ExecStdin,
752            MessageType::ExecStdinError,
753            MessageType::ExecStdout,
754            MessageType::ExecStderr,
755            MessageType::ExecExited,
756            MessageType::ExecFailed,
757            MessageType::ExecResize,
758            MessageType::ExecSignal,
759        ];
760        for mt in &baseline {
761            assert_eq!(mt.min_protocol_version(), 1, "{mt:?} should be v1 baseline");
762        }
763
764        // Filesystem streaming did not exist in the pre-0.5 legacy protocol, so
765        // these require a post-legacy generation.
766        for mt in [
767            MessageType::FsRequest,
768            MessageType::FsResponse,
769            MessageType::FsData,
770        ] {
771            assert_eq!(mt.min_protocol_version(), 2, "{mt:?} should require gen 2");
772        }
773
774        for mt in [
775            MessageType::Ping,
776            MessageType::Pong,
777            MessageType::Touch,
778            MessageType::Touched,
779        ] {
780            assert_eq!(mt.min_protocol_version(), 6, "{mt:?} should require gen 6");
781        }
782
783        assert_eq!(MessageType::Bootstrap.min_protocol_version(), 7);
784        for mt in [
785            MessageType::BulkAccepted,
786            MessageType::BulkCredit,
787            MessageType::BulkFinish,
788            MessageType::BulkCancel,
789        ] {
790            assert_eq!(mt.min_protocol_version(), 8, "{mt:?} should require gen 8");
791        }
792
793        for mt in [
794            MessageType::WorkloadFreeze,
795            MessageType::WorkloadFrozen,
796            MessageType::WorkloadThaw,
797            MessageType::WorkloadThawed,
798            MessageType::WorkloadTransportCredit,
799        ] {
800            assert_eq!(mt.min_protocol_version(), 9, "{mt:?} should require gen 9");
801        }
802
803        // Every current type must be sendable to a current peer.
804        assert!(MessageType::FsRequest.min_protocol_version() <= PROTOCOL_VERSION);
805    }
806
807    #[test]
808    fn test_message_new_computes_flags() {
809        let msg = Message::new(MessageType::ExecRequest, 1, Vec::new());
810        assert_eq!(msg.flags, FLAG_SESSION_START);
811
812        let msg = Message::new(MessageType::ExecStdout, 1, Vec::new());
813        assert_eq!(msg.flags, 0);
814    }
815}