mxc-sdk 1.0.0

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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Phase-process side of the state-aware WSLc control protocol.
//!
//! Each state-aware lifecycle phase (`provision` / `start` / `exec` / `stop` /
//! `deprovision`) runs as a short-lived process that drives the long-lived
//! `wxc-wslc-daemon` over an owner-only named pipe. This module is the client
//! half: it discovers (or spawns) the daemon, then issues one
//! [`DaemonRequest`] per connection and decodes the [`DaemonResponse`] (and, for
//! exec, the [`StreamFrame`] data phase).
//!
//! # Sync by design
//! The daemon server is async (tokio), but the client is deliberately
//! **blocking**: a phase process is otherwise synchronous, `wslc_common` has no
//! tokio dependency, and the framing (`[len: u32 LE][json]`) is trivial over
//! blocking `std::io`. A Windows named pipe opens as an ordinary synchronous
//! file handle, so `std::fs::File` read/write is all that is needed.
//!
//! # Discovery / spawn
//! [`DaemonClient::connect`] fast-paths onto a live, ready, protocol-compatible
//! daemon. Otherwise it takes the cross-process [`TransitionLock`] (so two phase
//! processes cannot both spawn a daemon), re-checks, spawns
//! `wxc-wslc-daemon.exe` (co-located with the loaded MXC native module) if
//! none exists, and waits for it to publish a `ready` record.
//!
//! Windows-only: the daemon and its named-pipe transport are a Windows feature
//! (`daemon_record` provides non-Windows stubs, but there is no daemon there).

use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;
#[cfg(not(windows))]
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::wslc_common::container_steps::OutStream;
use crate::wslc_common::daemon_protocol::{
    encode_frame, CancelExecConfig, DaemonRequest, DaemonResponse, DeprovisionConfig, ErrKind,
    ExecConfig, ExecTerminal, ProvisionConfig, StartConfig, StopConfig, StreamFrame,
    MAX_FRAME_SIZE, PROTOCOL_VERSION,
};
use crate::wslc_common::daemon_record::{live_daemon, DaemonRecord, TransitionLock};

/// Max wait for a freshly spawned (or concurrently starting) daemon to publish a
/// `ready` record.
const READY_TIMEOUT: Duration = Duration::from_secs(60);

/// Max wait to acquire the daemon spawn/teardown transition lock. Must exceed
/// [`READY_TIMEOUT`]: the lock holder retains it for the whole readiness wait, so
/// a second client has to be willing to wait at least that long — otherwise it
/// would give up while the first daemon is still validly starting and report a
/// spurious failure.
const SPAWN_LOCK_TIMEOUT: Duration = Duration::from_secs(75);

/// Overall per-request response deadline for a non-streaming daemon call
/// (`provision` / `start` / `stop` / `deprovision` / `ping`). The daemon services
/// every lifecycle op on a single apartment-affine worker, so a call that hangs
/// on the SDK would otherwise block this phase process — and, transitively, every
/// later lifecycle command including teardown — forever. Bounding the client read
/// lets a wedged daemon surface an actionable timeout instead of blocking
/// indefinitely. Generous enough to cover a cold image pull at `provision`.
const CALL_TIMEOUT: Duration = Duration::from_secs(600);

/// Env override (positive whole seconds) for [`READY_TIMEOUT`]. Lets negative
/// tests (readiness failure) fail fast instead of waiting a minute.
const READY_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_READY_TIMEOUT_SECS";

/// Env override (positive whole seconds) for [`SPAWN_LOCK_TIMEOUT`].
const SPAWN_LOCK_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_SPAWN_LOCK_TIMEOUT_SECS";

/// Env override (positive whole seconds) for [`CALL_TIMEOUT`].
pub const CALL_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_CALL_TIMEOUT_SECS";

/// How long to wait for a cancelled reader to unwind and drop the pipe; it only
/// covers the return of an already-aborted read.
const READER_CANCEL_GRACE: Duration = Duration::from_secs(5);

/// How long to wait for a reply the reader produced just as the deadline
/// expired; it only covers handing over a value that already exists.
const READER_RECOVERY_GRACE: Duration = Duration::from_millis(250);

/// Resolve a `Duration` from an environment variable holding a positive whole
/// number of seconds, falling back to `default` when the variable is unset,
/// empty, non-numeric, or zero. Mirrors the daemon-side override pattern so the
/// production defaults stand unless a test/operator deliberately tunes them.
fn duration_from_env(var: &str, default: Duration) -> Duration {
    resolve_duration(std::env::var(var).ok().as_deref(), default)
}

/// Pure core of [`duration_from_env`]: map an optional raw string to a
/// `Duration`, using `default` unless the string is a positive integer number
/// of seconds. Split out so the parsing rules are unit-testable without mutating
/// process-global environment state.
fn resolve_duration(raw: Option<&str>, default: Duration) -> Duration {
    raw.and_then(|s| s.trim().parse::<u64>().ok())
        .filter(|&secs| secs > 0)
        .map(Duration::from_secs)
        .unwrap_or(default)
}

