mxc-sdk 1.0.1

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Control protocol between a `wxc-exec` phase process and the long-lived
//! `wxc-wslc-daemon`.
//!
//! State-aware WSLc runs each lifecycle phase (provision / start / exec / stop /
//! deprovision) as a **separate** short-lived `wxc-exec` process, but the WSLc
//! SDK has no cross-process re-attach: `WslcSession` / `WslcContainer` handles
//! are obtainable only via `WslcCreate*` and are in-process. A persistent
//! per-user daemon therefore owns the handles, and the phase processes drive it
//! over this protocol.
//!
//! # Framing
//! Every message is length-prefixed: a 4-byte little-endian `u32` frame length
//! followed by that many bytes of JSON ([`serde_json`]). The same framing
//! carries both the control frames ([`DaemonRequest`] / [`DaemonResponse`]) and
//! the exec data-phase [`StreamFrame`]s, so the wire has a single, trivially
//! testable structure.
//!
//! # Layering
//! These are the daemon's **own internal** config structs, deliberately
//! separate from the public `wslc.*` wire schema. The state-aware
//! backend (a later PR) is the translator between the public wire model and
//! this protocol; keeping them decoupled lets the daemon + IPC ship and be
//! fully tested without touching the wire schema or its CI gates.

use serde::de::DeserializeOwned;
use serde::ser::Error as _;
use serde::{Deserialize, Deserializer, Serialize};

use crate::wslc_common::process_env::EnvScope;

/// Upper bound on a single decoded frame (16 MiB). Guards the decoder against a
/// hostile or corrupt length prefix demanding an unbounded allocation.
pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;

/// Maximum UTF-8 byte length of an exec identifier or per-run token.
///
/// Both values are generated as 32-byte UUID hex strings. The larger bound
/// leaves room for diagnostics/test callers without allowing a control frame
/// to retain multi-megabyte map keys.
pub const MAX_EXEC_ID_BYTES: usize = 128;

/// Control-channel wire-protocol version. The daemon and client are shipped
/// from the same build, so in normal operation both sides always match; the
/// version guards against a stale daemon left running by a different mxc
/// install. Bump only for incompatible changes to framing or message shape.
///
/// A new optional field counts: these structs do not deny unknown fields, so a
/// daemon predating one drops it and acts on a request it only partly
/// understood.
pub const PROTOCOL_VERSION: u32 = 7;

fn deserialize_exec_id<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let value = String::deserialize(deserializer)?;
    if value.is_empty() {
        return Err(<D::Error as serde::de::Error>::custom(
            "exec identifier must not be empty",
        ));
    }
    if value.len() > MAX_EXEC_ID_BYTES {
        return Err(<D::Error as serde::de::Error>::custom(format!(
            "exec identifier exceeds {MAX_EXEC_ID_BYTES} bytes"
        )));
    }
    Ok(value)
}

// ---------------------------------------------------------------------------
// Per-phase config structs (daemon-internal; NOT the public wire schema)
// ---------------------------------------------------------------------------

/// One host→container directory mount, mirroring the one-shot runner's volume
/// handling. Paths are host-absolute; `container` is the in-container mount
/// point.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VolumeMount {
    pub host: String,
    pub container: String,
    pub read_only: bool,
}

/// Container network mode. Mirrors exactly what the one-shot WSLc runner
/// supports — no host-filtering / egress allow-deny (the SDK grants no
/// `CAP_NET_ADMIN` and cannot give VM-level enforcement without breaking other
/// security promises, so there is no iptables path).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetworkMode {
    /// Isolated: no container networking.
    #[default]
    None,
    /// Bridged (NAT) networking.
    Bridged,
}

/// A host → container TCP forward applied to one sandbox's container.
///
/// TCP-only: the WSLC runtime returns `E_NOTIMPL` for UDP, and the exact
/// contract admits no other protocol, so none is carried on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortMapping {
    pub windows_port: u16,
    pub container_port: u16,
}

