Skip to main content

mxc_sdk/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! `mxc-sdk`: an importable library for running MXC containers in-process.
5//!
6//! See the [consumer glossary](https://github.com/microsoft/mxc/blob/main/docs/glossary.md)
7//! for terminology.
8//!
9//! Create a [`v1::ContainerRequest`] with its command and restrictions, then either:
10//!
11//! - hand it to [`v1::run`] to run the contained process **to completion** and get
12//!   its captured stdout/stderr and exit outcome in one call, or
13//! - hand it to [`v1::spawn`] for a live [`v1::MxcProcess`] handle you can
14//!   stream stdio through, feed stdin, and kill while it runs.
15//! - hand it to [`v1::spawn_with_pty`] for an [`v1::MxcPtyProcess`] with
16//!   merged terminal output and resize support.
17//!
18//! Either way the right containment backend is selected for the host and the
19//! ordinary `run` and `spawn` paths allocate no PTY.
20//!
21//! ```no_run
22//! use mxc_sdk::v1::{self, WaitResult};
23//!
24//! let request = v1::ContainerRequest::new("echo hi");
25//! let output = v1::run(request, Default::default())?;
26//! match output.outcome {
27//!     WaitResult::Exited(code) => println!("exit={code}"),
28//!     WaitResult::TimedOut => println!("timed out"),
29//! }
30//! println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
31//! # Ok::<(), Box<dyn std::error::Error>>(())
32//! ```
33//!
34//! ## Backend support
35//!
36//! The selected backend is driven by the request's [`v1::Containment`].
37//! Requests default to the host's native process backend.
38//!
39//! | Backend | Host | Selected by |
40//! |---------|------|-------------|
41//! | Bubblewrap | Linux | [`v1::Containment::Process`] or [`v1::Containment::Bubblewrap`] |
42//! | LXC | Linux | [`v1::Containment::Lxc`] |
43//! | Seatbelt | macOS | [`v1::Containment::Process`] or [`v1::Containment::Seatbelt`] |
44//! | ProcessContainer (PSEC) | Windows | [`v1::Containment::Process`] |
45//! | Explicit ProcessContainer configuration | Windows | [`v1::Containment::ProcessContainer`] |
46//! | WSLC (WSL Container) | Windows | [`v1::Containment::Wslc`] |
47//! | IsolationSession | Windows | [`v1::Containment::IsolationSession`] |
48//!
49//! LXC is reachable only by naming it: [`v1::Containment::Process`] resolves to
50//! Bubblewrap on Linux. It needs root. Ordinary streaming uses pipes, while
51//! [`v1::spawn_with_pty`] allocates a caller-controlled terminal.
52//!
53//! WSLC requires the crate's `wslc` build feature, and IsolationSession
54//! requires the `isolation_session` build feature. WSLC and IsolationSession
55//! are also available through the typed lifecycle API.
56//!
57//! The `wslc` feature stages `wslcsdk.dll` into the cargo profile directory,
58//! and WSLC loads it from beside the module holding this code, so an executable
59//! copied or installed out of that directory needs the DLL brought along. The
60//! crate README covers that and the separate `wxc-wslc-daemon.exe` that the
61//! container lifecycle needs.
62//!
63//! A concrete backend selected on another host returns an [`Error`] with
64//! [`ErrorCode::UnsupportedContainment`].
65//!
66//! # Diagnosing a failure
67//!
68//! [`Error`] carries an [`ErrorCode`] and a message. When an underlying platform
69//! API fails, it also identifies the call and its status:
70//!
71//! ```no_run
72//! # fn demo(error: mxc_sdk::v1::Error) {
73//! if let Some(operation) = &error.operation {
74//!     eprintln!("{operation} failed with {:?}", error.native_code);
75//! }
76//! if let Some(hint) = &error.remediation {
77//!     eprintln!("  try: {hint}");
78//! }
79//! # }
80//! ```
81//!
82//! [`Error::operation`] and [`Error::native_code`] are absent for a failure
83//! raised before any API call was reached (a malformed policy, say) and a
84//! native code only ever appears alongside the operation it belongs to.
85//! `Display` renders both, so logging the error alone does not lose them.
86//!
87//! ```no_run
88//! use mxc_sdk::v1;
89//!
90//! // Run a command inside a WSL container (Windows, --features wslc).
91//! let wslc = v1::configs::WslcConfig { image: "python:3.12".to_string(), ..Default::default() };
92//! let request = v1::ContainerRequest {
93//!     containment: v1::Containment::Wslc(wslc),
94//!     ..v1::ContainerRequest::new("python3 -c 'print(42)'")
95//! };
96//! let output = v1::run(request, Default::default())?;
97//! # Ok::<(), mxc_sdk::v1::Error>(())
98//! ```
99//!
100//! ## Choosing an entry point
101//!
102//! |             | container request | existing container | Stdio |
103//! |-------------|-------------------|--------------------|-------|
104//! | **capture** | [`v1::run`] | [`v1::container::run_in_container`] | captured stdout and stderr |
105//! | **handle**  | [`v1::spawn`] | [`v1::container::spawn_in_container`] | separate live pipes |
106//! | **PTY**     | [`v1::spawn_with_pty`] | [`v1::container::spawn_in_container_with_pty`] | merged output, resize |
107//! | **inherited** | [`v1::spawn_with_extended_options`] with [`v1::SpawnStdio::Inherit`] | — | the caller's own stdin, stdout, and stderr |
108//!
109//! [`v1::container::provision_container`], [`v1::container::start_container`],
110//! [`v1::container::stop_container`], and
111//! [`v1::container::deprovision_container`] drive the lifecycle with typed Rust
112//! requests. All SDK execution APIs take typed requests.
113//!
114//! ## Standard streams
115//!
116//! The V1 `run` and `spawn` APIs use ordinary pipes; PTY allocation is explicit
117//! through [`v1::spawn_with_pty`] and
118//! [`v1::container::spawn_in_container_with_pty`]. [`v1::run`] captures both output streams. With
119//! [`v1::spawn`] or [`v1::container::spawn_in_container`], callers
120//! can take the streams from [`MxcProcess`] or let `wait` drain and discard any
121//! stream they did not take.
122//!
123//! [`v1::spawn_with_pty`] allocates a caller-controlled PTY for create-and-run
124//! execution on supported backends, including IsolationSession, Bubblewrap, LXC,
125//! and Seatbelt direct execution.
126//! [`v1::container::spawn_in_container_with_pty`] does the same for a process in
127//! an existing IsolationSession container. Unsupported backends reject the
128//! request before creating a sandbox.
129//!
130//! [`v1::spawn_with_extended_options`] takes extensible options. With
131//! [`v1::SpawnStdio::Inherit`] it attaches the workload to the calling
132//! process's own stdin, stdout, and stderr, such as a terminal or pseudo-console
133//! the caller already set up; ProcessContainer, Bubblewrap, and Seatbelt support
134//! that mode.
135//!
136//! Policy and operational warnings are available through [`MxcProcess::warnings`]
137//! and [`ExecutionResult::warnings`]. These include security warnings, network rules
138//! that cannot carry traffic, and operational warnings such as unavailable
139//! telemetry routing.
140//!
141//! ## Internal module boundaries
142//!
143//! This crate root is the curated public facade. Backend dispatch, host
144//! probing, execution, and backend implementations are doc-hidden compatibility
145//! exports for workspace consumers rather than supported SDK entry points.
146
147#[path = "backends/mod.rs"]
148mod backend_modules;
149#[path = "core/mod.rs"]
150mod core_modules;
151
152#[doc(hidden)]
153pub use backend_modules::bubblewrap::common as bwrap_common;
154#[doc(hidden)]
155#[cfg(all(feature = "hyperlight", target_arch = "x86_64"))]
156pub use backend_modules::hyperlight::common as hyperlight_common;
157#[doc(hidden)]
158#[cfg(all(target_os = "windows", feature = "isolation_session"))]
159pub use backend_modules::isolation_session::bindings as isolation_session_bindings;
160#[doc(hidden)]
161#[cfg(all(target_os = "windows", feature = "isolation_session"))]
162pub use backend_modules::isolation_session::common as isolation_session_common;
163#[doc(hidden)]
164pub use backend_modules::lxc::common as lxc_common;
165#[doc(hidden)]
166#[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
167pub use backend_modules::nvx::runner as nvx_runner;
168#[doc(hidden)]
169#[cfg(target_os = "windows")]
170pub use backend_modules::process_container::common as process_container_common;
171#[doc(hidden)]
172pub use backend_modules::seatbelt::common as seatbelt_common;
173#[doc(hidden)]
174#[cfg(target_os = "windows")]
175pub use backend_modules::windows_sandbox::common as windows_sandbox_common;
176#[doc(hidden)]
177#[cfg(target_os = "windows")]
178pub use backend_modules::windows_sandbox::lifecycle as windows_sandbox_lifecycle;
179#[doc(hidden)]
180#[cfg(all(target_os = "windows", feature = "wslc"))]
181pub use backend_modules::wslc::common as wslc_common;
182#[doc(hidden)]
183#[cfg(all(target_os = "windows", feature = "wslc"))]
184pub use backend_modules::wslc::gateway_policy as wslc_gateway_policy;
185#[doc(hidden)]
186pub use core_modules::learning_mode_core;
187#[doc(hidden)]
188pub use core_modules::learning_mode_windows;
189#[doc(hidden)]
190pub use core_modules::mxc_common;
191#[doc(hidden)]
192pub use core_modules::mxc_contract;
193#[doc(hidden)]
194pub use core_modules::mxc_engine;
195#[doc(hidden)]
196pub use core_modules::mxc_pty;
197#[doc(hidden)]
198pub use core_modules::mxc_schema_support;
199#[doc(hidden)]
200pub use core_modules::mxc_telemetry;
201#[doc(hidden)]
202pub use core_modules::process_security_environment_spec;
203
204mod configs;
205mod dev;
206mod options;
207mod policy;
208mod sandbox;
209mod state_aware_sdk;
210
211mod telemetry;
212
213#[cfg(doctest)]
214mod api_tests;
215
216#[cfg(target_os = "windows")]
217use crate::mxc_engine::ProbeOutput;
218use crate::mxc_engine::{Error, ErrorCode};
219
220use sandbox::{ExecutionResult, MxcProcess};
221
222/// V1 contract-mapped request and typed lifecycle APIs.
223///
224/// These types and entry points target the latest published V1 contract
225/// owned by this SDK. Callers supply typed requests rather than JSON or a
226/// schema version.
227///
228pub mod v1 {
229    /// Caller-authored exact-JSON execution and lifecycle operations.
230    pub mod dev {
231        pub use crate::dev::*;
232    }
233
234    pub use crate::mxc_engine::{
235        available_backends, platform_support, AvailableBackend, BackendCapability,
236        BubblewrapNetworkSupport, Error, ErrorCode, PlatformSupport, ProxyEnforcement,
237    };
238    #[cfg(target_os = "windows")]
239    pub use crate::mxc_engine::{ProbeFacts, ProbeOutput, UiCapabilitySupport};
240    pub use crate::options::{
241        DeprovisionOptions, ProvisionOptions, RunInContainerOptions, RunOptions,
242        SpawnExtendedOptions, SpawnInContainerOptions, SpawnInContainerWithPtyOptions,
243        SpawnOptions, SpawnStdio, SpawnWithPtyOptions, StartOptions, StopOptions, TelemetryConfig,
244    };
245
246    /// V1 telemetry consent administration.
247    pub mod telemetry {
248        pub use crate::telemetry::*;
249    }
250
251    /// Backend-specific V1 configuration sections.
252    pub mod configs {
253        pub use crate::configs::{
254            CaptureDenials, CaptureDenialsMode, LxcConfig, ProcessContainerConfig,
255            ProcessContainerFilesystem, ProcessContainerNetwork, ProcessContainerSystemSettings,
256            ProcessContainerUi, ProcessContainerUiIsolation, SeatbeltConfig, WslcConfig,
257        };
258    }
259
260    /// V1 policy authoring types.
261    pub mod policy {
262        /// Host filesystem-policy discovery helpers and their options.
263        pub mod filesystem {
264            pub use crate::policy::{
265                available_tools_policy, temporary_files_policy, user_profile_policy,
266                FilesystemPolicyResult, ToolsPolicyContainerType, ToolsPolicyOptions,
267            };
268        }
269
270        pub use crate::policy::{
271            ClipboardPolicy, Containment, FilesystemPolicy, NetworkAction, NetworkEgressPolicy,
272            NetworkIngressPolicy, NetworkPeerPolicy, NetworkPolicy, NetworkPortPolicy,
273            NetworkProtocol, NetworkRulePolicy, NetworkRuntimeConfig, UiPolicy,
274        };
275    }
276
277    /// V1 typed lifecycle entry points.
278    pub mod container {
279        use super::{
280            ContainerId, Error, ExecutionRequest, ExecutionResult, MxcProcess,
281            RunInContainerOptions,
282        };
283
284        pub use crate::sandbox::{
285            deprovision as deprovision_container, provision as provision_container,
286            spawn_in_container, spawn_in_container_with_pty, start as start_container,
287            stop as stop_container, validate_deprovision, validate_process, validate_provision,
288            validate_start, validate_stop,
289        };
290
291        /// Run a workload in an existing container to completion and capture output.
292        pub fn run_in_container(
293            container_id: &ContainerId,
294            request: ExecutionRequest,
295            options: RunInContainerOptions,
296        ) -> Result<ExecutionResult, Error> {
297            let input = request
298                .into_sdk_input(container_id, options.telemetry)
299                .map_err(Error::from)?;
300            let process = crate::mxc_engine::exec_typed_state_aware_request(input, false, false)?;
301            crate::wait_with_output(MxcProcess::new(process))
302        }
303    }
304
305    pub use crate::policy::{
306        ClipboardPolicy, ContainerRequest, Containment, FilesystemPolicy, NetworkAction,
307        NetworkEgressPolicy, NetworkIngressPolicy, NetworkPeerPolicy, NetworkPolicy,
308        NetworkPortPolicy, NetworkProtocol, NetworkRulePolicy, NetworkRuntimeConfig, UiPolicy,
309    };
310    pub use crate::sandbox::{
311        CaptureDenialsError, CaptureDenialsResult, ExecutionMetadata, ExecutionResult, MxcProcess,
312        MxcPtyProcess, MxcPtySize, StreamCloser, WaitResult,
313    };
314    pub use crate::state_aware_sdk::{
315        ContainerId, ExecutionRequest, IsolationSessionProvisionMetadata, LifecycleResult,
316        ProcessNetworkPolicy, ProvisionMetadata, ProvisionRequest, ProvisionResult,
317        ValidationResult,
318    };
319
320    /// Probe an optional ProcessContainer request without creating a container.
321    ///
322    /// Other containments use backend availability discovery and their normal
323    /// launch-time validation because this result describes ProcessContainer tiers.
324    #[cfg(target_os = "windows")]
325    pub fn probe(request: Option<&ContainerRequest>) -> Result<crate::ProbeOutput, Error> {
326        let prepared = request.map(crate::policy::prepare_request).transpose()?;
327        crate::mxc_engine::probe_execution_request(prepared.as_ref().map(|request| &request.inner))
328    }
329
330    /// Spawn a [`ContainerRequest`] and return its live process.
331    ///
332    /// Returns a [`MxcProcess`] handle for live bidirectional stdio and termination;
333    /// no pty is allocated. Any stdout/stderr stream the caller does not
334    /// `take_*` is drained and discarded by [`wait`](MxcProcess::wait).
335    pub fn spawn(request: ContainerRequest, options: SpawnOptions) -> Result<MxcProcess, Error> {
336        let prepared = crate::policy::prepare_creation_request(&request, options.telemetry)?;
337        crate::mxc_engine::spawn_execution_request(&prepared.inner, true).map(MxcProcess::new)
338    }
339
340    /// Spawn a [`ContainerRequest`] attached to a caller-controlled PTY.
341    pub fn spawn_with_pty(
342        request: ContainerRequest,
343        options: SpawnWithPtyOptions,
344    ) -> Result<MxcPtyProcess, Error> {
345        options.size.validate()?;
346        let prepared = crate::policy::prepare_creation_request(&request, options.telemetry)?;
347        crate::mxc_engine::spawn_with_pty(&prepared.inner, options.size.into())
348            .and_then(MxcPtyProcess::new)
349    }
350
351    /// Spawn a [`ContainerRequest`] with stdio and other controls chosen in [`SpawnExtendedOptions`].
352    pub fn spawn_with_extended_options(
353        request: ContainerRequest,
354        options: SpawnExtendedOptions,
355    ) -> Result<MxcProcess, Error> {
356        let prepared = crate::policy::prepare_creation_request(&request, options.telemetry)?;
357        crate::mxc_engine::spawn_with_stdio(&prepared.inner, options.stdio.into())
358            .map(MxcProcess::new)
359    }
360
361    /// Run a [`ContainerRequest`] to completion and capture its output.
362    ///
363    /// Both streams are drained concurrently, so an output-heavy child cannot
364    /// deadlock. No pty is allocated.
365    ///
366    /// Use [`spawn`] instead when you need to stream stdio, feed stdin, or kill
367    /// the process while it runs.
368    ///
369    /// `Err` is returned when the backend can't be selected/spawned (an
370    /// [`Error`]), or when waiting on the child fails at the OS level.
371    pub fn run(request: ContainerRequest, options: RunOptions) -> Result<ExecutionResult, Error> {
372        let prepared = crate::policy::prepare_creation_request(&request, options.telemetry)?;
373        let process = crate::mxc_engine::spawn_execution_request(&prepared.inner, false)?;
374        crate::wait_with_output(MxcProcess::new(process))
375    }
376
377    #[cfg(all(test, target_os = "windows"))]
378    mod tests {
379        use super::*;
380
381        #[test]
382        fn public_creation_uses_required_telemetry_without_opt_in() {
383            use crate::mxc_common::telemetry::{self, events::test_sink};
384
385            let store = tempfile::tempdir().unwrap();
386            let env = telemetry::test_support::TelemetryTestEnv::new(store.path());
387            env.set_policy_value(0);
388            telemetry::consent::set_consent(false, "test").unwrap();
389            let _lock = test_sink::TEST_LOCK
390                .lock()
391                .unwrap_or_else(|error| error.into_inner());
392            test_sink::install();
393
394            for enabled in [None, Some(false)] {
395                let request = ContainerRequest {
396                    containment: Containment::Bubblewrap,
397                    ..ContainerRequest::new("true")
398                };
399                let error = run(
400                    request,
401                    RunOptions {
402                        telemetry: enabled.map(|enabled| TelemetryConfig {
403                            enabled: Some(enabled),
404                        }),
405                    },
406                )
407                .unwrap_err();
408                assert_eq!(error.code, ErrorCode::UnsupportedContainment);
409
410                let expected = usize::from(crate::mxc_telemetry::REQUIRED_COLLECTION_ELIGIBLE);
411                let starts = test_sink::take_starts();
412                let ends = test_sink::take_executions();
413                let errors = test_sink::take_errors();
414                assert_eq!(starts.len(), expected, "enabled={enabled:?}");
415                assert_eq!(ends.len(), expected, "enabled={enabled:?}");
416                assert_eq!(errors.len(), expected, "enabled={enabled:?}");
417                if let Some(start) = starts.first() {
418                    assert_eq!(start.session_id, ends[0].session_id);
419                    assert_eq!(start.session_id, errors[0].session_id);
420                    assert_eq!(start.backend, "bubblewrap");
421                    assert_eq!(ends[0].outcome, "failure");
422                }
423                assert!(test_sink::take_requirements().is_empty());
424                assert!(test_sink::take_verbose().is_empty());
425            }
426            test_sink::clear();
427        }
428
429        #[test]
430        fn json_and_public_creation_preserve_process_attribution_without_telemetry() {
431            use crate::mxc_common::telemetry::{self, events::test_sink};
432
433            let store = tempfile::tempdir().unwrap();
434            let env = telemetry::test_support::TelemetryTestEnv::new(store.path());
435            env.set_policy_value(0);
436            telemetry::consent::set_consent(false, "test").unwrap();
437            let _lock = test_sink::TEST_LOCK
438                .lock()
439                .unwrap_or_else(|error| error.into_inner());
440            test_sink::install();
441
442            for typed in [false, true] {
443                for enabled in [None, Some(false)] {
444                    let succeeded = if typed {
445                        run(
446                            ContainerRequest {
447                                containment: Containment::Process,
448                                ..ContainerRequest::new("cmd /c exit 0")
449                            },
450                            RunOptions {
451                                telemetry: enabled.map(|enabled| TelemetryConfig {
452                                    enabled: Some(enabled),
453                                }),
454                            },
455                        )
456                        .is_ok()
457                    } else {
458                        let mut request = serde_json::json!({
459                            "version": "1.0.0",
460                            "containment": "process",
461                            "process": { "commandLine": "cmd /c exit 0" }
462                        });
463                        if let Some(enabled) = enabled {
464                            request["telemetry"] = serde_json::json!({ "enabled": enabled });
465                        }
466                        crate::__ffi::run_json(&request.to_string(), false).is_ok()
467                    };
468                    let expected = usize::from(crate::mxc_telemetry::REQUIRED_COLLECTION_ELIGIBLE);
469                    let starts = test_sink::take_starts();
470                    let ends = test_sink::take_executions();
471                    assert_eq!(starts.len(), expected, "typed={typed}, enabled={enabled:?}");
472                    assert_eq!(ends.len(), expected, "typed={typed}, enabled={enabled:?}");
473                    if let Some(start) = starts.first() {
474                        assert_eq!(start.sandbox_kind, "process");
475                        assert_eq!(ends[0].sandbox_kind, "process");
476                        assert_eq!(start.backend, "processcontainer");
477                        assert_eq!(
478                            ends[0].outcome,
479                            if succeeded { "success" } else { "failure" }
480                        );
481                    }
482                    test_sink::take_errors();
483                    test_sink::take_requirements();
484                }
485            }
486            test_sink::clear();
487        }
488
489        #[test]
490        fn public_request_probe_uses_sdk_request_model() {
491            let request = ContainerRequest::new("cmd /c exit 0");
492            let output = probe(Some(&request)).expect("default request probes");
493            assert!(output.error.is_some() || output.tier.is_some());
494        }
495    }
496}
497
498mod lifecycle_thread_context {
499    /// Context carried onto the C ABI lifecycle worker.
500    #[doc(hidden)]
501    pub struct LifecycleThreadContext {
502        #[cfg(target_os = "windows")]
503        token: Option<crate::mxc_common::process_util::SendOwnedHandle>,
504        telemetry: crate::mxc_common::telemetry::session::SessionContext,
505        sink: Option<crate::mxc_common::logger::Logger>,
506    }
507
508    impl LifecycleThreadContext {
509        /// Capture the caller's security and diagnostic context before spawning.
510        pub fn capture() -> Result<Self, String> {
511            #[cfg(target_os = "windows")]
512            let token =
513                crate::mxc_common::process_util::duplicate_thread_token().map_err(|error| {
514                    format!("could not preserve the calling thread's impersonation: {error}")
515                })?;
516            let sink = crate::mxc_common::logger::Logger::inherit_thread_diagnostic_sink();
517            Ok(Self {
518                #[cfg(target_os = "windows")]
519                token,
520                telemetry: crate::mxc_common::telemetry::session::capture(),
521                sink: sink.has_diagnostic_sink().then_some(sink),
522            })
523        }
524
525        /// Run under the captured context, refusing to execute if impersonation fails.
526        pub fn run<T>(self, f: impl FnOnce() -> T) -> Result<T, String> {
527            #[cfg(target_os = "windows")]
528            if let Some(token) = &self.token {
529                // SAFETY: token is a live impersonation token and None selects this thread.
530                unsafe {
531                    windows::Win32::System::Threading::SetThreadToken(None, Some(token.get()))
532                }
533                .map_err(|error| {
534                    format!("could not impersonate on the lifecycle worker: {error}")
535                })?;
536            }
537            let _session = crate::mxc_common::telemetry::session::resume(self.telemetry);
538            let _sink = self
539                .sink
540                .as_ref()
541                .map(crate::mxc_common::logger::Logger::install_thread_diagnostic_sink);
542            Ok(f())
543        }
544    }
545}
546
547/// Internal adapters for the C ABI and native contract tests, not SDK authoring APIs.
548#[doc(hidden)]
549pub mod __ffi {
550    use super::*;
551    use crate::sandbox::WaitResult;
552    /// Decode bounded preparation input, rather than a terminal stored report.
553    pub fn decode_policy_failures_json(json: &str) -> Result<v1::dev::PolicyFailures, Error> {
554        v1::dev::PolicyFailures::parse(json)
555            .map_err(|message| Error::new(ErrorCode::MalformedRequest, message))
556    }
557
558    /// Whether this build contains the Windows x64 MicroVM runtime adapter.
559    #[doc(hidden)]
560    pub const MICROVM_RUNTIME_COMPILED: bool = cfg!(all(
561        target_os = "windows",
562        target_arch = "x86_64",
563        feature = "microvm"
564    ));
565
566    /// Register the runtime directory used by the MicroVM backend in this process.
567    pub fn register_runtime_directory(backend: &str, directory: &str) -> Result<(), Error> {
568        if backend != "microvm" {
569            return Err(Error::new(
570                ErrorCode::UnsupportedContainment,
571                "unknown runtime backend",
572            ));
573        }
574        #[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
575        {
576            crate::backend_modules::nvx::register_runtime_directory(directory).map_err(Error::from)
577        }
578        #[cfg(not(all(target_os = "windows", target_arch = "x86_64", feature = "microvm")))]
579        {
580            let _ = directory;
581            Err(Error::new(
582                ErrorCode::BackendUnavailable,
583                "MicroVM runtime is unavailable on this platform",
584            ))
585        }
586    }
587
588    /// Spawn a raw exact-version JSON container request as a live process.
589    ///
590    /// The JSON must declare an exact registered `version` and contain a
591    /// container request. Lifecycle requests are rejected; use lifecycle APIs.
592    /// `experimental` permits selecting an experimental backend (MicroVM,
593    /// Hyperlight, or Windows Sandbox), which is otherwise refused with
594    /// [`ErrorCode::BackendUnavailable`]. It is ignored for production backends and
595    /// is never read from the JSON.
596    pub fn spawn_container_json(
597        request_json: &str,
598        experimental: bool,
599    ) -> Result<MxcProcess, Error> {
600        crate::mxc_engine::spawn_one_shot_json(request_json, experimental).map(MxcProcess::new)
601    }
602
603    /// Spawn an exact-version JSON request attached to a caller-controlled PTY.
604    #[doc(hidden)]
605    pub fn spawn_with_pty_json(
606        request_json: &str,
607        experimental: bool,
608        size: v1::MxcPtySize,
609    ) -> Result<v1::MxcPtyProcess, Error> {
610        size.validate()?;
611        crate::mxc_engine::spawn_one_shot_pty_json(request_json, experimental, size.into())
612            .and_then(v1::MxcPtyProcess::new)
613    }
614
615    pub fn spawn_with_extended_options_json(
616        request_json: &str,
617        experimental: bool,
618        stdio: v1::SpawnStdio,
619    ) -> Result<MxcProcess, Error> {
620        crate::mxc_engine::spawn_one_shot_with_stdio_json(request_json, experimental, stdio.into())
621            .map(MxcProcess::new)
622    }
623
624    /// Run a raw exact-version JSON container request to completion and capture
625    /// its output. The JSON and `experimental` rules match [`spawn_container_json`].
626    pub fn run_json(request_json: &str, experimental: bool) -> Result<ExecutionResult, Error> {
627        match crate::mxc_engine::execute_one_shot_json(request_json, experimental)? {
628            #[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
629            crate::mxc_engine::OneShotExecution::Captured(result) => {
630                Ok(captured_execution_result(result))
631            }
632            crate::mxc_engine::OneShotExecution::Streaming(process) => {
633                wait_with_output(MxcProcess::new(process))
634            }
635        }
636    }
637
638    #[doc(hidden)]
639    pub use crate::lifecycle_thread_context::LifecycleThreadContext;
640
641    /// Run an [MXC lifecycle JSON request](https://github.com/microsoft/mxc/blob/main/docs/development/architecture/container-lifecycle.md#raw-json-entry-points) and return its JSON response envelope.
642    pub fn run_lifecycle_json(
643        request_json: &str,
644        dry_run: bool,
645        experimental: bool,
646    ) -> Result<String, Error> {
647        crate::mxc_engine::run_state_aware_json(request_json, dry_run, experimental)
648    }
649
650    /// Execute a lifecycle request (as a JSON string) as a **live streaming**
651    /// process, returning a [`MxcProcess`] handle for output streaming, waiting,
652    /// and termination, exactly like [`v1::spawn`]. Backends that expose process
653    /// input also make [`MxcProcess::take_stdin`] available.
654    ///
655    /// The request JSON must specify the `exec` lifecycle phase (with a
656    /// `sandboxId` identifying a started container). No pty is allocated.
657    ///
658    /// IsolationSession and WSLC serve this with the crate's corresponding
659    /// `isolation_session` or `wslc` feature. Windows Sandbox cannot hand back
660    /// pipes and refuses.
661    /// `experimental` opts in to experimental backends, as for
662    /// [`run_lifecycle_json`].
663    ///
664    /// [`MxcProcess::kill`] reaches only the foreground process here; a descendant the
665    /// workload backgrounded is reclaimed when the container is stopped and
666    /// deprovisioned.
667    pub fn execute_lifecycle_json(
668        request_json: &str,
669        experimental: bool,
670    ) -> Result<MxcProcess, Error> {
671        crate::mxc_engine::exec_state_aware_json(request_json, experimental, true)
672            .map(MxcProcess::new)
673    }
674
675    /// Execute for a run-to-completion helper: like [`execute_lifecycle_json`],
676    /// but a WSLC workload reads end-of-file on stdin.
677    pub fn execute_lifecycle_for_run_json(
678        request_json: &str,
679        experimental: bool,
680    ) -> Result<MxcProcess, Error> {
681        crate::mxc_engine::exec_state_aware_json(request_json, experimental, false)
682            .map(MxcProcess::new)
683    }
684
685    /// Execute with the backend's bounded output collection settings.
686    ///
687    /// Returns a cancellable process handle with pipes; the caller collects the
688    /// output and waits for completion.
689    pub fn execute_lifecycle_buffered_json(
690        request_json: &str,
691        experimental: bool,
692    ) -> Result<MxcProcess, Error> {
693        crate::mxc_engine::exec_state_aware_buffered_json(request_json, experimental)
694            .map(MxcProcess::new)
695    }
696
697    pub use execute_lifecycle_buffered_json as execute_lifecycle_capture_json;
698
699    /// Spawn a lifecycle execution request with a caller-controlled PTY.
700    #[doc(hidden)]
701    pub fn spawn_in_container_with_pty_json(
702        request_json: &str,
703        size: v1::MxcPtySize,
704        experimental: bool,
705    ) -> Result<v1::MxcPtyProcess, Error> {
706        size.validate()?;
707        crate::mxc_engine::exec_state_aware_pty_json(request_json, experimental, size.into())
708            .and_then(v1::MxcPtyProcess::new)
709    }
710
711    /// Execute a lifecycle request attached to this process's stdio.
712    #[expect(
713        dead_code,
714        reason = "Attached exec is reserved but not exposed by the SDK yet"
715    )]
716    fn exec_attached(request_json: &str, experimental: bool) -> Result<WaitResult, Error> {
717        exec_attached_json(request_json, experimental)
718    }
719
720    /// Run an exact-JSON lifecycle execution request attached to this process's stdio.
721    fn exec_attached_json(request_json: &str, experimental: bool) -> Result<WaitResult, Error> {
722        use crate::mxc_common::state_aware_backend::ExecOutcome;
723        crate::mxc_engine::exec_state_aware_attached(request_json, experimental).map(|outcome| {
724            match outcome {
725                ExecOutcome::Exited(code) => WaitResult::Exited(code),
726                ExecOutcome::TimedOut => WaitResult::TimedOut,
727            }
728        })
729    }
730}
731
732#[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
733fn captured_execution_result(
734    result: crate::mxc_engine::CapturedExecutionResult,
735) -> ExecutionResult {
736    ExecutionResult {
737        outcome: match result.outcome {
738            crate::mxc_engine::CapturedOutcome::Exited(code) => sandbox::WaitResult::Exited(code),
739            crate::mxc_engine::CapturedOutcome::TimedOut => sandbox::WaitResult::TimedOut,
740        },
741        warnings: result.warnings,
742        stdout: result.stdout,
743        stderr: result.stderr,
744        output_metadata: None,
745    }
746}
747
748fn wait_with_output(sandbox: MxcProcess) -> Result<ExecutionResult, Error> {
749    sandbox.wait_with_output_detailed()
750}