/// The daemon-readiness wait, honoring [`READY_TIMEOUT_ENV`].
fn ready_timeout() -> Duration {
    duration_from_env(READY_TIMEOUT_ENV, READY_TIMEOUT)
}

/// The spawn/teardown transition-lock wait, honoring [`SPAWN_LOCK_TIMEOUT_ENV`].
fn spawn_lock_timeout() -> Duration {
    duration_from_env(SPAWN_LOCK_TIMEOUT_ENV, SPAWN_LOCK_TIMEOUT)
}

/// The overall per-request response deadline, honoring [`CALL_TIMEOUT_ENV`].
/// The overall per-request response deadline, honoring [`CALL_TIMEOUT_ENV`].
///
/// Public so a pull can bound itself against the deadline its caller is
/// waiting on.
pub fn call_timeout() -> Duration {
    duration_from_env(CALL_TIMEOUT_ENV, CALL_TIMEOUT)
}

/// Poll cadence while waiting for the `ready` record.
const READY_POLL: Duration = Duration::from_millis(100);

/// Max wait when opening the daemon pipe, to ride out the brief window between
/// the server accepting one client and re-creating the next listening instance.
const OPEN_TIMEOUT: Duration = Duration::from_secs(10);

/// Retry cadence for a transiently busy/absent pipe instance.
const OPEN_RETRY: Duration = Duration::from_millis(20);

// Win32 error codes for the transient pipe-open conditions worth retrying.
const ERROR_FILE_NOT_FOUND: i32 = 2;
const ERROR_PIPE_BUSY: i32 = 231;

/// The captured result of an exec run: the exit code plus fully-buffered
/// stdout/stderr. Prefer [`DaemonClient::exec_streaming`] to relay output as it
/// arrives; this buffering variant is for callers (and tests) that want the
/// whole capture at once.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExecResult {
    pub exit_code: i32,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
}

/// Terminal outcome of a streaming daemon exec.
pub type DaemonExecOutcome = ExecTerminal;

/// How a streaming exec finished, and whether the daemon had to drop live
/// output on the way there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DaemonExecCompletion {
    pub outcome: DaemonExecOutcome,
    pub truncated: bool,
}

/// An exec request that the daemon has admitted and whose pipe is now carrying
/// only the [`StreamFrame`] data phase.
#[derive(Debug)]
pub(crate) struct AdmittedExec {
    pipe: File,
}

impl AdmittedExec {
    /// Consume output frames until the daemon reports the terminal outcome.
    pub(crate) fn read_to_completion(
        mut self,
        mut on_output: impl FnMut(OutStream, &[u8]),
    ) -> DaemonResult<DaemonExecCompletion> {
        let mut truncated = false;
        loop {
            let outcome = match read_frame::<StreamFrame>(&mut self.pipe)? {
                StreamFrame::Stdout { data } => {
                    on_output(OutStream::Stdout, &data);
                    continue;
                }
                StreamFrame::Stderr { data } => {
                    on_output(OutStream::Stderr, &data);
                    continue;
                }
                StreamFrame::Truncated => {
                    truncated = true;
                    continue;
                }
                StreamFrame::Exit { code } => DaemonExecOutcome::Exited(code),
                StreamFrame::TimedOut => DaemonExecOutcome::TimedOut,
                StreamFrame::Cancelled => DaemonExecOutcome::Cancelled,
                StreamFrame::Error { message } => {
                    return Err(DaemonError::transport(format!(
                        "exec failed: {message}{}",
                        truncation_suffix(truncated)
                    )))
                }
                StreamFrame::Stdin { .. } => {
                    return Err(DaemonError::transport(
                        "protocol error: daemon sent a Stdin frame to the client",
                    ))
                }
            };
            return Ok(DaemonExecCompletion { outcome, truncated });
        }
    }
}

/// Suffix naming lost output, for an error whose own classification the caller
/// still needs.
pub(crate) fn truncation_suffix(truncated: bool) -> &'static str {
    if truncated {
        " (live output was truncated: it was not drained fast enough and a bounded output queue \
         overflowed)"
    } else {
        ""
    }
}

/// A typed failure from a daemon call. `Daemon` carries the daemon's stable
/// [`ErrKind`] token so the state-aware backend can map it onto the matching
/// `MxcError` code (e.g. `NotProvisioned` / `NotStarted`) without string
/// matching; `Transport` covers connection, framing, and protocol violations,
/// which map to a generic backend error.
#[derive(Debug)]
pub enum DaemonError {
    /// The daemon returned a structured [`DaemonResponse::Err`].
    Daemon { kind: ErrKind, message: String },
    /// A transport / protocol failure (connect, framing, or an unexpected
    /// reply shape).
    Transport(anyhow::Error),
}

impl DaemonError {
    fn transport(message: impl Into<String>) -> Self {
        Self::Transport(anyhow::anyhow!(message.into()))
    }
}