/// Inputs to `provision`: ensure the shared session (booting the WSL2 utility VM
/// on first provision), resolve the image, and create the container. Mirrors the
/// session/container-level fields of the one-shot `WslcConfig` plus the
/// container's volume and network policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProvisionConfig {
    /// Container image reference (e.g. `alpine:latest`).
    pub image: String,
    /// Optional local tar to import as the image instead of pulling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image_tar_path: Option<String>,
    /// Host↔container directory mounts.
    #[serde(default)]
    pub volumes: Vec<VolumeMount>,
    /// Container network mode.
    #[serde(default)]
    pub network: NetworkMode,
    /// Host → container TCP forwards for this sandbox's container.
    #[serde(default)]
    pub port_mappings: Vec<PortMapping>,
}

/// Inputs to `start`: the container was created at provision; start boots it.
/// Carries only the sandbox id — network/volume policy is immutable post-provision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StartConfig {
    pub sandbox_id: String,
}

/// Inputs to `exec`: run one command in the started container and stream its
/// stdio back over the pipe.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecConfig {
    /// Correlates this run with an out-of-band [`DaemonRequest::CancelExec`].
    #[serde(deserialize_with = "deserialize_exec_id")]
    pub exec_id: String,
    /// Identifies this specific use of `exec_id`, preventing a delayed
    /// cancellation from affecting a later run that reuses the same ID.
    #[serde(deserialize_with = "deserialize_exec_id")]
    pub run_token: String,
    pub sandbox_id: String,
    /// Command line to run inside the container (shell-interpreted, mirroring
    /// the one-shot runner's `script_code`).
    pub script_code: String,
    /// Working directory inside the container (empty = container default).
    #[serde(default)]
    pub working_directory: String,
    /// Environment variables applied to the process, as `(name, value)` pairs.
    #[serde(default)]
    pub env: Vec<(String, String)>,

    /// How `env` combines with the container image's own environment.
    #[serde(default)]
    pub env_scope: EnvScope,
    /// Timeout in milliseconds (0 = no timeout).
    #[serde(default)]
    pub timeout_ms: u32,
}

/// Inputs to `stop`: stop the running container, keeping it created for a later
/// `start`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StopConfig {
    pub sandbox_id: String,
}

/// Inputs to `deprovision`: delete the container and drop its refcount; the
/// daemon releases the shared session once the last container is gone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeprovisionConfig {
    pub sandbox_id: String,
}

/// Inputs to `cancel_exec`: request termination of one admitted exec without
/// stopping its warm container.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CancelExecConfig {
    #[serde(deserialize_with = "deserialize_exec_id")]
    pub exec_id: String,
    #[serde(deserialize_with = "deserialize_exec_id")]
    pub run_token: String,
}

/// Confirmed terminal outcome shared by the daemon worker and client.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecTerminal {
    /// The process exited naturally with its exit code.
    Exited(i32),
    /// The configured timeout elapsed and termination was confirmed.
    TimedOut,
    /// Caller cancellation was observed and termination was confirmed.
    Cancelled,
}

// ---------------------------------------------------------------------------
// Control frames
// ---------------------------------------------------------------------------

/// A control request sent by a phase process to the daemon.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum DaemonRequest {
    /// Ensure session + create container. Replies [`DaemonResponse::Provisioned`].
    Provision(ProvisionConfig),
    /// Boot the created container. Replies [`DaemonResponse::Ok`].
    Start(StartConfig),
    /// Run a command and stream its stdio. After an [`DaemonResponse::Ok`]
    /// admission, the daemon streams output followed by one terminal frame.
    Exec(ExecConfig),
    /// Request termination of one admitted exec. Replies [`DaemonResponse::Ok`].
    CancelExec(CancelExecConfig),
    /// Stop the running container. Replies [`DaemonResponse::Ok`].
    Stop(StopConfig),
    /// Delete the container (refcount--). Replies [`DaemonResponse::Ok`].
    Deprovision(DeprovisionConfig),
    /// Liveness probe. Replies [`DaemonResponse::Pong`].
    Ping,
}