impl std::fmt::Display for DaemonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Daemon { kind, message } => write!(f, "daemon error [{kind:?}]: {message}"),
            Self::Transport(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for DaemonError {}

impl From<anyhow::Error> for DaemonError {
    fn from(e: anyhow::Error) -> Self {
        Self::Transport(e)
    }
}

/// Convenience alias for the typed daemon-call result.
pub type DaemonResult<T> = std::result::Result<T, DaemonError>;

/// A connected handle to the live daemon. Cheap to hold: it caches only the
/// resolved pipe name plus the daemon's trusted identity (PID + creation time
/// from the discovery record), and opens a fresh pipe connection per request
/// (one request per connection, matching the server).
#[derive(Clone)]
pub struct DaemonClient {
    pipe_name: String,
    /// PID of the daemon process this client trusts, from the discovery record.
    /// Every opened pipe is authenticated against this so a hostile same-user
    /// pipe squatter cannot impersonate the daemon.
    #[cfg_attr(not(windows), allow(dead_code))]
    server_pid: u32,
    /// Creation time of `server_pid` from the record, to defeat PID reuse: the
    /// connected server must be the exact process the record identified.
    #[cfg_attr(not(windows), allow(dead_code))]
    server_pid_creation_time: u64,
}

impl DaemonClient {
    /// Discover the live daemon, spawning it if necessary, and return a client
    /// bound to its pipe.
    pub fn connect() -> Result<Self> {
        // Fast path: a live, ready, compatible daemon already exists.
        if let Some(record) = ready_daemon()? {
            return Ok(Self::from_record(&record));
        }

        // Slow path: serialise spawn/teardown so two phase processes cannot both
        // spawn a daemon (or race a spawn against a teardown).
        let _lock = TransitionLock::acquire(spawn_lock_timeout())
            .context("acquire daemon spawn transition lock")?;

        let ready_timeout = ready_timeout();
        let deadline = Instant::now() + ready_timeout;
        let mut spawned = false;
        loop {
            match live_daemon()? {
                Some(record) if !record.protocol_compatible() => {
                    bail!(
                        "a running wslc daemon speaks control protocol v{} but this build speaks \
                         v{}; refusing to drive it (stop the stale daemon and retry)",
                        record.protocol_version,
                        PROTOCOL_VERSION
                    );
                }
                Some(record) if record.ready => return Ok(Self::from_record(&record)),
                // A daemon is alive but still starting up: keep waiting for it to
                // flip `ready` rather than spawning a duplicate.
                Some(_) => {}
                None => {
                    if !spawned {
                        spawn_daemon()?;
                        spawned = true;
                    }
                    // Otherwise we already spawned; keep polling for its record.
                }
            }

            if Instant::now() >= deadline {
                bail!(
                    "timed out after {ready_timeout:?} waiting for the wslc daemon to become ready"
                );
            }
            std::thread::sleep(READY_POLL);
        }
    }

    fn from_record(record: &DaemonRecord) -> Self {
        Self {
            pipe_name: record.pipe_name.clone(),
            server_pid: record.pid,
            server_pid_creation_time: record.pid_creation_time,
        }
    }

    /// Liveness probe. Returns `Ok(())` iff the daemon answers with `Pong`.
    pub fn ping(&self) -> DaemonResult<()> {
        match self.call(&DaemonRequest::Ping)? {
            DaemonResponse::Pong => Ok(()),
            DaemonResponse::Err { kind, message } => Err(DaemonError::Daemon { kind, message }),
            other => Err(DaemonError::transport(format!(
                "unexpected reply to ping: {other:?}"
            ))),
        }
    }

    /// Provision a container; returns the daemon-minted sandbox id.
    pub fn provision(&self, config: ProvisionConfig) -> DaemonResult<String> {
        match self.call(&DaemonRequest::Provision(config))? {
            DaemonResponse::Provisioned { sandbox_id } => Ok(sandbox_id),
            DaemonResponse::Err { kind, message } => Err(DaemonError::Daemon { kind, message }),
            other => Err(DaemonError::transport(format!(
                "unexpected reply to provision: {other:?}"
            ))),
        }
    }

    /// Start a provisioned container.
    pub fn start(&self, config: StartConfig) -> DaemonResult<()> {
        expect_ok(self.call(&DaemonRequest::Start(config))?)
    }

    /// Stop a running container (keeps it created for a later `start`).
    pub fn stop(&self, config: StopConfig) -> DaemonResult<()> {
        expect_ok(self.call(&DaemonRequest::Stop(config))?)
    }

    /// Deprovision (delete) a container.
    pub fn deprovision(&self, config: DeprovisionConfig) -> DaemonResult<()> {
        expect_ok(self.call(&DaemonRequest::Deprovision(config))?)
    }

    /// Run a command in a started container to completion, returning its exit
    /// code and fully-buffered output.
    ///
    /// A convenience wrapper over [`exec_streaming`](Self::exec_streaming) that
    /// accumulates every stdout/stderr chunk into an [`ExecResult`].
    ///
    /// **Unbounded capture — trusted/bounded output only.** This buffers the
    /// entire stream in memory with no cap, so container-controlled output can
    /// exhaust the caller's process memory. It is intended for tests and callers
    /// that already know the command's output is small and bounded. Any path that
    /// relays or handles live/untrusted output must use
    /// [`exec_streaming`](Self::exec_streaming) (the production state-aware runner
    /// does), which buffers nothing and lets the caller apply its own policy.
    pub fn exec(&self, config: ExecConfig) -> DaemonResult<ExecResult> {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let completion = self.exec_streaming(config, |stream, data| match stream {
            OutStream::Stdout => stdout.extend_from_slice(data),
            OutStream::Stderr => stderr.extend_from_slice(data),
        })?;
        let exit_code = match completion.outcome {
            DaemonExecOutcome::Exited(code) => code,
            DaemonExecOutcome::TimedOut => {
                return Err(DaemonError::transport(format!(
                    "exec timed out{}",
                    truncation_suffix(completion.truncated)
                )))
            }
            DaemonExecOutcome::Cancelled => {
                return Err(DaemonError::transport(format!(
                    "exec was cancelled{}",
                    truncation_suffix(completion.truncated)
                )))
            }
        };
        if completion.truncated {
            return Err(DaemonError::transport(format!(
                "exec output was truncated before it could be captured (the process exited \
                 {exit_code})"
            )));
        }
        Ok(ExecResult {
            exit_code,
            stdout,
            stderr,
        })
    }

    /// Run a command in a started container, invoking `on_output` for each live
    /// stdout/stderr chunk **as it arrives**, and returning the exit code once
    /// the run completes.
    ///
    /// After the daemon admits the exec with `Ok`, this reads the
    /// [`StreamFrame`] data phase, dispatching `Stdout`/`Stderr` chunks to the
    /// callback until the terminal frame. Unlike [`exec`](Self::exec), nothing
    /// is buffered here — the caller decides what to do with each chunk.
    pub fn exec_streaming(
        &self,
        config: ExecConfig,
        on_output: impl FnMut(OutStream, &[u8]),
    ) -> DaemonResult<DaemonExecCompletion> {
        self.admit_exec(config)?.read_to_completion(on_output)
    }

    /// Submit an exec request and return once the daemon has admitted it.
    ///
    /// Keeping admission separate from stream consumption lets cancellable
    /// callers replay a cancellation that raced ahead of daemon admission.
    pub(crate) fn admit_exec(&self, config: ExecConfig) -> DaemonResult<AdmittedExec> {
        let mut pipe = self.open_pipe()?;
        write_frame(&mut pipe, &DaemonRequest::Exec(config))?;

        let timeout = call_timeout();
        let (pipe, response) = read_frame_with_deadline(
            move || {
                let response = read_frame::<DaemonResponse>(&mut pipe)?;
                Ok((pipe, response))
            },
            timeout,
        )?;

        match response {
            DaemonResponse::Ok => {}
            DaemonResponse::Err { kind, message } => {
                return Err(DaemonError::Daemon { kind, message })
            }
            other => {
                return Err(DaemonError::transport(format!(
                    "unexpected exec admission reply: {other:?}"
                )))
            }
        }

        Ok(AdmittedExec { pipe })
    }

    /// Request termination of an admitted exec. The request is idempotent: a
    /// late cancellation after natural completion is still success.
    pub fn cancel_exec(&self, exec_id: String, run_token: String) -> DaemonResult<()> {
        expect_ok(self.call(&DaemonRequest::CancelExec(CancelExecConfig {
            exec_id,
            run_token,
        }))?)
    }

    /// Issue a single non-streaming request on a fresh connection and return the
    /// daemon's reply.
    ///
    /// The response read is bounded by [`call_timeout`]: the daemon services
    /// every lifecycle op on one apartment-affine worker, so a hung SDK call
    /// would otherwise block this phase process (and thus later teardown)
    /// forever. On deadline we cancel the read — closing the pipe, so the daemon
    /// can release an undelivered sandbox — and return an actionable timeout.
    fn call(&self, request: &DaemonRequest) -> DaemonResult<DaemonResponse> {
        let mut pipe = self.open_pipe()?;
        write_frame(&mut pipe, request)?;
        let timeout = call_timeout();
        read_frame_with_deadline::<DaemonResponse, _>(move || read_frame(&mut pipe), timeout)
    }

    /// Open a fresh synchronous connection to the daemon pipe, retrying past the
    /// brief windows where every instance is momentarily busy or being recreated.
    ///
    /// SECURITY: the handle is opened with `SECURITY_SQOS_PRESENT |
    /// SECURITY_IDENTIFICATION` so a pipe server can only *identify* this
    /// (possibly elevated) phase process, never impersonate it; and once
    /// connected the server's PID/creation time is authenticated against the
    /// trusted discovery record before any request is sent, so a hostile
    /// same-user pipe squatter cannot pose as the daemon.
    fn open_pipe(&self) -> Result<File> {
        let deadline = Instant::now() + OPEN_TIMEOUT;
        let file = loop {
            match open_pipe_handle(&self.pipe_name) {
                Ok(file) => break file,
                Err(e) => {
                    let retryable = matches!(
                        e.raw_os_error(),
                        Some(ERROR_PIPE_BUSY) | Some(ERROR_FILE_NOT_FOUND)
                    );
                    if retryable && Instant::now() < deadline {
                        std::thread::sleep(OPEN_RETRY);
                        continue;
                    }
                    return Err(e).with_context(|| format!("open daemon pipe {}", self.pipe_name));
                }
            }
        };
        self.verify_server_identity(&file)?;
        Ok(file)
    }

    /// Authenticate the connected pipe server against the trusted discovery
    /// record. A mismatch means something other than the recorded daemon is
    /// answering on this pipe name — refuse to send it anything.
    #[cfg(windows)]
    fn verify_server_identity(&self, pipe: &File) -> Result<()> {
        use std::os::windows::io::AsRawHandle;
        use windows::Win32::Foundation::HANDLE;
        use windows::Win32::System::Pipes::GetNamedPipeServerProcessId;

        let handle = HANDLE(pipe.as_raw_handle());
        let mut server_pid: u32 = 0;
        // SAFETY: `handle` is a live pipe handle owned by `pipe`; `server_pid`
        // is a valid out pointer.
        unsafe { GetNamedPipeServerProcessId(handle, &mut server_pid) }
            .map_err(|e| anyhow::anyhow!("GetNamedPipeServerProcessId failed: {e}"))?;

        if server_pid != self.server_pid {
            bail!(
                "refusing to talk to daemon pipe {}: connected server pid {} does not match the \
                 trusted discovery record pid {} (possible pipe-squatting attempt)",
                self.pipe_name,
                server_pid,
                self.server_pid
            );
        }
        // Defeat PID reuse: the server must be the exact process the record
        // identified, not a new process that recycled the PID.
        match crate::wslc_common::daemon_record::process_creation_time(server_pid) {
            Some(ct) if ct == self.server_pid_creation_time => Ok(()),
            Some(ct) => bail!(
                "refusing to talk to daemon pipe {}: server pid {} creation time {} does not \
                 match the trusted record {} (pid reuse or spoofed server)",
                self.pipe_name,
                server_pid,
                ct,
                self.server_pid_creation_time
            ),
            None => bail!(
                "refusing to talk to daemon pipe {}: could not read the creation time of server \
                 pid {} to authenticate it",
                self.pipe_name,
                server_pid
            ),
        }
    }

    /// Non-Windows stub: there is no daemon (and no named-pipe transport) off
    /// Windows, so nothing to authenticate.
    #[cfg(not(windows))]
    fn verify_server_identity(&self, _pipe: &File) -> Result<()> {
        Ok(())
    }
}

/// Open the daemon pipe as an ordinary synchronous file handle.
///
/// On Windows the handle carries `SECURITY_SQOS_PRESENT |
/// SECURITY_IDENTIFICATION` so the pipe server is capped at the Identification
/// impersonation level and cannot act as this process.
fn open_pipe_handle(pipe_name: &str) -> std::io::Result<File> {
    let mut opts = OpenOptions::new();
    opts.read(true).write(true);
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        // Security quality-of-service flags for CreateFile: present bit plus the
        // Identification level (SecurityIdentification == 1, shifted into the
        // high word).
        const SECURITY_SQOS_PRESENT: u32 = 0x0010_0000;
        const SECURITY_IDENTIFICATION: u32 = 0x0001_0000;
        opts.custom_flags(SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION);
    }
    opts.open(pipe_name)
}

/// The live daemon iff it is ready and speaks this build's protocol version.
fn ready_daemon() -> Result<Option<DaemonRecord>> {
    match live_daemon()? {
        Some(record) if record.ready && record.protocol_compatible() => Ok(Some(record)),
        _ => Ok(None),
    }
}

/// Spawn `wxc-wslc-daemon.exe` (co-located with the loaded MXC native module). It
/// publishes its own discovery record; we do not hold a handle to it.
///
/// The WSLc SDK's session/container creation blocks forever without a console,
/// so the daemon is given its own new console with a hidden (`SW_HIDE`) window.
#[cfg(windows)]
fn spawn_daemon() -> Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows::core::{PCWSTR, PWSTR};
    use windows::Win32::Foundation::CloseHandle;
    use windows::Win32::System::Threading::{
        CreateProcessW, CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, PROCESS_INFORMATION,
        STARTF_USESHOWWINDOW, STARTUPINFOW,
    };

    let exe = daemon_exe_path()?;

    // Writable, NUL-terminated wide command line (`"<exe>"`); CreateProcessW may
    // modify the buffer in place, so it must be a mutable local that outlives the
    // call.
    let mut command_line: Vec<u16> = std::iter::once(u16::from(b'"'))
        .chain(exe.as_os_str().encode_wide())
        .chain([u16::from(b'"'), 0])
        .collect();

    // SW_HIDE == 0: the daemon owns a console but its window is never shown.
    let startup = STARTUPINFOW {
        cb: std::mem::size_of::<STARTUPINFOW>() as u32,
        dwFlags: STARTF_USESHOWWINDOW,
        wShowWindow: 0,
        ..Default::default()
    };
    let mut info = PROCESS_INFORMATION::default();

    // SAFETY: `command_line` is a writable NUL-terminated wide buffer that lives
    // across the call; `startup`/`info` are valid for its duration. We inherit no
    // handles (the new console supplies the daemon's stdio).
    unsafe {
        CreateProcessW(
            PCWSTR::null(),
            Some(PWSTR(command_line.as_mut_ptr())),
            None,
            None,
            false,
            CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
            None,
            PCWSTR::null(),
            &startup,
            &mut info,
        )
        .with_context(|| format!("spawn wslc daemon {}", exe.display()))?;

        // We never wait on the daemon; release the handles we own so they do not
        // leak (the daemon keeps running).
        let _ = CloseHandle(info.hProcess);
        let _ = CloseHandle(info.hThread);
    }
    Ok(())
}