/// The daemon's reply to a [`DaemonRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum DaemonResponse {
    /// `provision` succeeded; carries the minted sandbox id (the addressable
    /// handle a later phase presents).
    Provisioned { sandbox_id: String },
    /// Generic success (start / stop / deprovision, and exec admission).
    Ok,
    /// Reply to [`DaemonRequest::Ping`].
    Pong,
    /// The request failed or was refused. `kind` is a stable machine-readable
    /// token (see [`ErrKind`]); `message` is human-readable detail.
    Err { kind: ErrKind, message: String },
}

/// Stable, machine-readable classification of a [`DaemonResponse::Err`], so the
/// client can map daemon failures onto the appropriate `MxcError` variant
/// without string-matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrKind {
    /// The referenced sandbox id is unknown to the daemon.
    NotProvisioned,

    /// The sandbox exists but is not in a state that permits the request
    /// (e.g. exec before start).
    NotStarted,

    /// Another exec already holds the container's single-flight slot.
    Busy,

    /// The container/session is still coming up.
    NotReady,

    /// The client speaks a different protocol version than this daemon.
    Protocol,

    /// The host cannot run WSLc at all — the SDK or a WSL component it depends
    /// on is missing.
    Unavailable,

    /// The request cannot be honored as written.
    Rejected,

    /// A backend/SDK-level failure while servicing the request.
    Backend,

    /// A kind this build does not recognize, from a daemon newer than it.
    #[serde(other)]
    Unknown,
}

// ---------------------------------------------------------------------------
// Exec data-phase stream frames
// ---------------------------------------------------------------------------

/// A frame exchanged during the exec data phase (after an admitted
/// [`DaemonRequest::Exec`]). Client→daemon carries [`StreamFrame::Stdin`];
/// daemon→client carries [`StreamFrame::Stdout`] / [`StreamFrame::Stderr`] and
/// one terminal exit, timeout, cancellation, or error frame.
///
/// The raw byte payloads are base64-encoded on the wire (see [`base64_bytes`]).
/// serde_json renders a `Vec<u8>` as a JSON array of decimal integers (`[104,
/// 105, ...]`), roughly **4 bytes of wire per payload byte**, and since
/// [`MAX_FRAME_SIZE`] is measured against the *encoded* frame that would cut
/// effective throughput to ~1/4. base64 is ~1.33x instead, while keeping the
/// single uniform JSON framing (no separate binary path to test).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StreamFrame {
    /// Client→daemon: bytes to write to the process stdin. An empty payload
    /// signals stdin EOF.
    Stdin {
        #[serde(with = "base64_bytes")]
        data: Vec<u8>,
    },
    /// Daemon→client: bytes read from the process stdout.
    Stdout {
        #[serde(with = "base64_bytes")]
        data: Vec<u8>,
    },
    /// Daemon→client: bytes read from the process stderr.
    Stderr {
        #[serde(with = "base64_bytes")]
        data: Vec<u8>,
    },
    /// Daemon→client: terminal frame; the process exited with `code`. No more
    /// stream frames follow.
    Exit { code: i32 },
    /// Daemon→client: terminal frame; the request timeout elapsed and the
    /// process was confirmed terminated.
    TimedOut,
    /// Daemon→client: terminal frame; an explicit cancellation request was
    /// accepted and the process was confirmed terminated.
    Cancelled,
    /// Daemon→client: live output was dropped; the terminal frame still follows.
    Truncated,
    /// Daemon→client: terminal frame; the exec failed before or during the run.
    Error { message: String },
}

/// serde adapter that (de)serializes a `Vec<u8>` as a base64 string rather than
/// a JSON integer array. Used for the [`StreamFrame`] byte payloads to keep the
/// exec data phase compact over the wire.
mod base64_bytes {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&STANDARD.encode(bytes))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
        let encoded = String::deserialize(deserializer)?;
        STANDARD.decode(&encoded).map_err(serde::de::Error::custom)
    }
}

// ---------------------------------------------------------------------------
// Framing helpers (generic over any serde message type)
// ---------------------------------------------------------------------------