/// Non-Windows stub so `wslc_common` still compiles off Windows (the daemon and
/// its named-pipe transport are Windows-only; this path is never reached).
#[cfg(not(windows))]
fn spawn_daemon() -> Result<()> {
    let exe = daemon_exe_path()?;
    Command::new(&exe)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| format!("spawn wslc daemon {}", exe.display()))?;
    Ok(())
}

/// Resolve the daemon executable path beside the module containing this code.
/// This is the executor directory for `wxc-exec.exe` and the NuGet native-asset
/// directory for `mxc_ffi.dll`.
fn daemon_exe_path() -> Result<PathBuf> {
    let module =
        crate::mxc_common::process_util::module_path_for_address(daemon_exe_path as *const ())
            .map_err(anyhow::Error::msg)?;
    let dir = module
        .parent()
        .context("MXC native module has no parent directory")?;
    let name = if cfg!(windows) {
        "wxc-wslc-daemon.exe"
    } else {
        "wxc-wslc-daemon"
    };
    Ok(dir.join(name))
}

/// Map a `DaemonResponse` expected to be a bare success into `DaemonResult<()>`.
fn expect_ok(response: DaemonResponse) -> DaemonResult<()> {
    match response {
        DaemonResponse::Ok => Ok(()),
        DaemonResponse::Err { kind, message } => Err(DaemonError::Daemon { kind, message }),
        other => Err(DaemonError::transport(format!(
            "unexpected reply (expected ok): {other:?}"
        ))),
    }
}

/// Serialise `msg` and write it as one length-prefixed frame.
fn write_frame<T: Serialize>(pipe: &mut File, msg: &T) -> Result<()> {
    let frame = encode_frame(msg).context("encode frame")?;
    pipe.write_all(&frame).context("write frame")?;
    pipe.flush().context("flush frame")?;
    Ok(())
}

/// Read exactly one length-prefixed frame and deserialise it.
fn read_frame<T: DeserializeOwned>(pipe: &mut File) -> Result<T> {
    let mut len_buf = [0u8; 4];
    pipe.read_exact(&mut len_buf)
        .context("read frame length prefix")?;
    let len = u32::from_le_bytes(len_buf) as usize;
    if len > MAX_FRAME_SIZE {
        bail!("incoming frame length {len} exceeds maximum {MAX_FRAME_SIZE}");
    }
    let mut body = vec![0u8; len];
    pipe.read_exact(&mut body).context("read frame body")?;
    serde_json::from_slice(&body).context("deserialise frame body")
}

/// Run a blocking frame `read` with an overall `timeout`.
///
/// A Windows named pipe opened as a synchronous `File` has no per-read timeout,
/// so the read runs on a spawned thread and we wait on an [`mpsc`] channel with
/// [`Receiver::recv_timeout`]. On timeout we cancel that blocked read and return
/// an actionable transport error rather than blocking forever behind a wedged
/// daemon.
///
/// [`mpsc`]: std::sync::mpsc
/// [`Receiver::recv_timeout`]: std::sync::mpsc::Receiver::recv_timeout
fn read_frame_with_deadline<T, F>(read: F, timeout: Duration) -> DaemonResult<T>
where
    T: Send + 'static,
    F: FnOnce() -> Result<T> + Send + 'static,
{
    use std::sync::mpsc::{channel, RecvTimeoutError};

    let (tx, rx) = channel();
    let reader = std::thread::spawn(move || {
        // The receiver may already be gone (we timed out); ignore the send error.
        let _ = tx.send(read());
    });

    match rx.recv_timeout(timeout) {
        Ok(result) => result.map_err(DaemonError::Transport),
        Err(RecvTimeoutError::Timeout) => match recover_or_cancel_read(reader, &rx) {
            Some(result) => result.map_err(DaemonError::Transport),
            None => Err(DaemonError::transport(format!(
                "timed out after {timeout:?} waiting for the wslc daemon to respond; it may be \
                 wedged on a prior operation (override with {CALL_TIMEOUT_ENV})"
            ))),
        },
        Err(RecvTimeoutError::Disconnected) => Err(DaemonError::transport(
            "wslc daemon reader thread ended without a response",
        )),
    }
}