/// Serialize `msg` into a length-prefixed frame: `[len: u32 LE][json: len bytes]`.
pub fn encode_frame<T: Serialize>(msg: &T) -> Result<Vec<u8>, serde_json::Error> {
    let json = serde_json::to_vec(msg)?;
    if json.len() > MAX_FRAME_SIZE {
        return Err(serde_json::Error::custom(
            "message too large for protocol framing",
        ));
    }
    let len = json.len() as u32;
    let mut frame = Vec::with_capacity(4 + json.len());
    frame.extend_from_slice(&len.to_le_bytes());
    frame.extend_from_slice(&json);
    Ok(frame)
}

/// Result of attempting to decode one frame from the front of a byte buffer.
#[derive(Debug, PartialEq, Eq)]
pub enum DecodeResult<T> {
    /// A complete message was decoded; drain `consumed` bytes from the front of
    /// the buffer before decoding again.
    Message { message: T, consumed: usize },
    /// The buffer does not yet hold a full frame; read more bytes and retry.
    Incomplete,
}

/// Try to decode one message of type `T` from the front of `buf`.
///
/// Returns [`DecodeResult::Incomplete`] when fewer than `4 + len` bytes are
/// present. A length prefix exceeding [`MAX_FRAME_SIZE`] is a hard error rather
/// than an unbounded wait.
pub fn decode_frame<T: DeserializeOwned>(buf: &[u8]) -> Result<DecodeResult<T>, serde_json::Error> {
    if buf.len() < 4 {
        return Ok(DecodeResult::Incomplete);
    }
    let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
    if len > MAX_FRAME_SIZE {
        return Err(serde_json::Error::custom("frame length exceeds maximum"));
    }
    let total = 4 + len;
    if buf.len() < total {
        return Ok(DecodeResult::Incomplete);
    }
    let message: T = serde_json::from_slice(&buf[4..total])?;
    Ok(DecodeResult::Message {
        message,
        consumed: total,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn roundtrip<T>(msg: T)
    where
        T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug,
    {
        let frame = encode_frame(&msg).unwrap();
        match decode_frame::<T>(&frame).unwrap() {
            DecodeResult::Message { message, consumed } => {
                assert_eq!(message, msg);
                assert_eq!(consumed, frame.len());
            }
            DecodeResult::Incomplete => panic!("expected a complete message"),
        }
    }

    #[test]
    fn roundtrip_provision() {
        roundtrip(DaemonRequest::Provision(ProvisionConfig {
            image: "alpine:latest".to_string(),
            image_tar_path: Some(r"C:\images\alpine.tar".to_string()),
            volumes: vec![VolumeMount {
                host: r"C:\work".to_string(),
                container: "/work".to_string(),
                read_only: true,
            }],
            network: NetworkMode::Bridged,
            port_mappings: vec![PortMapping {
                windows_port: 8080,
                container_port: 80,
            }],
        }));
    }

    #[test]
    fn roundtrip_each_request_variant() {
        roundtrip(DaemonRequest::Start(StartConfig {
            sandbox_id: "wslc:abc123".to_string(),
        }));
        roundtrip(DaemonRequest::Exec(ExecConfig {
            exec_id: "exec-1".to_string(),
            run_token: "run-1".to_string(),
            sandbox_id: "wslc:abc123".to_string(),
            script_code: "echo hi".to_string(),
            working_directory: "/work".to_string(),
            env: vec![("PATH".to_string(), "/usr/bin".to_string())],
            env_scope: EnvScope::Replace,
            timeout_ms: 30_000,
        }));
        roundtrip(DaemonRequest::CancelExec(CancelExecConfig {
            exec_id: "exec-1".to_string(),
            run_token: "run-1".to_string(),
        }));
        roundtrip(DaemonRequest::Stop(StopConfig {
            sandbox_id: "wslc:abc123".to_string(),
        }));
        roundtrip(DaemonRequest::Deprovision(DeprovisionConfig {
            sandbox_id: "wslc:abc123".to_string(),
        }));
        roundtrip(DaemonRequest::Ping);
    }

    #[test]
    fn an_exec_config_keeps_repeated_environment_names_in_order() {
        // `env -i` and the SDK's setter both apply entries left to right, so a
        // reordered or deduplicated wire form would hand the child a different
        // value than the caller asked for.
        let config = ExecConfig {
            exec_id: "exec-1".to_string(),
            run_token: "run-1".to_string(),
            sandbox_id: "wslc:abc123".to_string(),
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            env: vec![
                ("FOO".to_string(), "1".to_string()),
                ("BAR".to_string(), "keep".to_string()),
                ("FOO".to_string(), "2".to_string()),
            ],
            env_scope: EnvScope::Replace,
            timeout_ms: 0,
        };

        let frame = encode_frame(&DaemonRequest::Exec(config.clone())).unwrap();
        let DecodeResult::Message { message, .. } = decode_frame::<DaemonRequest>(&frame).unwrap()
        else {
            panic!("expected a complete message");
        };
        let DaemonRequest::Exec(decoded) = message else {
            panic!("expected an exec request");
        };

        assert_eq!(decoded.env, config.env);
    }

    #[test]
    fn roundtrip_each_response_variant() {
        roundtrip(DaemonResponse::Provisioned {
            sandbox_id: "wslc:abc123".to_string(),
        });
        roundtrip(DaemonResponse::Ok);
        roundtrip(DaemonResponse::Pong);
        for kind in [
            ErrKind::NotProvisioned,
            ErrKind::NotStarted,
            ErrKind::Busy,
            ErrKind::NotReady,
            ErrKind::Protocol,
            ErrKind::Unavailable,
            ErrKind::Rejected,
            ErrKind::Backend,
            ErrKind::Unknown,
        ] {
            roundtrip(DaemonResponse::Err {
                kind,
                message: "detail".to_string(),
            });
        }
    }

    #[test]
    fn unrecognized_err_kind_decodes_as_unknown() {
        let wire = r#"{"status":"err","kind":"some_future_kind","message":"detail"}"#;
        let decoded: DaemonResponse = serde_json::from_str(wire).expect("decode unknown kind");
        assert_eq!(
            decoded,
            DaemonResponse::Err {
                kind: ErrKind::Unknown,
                message: "detail".to_string(),
            }
        );
    }

    #[test]
    fn oversized_exec_identifiers_are_rejected_during_decode() {
        let oversized = "x".repeat(MAX_EXEC_ID_BYTES + 1);
        let exec = serde_json::json!({
            "op": "exec",
            "exec_id": oversized,
            "run_token": "run-1",
            "sandbox_id": "wslc:abc123",
            "script_code": "true",
            "working_directory": "",
            "env": [],
            "timeout_ms": 0
        });
        assert!(serde_json::from_value::<DaemonRequest>(exec).is_err());

        let cancel = serde_json::json!({
            "op": "cancel_exec",
            "exec_id": "exec-1",
            "run_token": "x".repeat(MAX_EXEC_ID_BYTES + 1)
        });
        assert!(serde_json::from_value::<DaemonRequest>(cancel).is_err());
    }

    #[test]
    fn roundtrip_stream_frames() {
        roundtrip(StreamFrame::Stdin {
            data: b"input".to_vec(),
        });
        roundtrip(StreamFrame::Stdout {
            data: b"out".to_vec(),
        });
        roundtrip(StreamFrame::Stderr {
            data: b"err".to_vec(),
        });
        roundtrip(StreamFrame::Exit { code: 42 });
        roundtrip(StreamFrame::TimedOut);
        roundtrip(StreamFrame::Cancelled);
        roundtrip(StreamFrame::Truncated);
        roundtrip(StreamFrame::Error {
            message: "spawn failed".to_string(),
        });
    }

    #[test]
    fn stream_frame_bytes_roundtrip_including_non_utf8() {
        // Arbitrary bytes (incl. non-UTF8, NUL, 0xFF) must survive the base64
        // wire encoding exactly.
        let raw: Vec<u8> = (0u16..=255).map(|b| b as u8).collect();
        roundtrip(StreamFrame::Stdout { data: raw.clone() });
        roundtrip(StreamFrame::Stderr { data: raw.clone() });
        roundtrip(StreamFrame::Stdin { data: raw });
    }

    #[test]
    fn stream_frame_payload_is_base64_not_integer_array() {
        // Guards the compact wire encoding: the payload is a base64 string, not
        // serde_json's default `[104, 105, ...]` integer array (~4x larger).
        let json = serde_json::to_string(&StreamFrame::Stdout {
            data: b"hi".to_vec(),
        })
        .unwrap();
        assert!(
            json.contains("\"data\":\"aGk=\""),
            "unexpected wire: {json}"
        );
        assert!(
            !json.contains('['),
            "payload must not be an integer array: {json}"
        );
    }

    #[test]
    fn network_mode_defaults_to_none() {
        assert_eq!(NetworkMode::default(), NetworkMode::None);
    }

    #[test]
    fn decode_incomplete_header() {
        let r: DecodeResult<DaemonRequest> = decode_frame(&[0u8; 3]).unwrap();
        assert_eq!(r, DecodeResult::Incomplete);
    }

    #[test]
    fn decode_incomplete_body() {
        // Header claims 100 bytes; only 10 present.
        let mut buf = Vec::new();
        buf.extend_from_slice(&100u32.to_le_bytes());
        buf.extend_from_slice(&[0u8; 10]);
        let r: DecodeResult<DaemonRequest> = decode_frame(&buf).unwrap();
        assert_eq!(r, DecodeResult::Incomplete);
    }

    #[test]
    fn decode_empty_buffer_is_incomplete() {
        let r: DecodeResult<DaemonRequest> = decode_frame(&[]).unwrap();
        assert_eq!(r, DecodeResult::Incomplete);
    }

    #[test]
    fn decode_rejects_oversized_length_prefix() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&(MAX_FRAME_SIZE as u32 + 1).to_le_bytes());
        let r: Result<DecodeResult<DaemonRequest>, _> = decode_frame(&buf);
        assert!(r.is_err());
    }

    #[test]
    fn frame_length_prefix_matches_payload() {
        let frame = encode_frame(&DaemonRequest::Ping).unwrap();
        let declared = u32::from_le_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize;
        assert_eq!(declared, frame.len() - 4);
    }

    #[test]
    fn two_frames_decode_sequentially() {
        let f1 = encode_frame(&DaemonRequest::Ping).unwrap();
        let f2 = encode_frame(&DaemonResponse::Pong).unwrap();
        let mut buf = Vec::new();
        buf.extend_from_slice(&f1);
        buf.extend_from_slice(&f2);

        let consumed = match decode_frame::<DaemonRequest>(&buf).unwrap() {
            DecodeResult::Message { message, consumed } => {
                assert_eq!(message, DaemonRequest::Ping);
                consumed
            }
            DecodeResult::Incomplete => panic!("expected first frame"),
        };
        match decode_frame::<DaemonResponse>(&buf[consumed..]).unwrap() {
            DecodeResult::Message {
                message,
                consumed: c2,
            } => {
                assert_eq!(message, DaemonResponse::Pong);
                assert_eq!(consumed + c2, buf.len());
            }
            DecodeResult::Incomplete => panic!("expected second frame"),
        }
    }

    #[test]
    fn decode_rejects_malformed_json_body() {
        let mut buf = Vec::new();
        let body = b"{ not json";
        buf.extend_from_slice(&(body.len() as u32).to_le_bytes());
        buf.extend_from_slice(body);
        let r: Result<DecodeResult<DaemonRequest>, _> = decode_frame(&buf);
        assert!(r.is_err());
    }

    #[test]
    fn an_exec_config_without_an_env_scope_defaults_to_merge() {
        let without = r#"{"exec_id":"e","run_token":"r","sandbox_id":"s","script_code":"run"}"#;
        let parsed: ExecConfig = serde_json::from_str(without).expect("env_scope is optional");

        assert_eq!(parsed.env_scope, EnvScope::Merge);
    }
}