/// Take the reply of a read that beat the deadline, or cancel one that did not.
///
/// The daemon releases an undelivered sandbox only when its response write
/// fails, which cannot happen while a parked reader holds this end open.
#[cfg(windows)]
fn recover_or_cancel_read<T>(
    reader: std::thread::JoinHandle<()>,
    rx: &std::sync::mpsc::Receiver<Result<T>>,
) -> Option<Result<T>> {
    use std::os::windows::io::AsRawHandle;
    use windows::Win32::Foundation::HANDLE;
    use windows::Win32::System::IO::CancelSynchronousIo;

    // SAFETY: `reader` owns the thread handle and keeps it alive across the call.
    let cancelled = unsafe { CancelSynchronousIo(HANDLE(reader.as_raw_handle())) }.is_ok();

    // Nothing was pending, so the read completed in the gap between the
    // deadline expiring and this call. The daemon recorded that reply as
    // delivered, so reporting a timeout would strand the sandbox it names.
    if !cancelled {
        return rx.recv_timeout(READER_RECOVERY_GRACE).ok();
    }

    // Hold here until the pipe is closed, so the daemon sees the disconnect
    // while the caller is still inside this call.
    let _ = rx.recv_timeout(READER_CANCEL_GRACE);
    None
}

/// No daemon transport exists off Windows, so nothing can be holding a pipe open.
#[cfg(not(windows))]
fn recover_or_cancel_read<T>(
    _reader: std::thread::JoinHandle<()>,
    _rx: &std::sync::mpsc::Receiver<Result<T>>,
) -> Option<Result<T>> {
    None
}

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

    #[test]
    fn daemon_exe_is_resolved_next_to_containing_module() {
        let path = daemon_exe_path().unwrap();
        let expected_dir = crate::mxc_common::process_util::module_path_for_address(
            daemon_exe_is_resolved_next_to_containing_module as *const (),
        )
        .unwrap()
        .parent()
        .unwrap()
        .to_path_buf();
        assert_eq!(path.parent().unwrap(), expected_dir);
        assert!(path
            .file_name()
            .unwrap()
            .to_string_lossy()
            .starts_with("wxc-wslc-daemon"));
    }

    #[test]
    fn expect_ok_maps_variants() {
        assert!(expect_ok(DaemonResponse::Ok).is_ok());

        let err = expect_ok(DaemonResponse::Err {
            kind: ErrKind::NotStarted,
            message: "sandbox not started".to_string(),
        })
        .unwrap_err();
        assert!(matches!(
            err,
            DaemonError::Daemon {
                kind: ErrKind::NotStarted,
                ..
            }
        ));
        assert!(err.to_string().contains("NotStarted"));
        assert!(err.to_string().contains("sandbox not started"));

        assert!(expect_ok(DaemonResponse::Pong).is_err());
    }

    #[test]
    fn daemon_error_display_carries_kind_and_message() {
        let err = DaemonError::Daemon {
            kind: ErrKind::Busy,
            message: "single-flight slot held".to_string(),
        };
        let text = err.to_string();
        assert!(text.contains("Busy"));
        assert!(text.contains("single-flight slot held"));
    }

    #[test]
    fn from_record_captures_server_identity() {
        use crate::wslc_common::daemon_record::RECORD_SCHEMA_VERSION;
        let record = DaemonRecord {
            schema_version: RECORD_SCHEMA_VERSION,
            pid: 4321,
            pid_creation_time: 0xABCD,
            pipe_name: r"\\.\pipe\mxc-wslc-test".to_string(),
            ready: true,
            protocol_version: PROTOCOL_VERSION,
        };
        let client = DaemonClient::from_record(&record);
        // The pipe server is authenticated against this identity in open_pipe;
        // losing it would silently disable the anti-squatting check.
        assert_eq!(client.pipe_name, record.pipe_name);
        assert_eq!(client.server_pid, 4321);
        assert_eq!(client.server_pid_creation_time, 0xABCD);
    }

    #[test]
    fn read_frame_with_deadline_returns_value_before_deadline() {
        let v: DaemonResult<u32> = read_frame_with_deadline(|| Ok(42u32), Duration::from_secs(5));
        assert_eq!(v.unwrap(), 42);
    }

    #[test]
    fn read_frame_with_deadline_times_out_on_wedged_reader() {
        // A deliberately non-responsive reader (mirrors a wedged daemon that
        // never answers) must surface an actionable timeout, not block forever.
        let start = Instant::now();
        let v: DaemonResult<u32> = read_frame_with_deadline(
            || {
                std::thread::sleep(Duration::from_secs(30));
                Ok(0u32)
            },
            Duration::from_millis(100),
        );
        let err = v.unwrap_err();
        assert!(matches!(err, DaemonError::Transport(_)));
        let text = err.to_string();
        assert!(text.contains("timed out"), "unexpected message: {text}");
        assert!(
            text.contains(CALL_TIMEOUT_ENV),
            "should name the override env"
        );
        // The whole call must return promptly on deadline, not after the read.
        assert!(start.elapsed() < Duration::from_secs(5));
    }

    /// The sleeping reader above leaves no pending I/O for `CancelSynchronousIo`
    /// to find, so it never reaches the cancellation path. This blocks a real
    /// synchronous pipe read instead, and checks the server observes the close
    /// — which is what lets the daemon release an undelivered sandbox.
    #[cfg(windows)]
    #[test]
    fn a_timed_out_pipe_read_is_cancelled_so_the_server_sees_the_close() {
        use std::io::Read;
        use std::sync::mpsc::channel;
        use windows::core::PCWSTR;
        use windows::Win32::Foundation::{CloseHandle, HANDLE};
        use windows::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
        use windows::Win32::System::Pipes::{
            ConnectNamedPipe, CreateNamedPipeW, PIPE_TYPE_BYTE, PIPE_WAIT,
        };

        let name = format!(
            r"\\.\pipe\mxc-wslc-cancel-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        );
        let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();

        // SAFETY: a single-instance byte pipe; the handle is closed below.
        let server = unsafe {
            CreateNamedPipeW(
                PCWSTR(wide.as_ptr()),
                PIPE_ACCESS_DUPLEX,
                PIPE_TYPE_BYTE | PIPE_WAIT,
                1,
                4096,
                4096,
                0,
                None,
            )
        };
        assert!(!server.is_invalid(), "could not create the test pipe");

        let (connected_tx, connected_rx) = channel();
        let (write_tx, write_rx) = channel();
        let server_raw = server.0 as isize;
        let server_thread = std::thread::spawn(move || {
            let handle = HANDLE(server_raw as *mut _);
            // SAFETY: this thread owns the handle until it closes it below.
            unsafe {
                let _ = ConnectNamedPipe(handle, None);
                let _ = connected_tx.send(());

                // The client is blocked in a read that its deadline will cancel.
                // Once it does, this write has nobody to deliver to.
                std::thread::sleep(Duration::from_millis(600));
                let mut written = 0u32;
                let wrote = windows::Win32::Storage::FileSystem::WriteFile(
                    handle,
                    Some(b"frame"),
                    Some(&mut written),
                    None,
                );
                let _ = write_tx.send(wrote.is_ok());
                let _ = CloseHandle(handle);
            }
        });

        let mut client = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&name)
            .expect("open the test pipe");
        connected_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("server accepted the connection");

        // Nothing is ever written before the deadline, so this read blocks in
        // the kernel rather than returning.
        let start = Instant::now();
        let outcome: DaemonResult<usize> = read_frame_with_deadline(
            move || {
                let mut buf = [0u8; 8];
                let n = client.read(&mut buf)?;
                Ok(n)
            },
            Duration::from_millis(150),
        );

        let err = outcome.unwrap_err();
        assert!(matches!(err, DaemonError::Transport(_)));
        assert!(
            start.elapsed() < Duration::from_secs(5),
            "the deadline must return promptly, not wait out the read"
        );

        let server_wrote = write_rx
            .recv_timeout(Duration::from_secs(10))
            .expect("server reported its write");
        assert!(
            !server_wrote,
            "the client's end must be closed, so the server's reply cannot land"
        );

        server_thread.join().expect("server thread");
    }

    /// Reporting a timeout for a reply the daemon already delivered would
    /// strand the sandbox that reply names.
    #[cfg(windows)]
    #[test]
    fn a_read_that_beat_the_deadline_is_reported_rather_than_discarded() {
        let outcome: DaemonResult<u32> = read_frame_with_deadline(
            || {
                std::thread::sleep(Duration::from_millis(120));
                Ok(7u32)
            },
            Duration::from_millis(100),
        );

        assert_eq!(
            outcome.expect("a completed read must not be reported as a timeout"),
            7
        );
    }

    #[test]
    fn read_frame_with_deadline_propagates_reader_error() {
        let v: DaemonResult<u32> = read_frame_with_deadline(
            || Err(anyhow::anyhow!("framing error")),
            Duration::from_secs(5),
        );
        let err = v.unwrap_err();
        assert!(matches!(err, DaemonError::Transport(_)));
        assert!(err.to_string().contains("framing error"));
    }

    #[test]
    fn resolve_duration_falls_back_when_absent_or_invalid() {
        let default = Duration::from_secs(600);
        assert_eq!(resolve_duration(None, default), default);
        assert_eq!(resolve_duration(Some(""), default), default);
        assert_eq!(resolve_duration(Some("nope"), default), default);
        assert_eq!(resolve_duration(Some("0"), default), default);
    }

    #[test]
    fn resolve_duration_honours_positive_override() {
        assert_eq!(
            resolve_duration(Some("  3  "), Duration::from_secs(600)),
            Duration::from_secs(3)
        );
    }
}