The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(mounts): expose directory mounts across CLI and SDKs (#3143)
Vitus466c7729d55f
diff --git a/docs/reference/cli/README.md b/docs/reference/cli/README.mdindex aca1eec19..a6748a395 100644--- a/docs/reference/cli/README.md+++ b/docs/reference/cli/README.md@@ -45,6 +45,7 @@ For a quick start, see [`src/cli/README.md`](../../../src/cli/README.md).- [`boxlite ssh`](#boxlite-ssh)- [`boxlite agent`](#boxlite-agent)- [`boxlite serve`](#boxlite-serve)+ - [`boxlite mount`](#boxlite-mount)- [`boxlite volume`](#boxlite-volume)- [`boxlite domain`](#boxlite-domain)- [`boxlite completion`](#boxlite-completion)@@ -180,7 +181,7 @@ Commands without shared options omit the global section.| `OIDC_CLIENT_ID` | `auth login` | OIDC client-id fallback after an explicit flag and server discovery || `OIDC_AUDIENCE` | `auth login` | OIDC audience fallback after an explicit flag and server discovery || `BOXLITE_LOG_FILE` | logging | Explicit JSON log-file path for any command; a bare filename is relative to the current directory. `serve` otherwise logs to `<BOXLITE_HOME>/logs/serve.log`. |-| `BOXLITE_EXPERIMENTAL` | `run`, `create` | Comma-separated RC features: `custom-kernel`, `nested-virtualization`, `native-vmm` |+| `BOXLITE_EXPERIMENTAL` | `run`, `create`, `mount`, `serve` | Comma-separated RC features: `custom-kernel`, `nested-virtualization`, `native-vmm`; mounts require `native-vmm` || `BOXLITE_RECONNECT_GRACE` | `serve` | Reconnect grace before SIGHUP; default `5m` || `BOXLITE_SHUTDOWN_GRACE` | `serve` | Grace between shutdown escalation stages; default `30s` || `BOXLITE_MAX_SESSION_LIFETIME` | `serve` | Session hard cap; default `24h` |@@ -1263,6 +1264,39 @@ BOXLITE_SERVE_API_KEY="$KEY" boxlite serve --host 0.0.0.0---+### `boxlite mount`++**Synopsis:** `boxlite mount <add|rm|ls|inspect> BOX [OPTIONS]`++Manage directory mounts on a Linux x86_64 native Box with+`BOXLITE_EXPERIMENTAL=native-vmm`. The command is hidden from help and+completion until opted in.++```bash+export BOXLITE_EXPERIMENTAL=native-vmm,custom-kernel+boxlite mount add mybox --source /srv/project --box-path /work --read-only+boxlite mount ls mybox --format json+boxlite mount inspect mybox --box-path /work --format json+boxlite mount rm mybox --box-path /work+```++`add` requires `--source HOST_DIR` and `--box-path CONTAINER_PATH`; its default+mode is writable. `rm` and `inspect` require `--box-path`. `ls` and `inspect`+accept `--format table|json|yaml` (default `table`). JSON inspection of a missing+target returns `null`; removal of a missing target fails with `NotFound`.++All four operations leave a stopped Box stopped. An add saves `configured` for+its next start; a running add returns `mounted` after guest confirmation.+Other current-run progress is `preparing` or `detaching`. Removal drops the+declaration and, on a running Box, lazily detaches the directory while keeping+open references usable.++Local and `--url` connections use the same commands. For REST, `--source`+names a directory on the server host, whose runtime must enable `native-vmm`.+See the [CLI example](../../../src/cli/README.md#runtime-directory-mounts-release-candidate).++---+### `boxlite volume`**Synopsis:** `boxlite volume <create|ls|get|rm>`diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex 0adb0a351..3b56b4a08 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -570,15 +570,22 @@ conflict rather than silently returning no output.require the `native-vmm` experimental feature and the local Linux x86_64 nativeengine. Changes require a container configured without `CAP_SYS_ADMIN`.+REST runtimes expose the same four methods against a local `boxlite serve`+with `runtime_mounts_enabled`. `source` names a directory on the server host.+See the [local REST contract](../../../src/cli/src/commands/serve/README.md#runtime-directory-mounts).+JSON mount details use lowercase state names, while SQLite keeps its existing+state representation.+| Method | Signature | Description ||--------|-----------|-------------|-| `add` | `async fn add(&self, request: MountRequest) -> BoxliteResult<MountInfo>` | Save a directory and deliver it immediately if the container is running |+| `add` | `async fn add(&self, options: MountOptions) -> BoxliteResult<MountInfo>` | Save a directory and deliver it immediately if the container is running || `remove` | `async fn remove(&self, target: impl AsRef<Path>) -> BoxliteResult<()>` | Remove a declaration and lazily detach its live mount || `list` | `async fn list(&self) -> BoxliteResult<Vec<MountInfo>>` | Read saved directories and current delivery progress || `get` | `async fn get(&self, target: impl AsRef<Path>) -> BoxliteResult<Option<MountInfo>>` | Read one entry by normalized container path, or `None` if absent |-A `MountRequest` takes an absolute host directory, a UTF-8 target below `/`,-and `read_only`. The target may omit intermediate directories and must exclude+`MountOptions` configures an absolute host directory, a UTF-8 target below `/`,+and `read_only`, using the same `Options` naming as snapshot, clone, and export.+The target may omit intermediate directories and must exclude`..`. A directory added at runtime, and a saved one at its next start, landson a target the guest creates when missing; a target with entries, or onereached through a symbolic link, is refused. Adding at an occupied target@@ -640,7 +647,7 @@ configured with `auto_delete: Some(0)`, save a read-only workspace and start it.```rustlet mounts = litebox.mount();let info = mounts- .add(MountRequest {+ .add(MountOptions {source: "/srv/project".into(),target: "/workspace".into(),read_only: true,diff --git a/sdks/c/Cargo.toml b/sdks/c/Cargo.tomlindex d0c25c9ec..1a1a7b900 100644--- a/sdks/c/Cargo.toml+++ b/sdks/c/Cargo.toml@@ -25,6 +25,9 @@ serde_json = "1.0"tokio = { version = "1.37", features = ["io-util", "net", "rt", "rt-multi-thread"] }tracing = "0.1"+[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]+boxlite = { workspace = true, features = ["native"] }+[dev-dependencies]boxlite = { workspace = true, features = ["rest", "test-support"] }boxlite-test-utils = { path = "../../src/test-utils" }diff --git a/sdks/c/README.md b/sdks/c/README.mdindex 1366a3c84..02e1a90e9 100644--- a/sdks/c/README.md+++ b/sdks/c/README.md@@ -534,6 +534,22 @@ BoxliteErrorCode boxlite_runtime_metrics(void boxlite_runtime_free(CBoxliteRuntime* runtime);```+#### Runtime directory mounts (release candidate)++Call `boxlite_box_mount_add`, `boxlite_box_mount_remove`, `boxlite_box_mount_list`,+or `boxlite_box_mount_get` on a native Box and drain the runtime for the `CBoxMountCb`+result: JSON for add, list and get (JSON `null` for an absent target or a completed+removal), or a typed error. Both pointers are borrowed until the callback returns.+A NULL callback, NULL input string, or invalid UTF-8 returns `InvalidArgument` without+a callback; a retained Box handle answers `Stopped` synchronously after runtime+shutdown or closure.++For a local Box with a custom kernel, pass `"native-vmm,custom-kernel"` to+`boxlite_runtime_new_experimental`. Mount states, lazy removal and REST sources follow the+[CLI contract](../../docs/reference/cli/README.md#boxlite-mount); none of these calls+starts a Box. Ending a caller's wait does not cancel an admitted operation, and callback+user data must stay valid until completion is delivered or the runtime is freed.+#### Box LifecycleNested virtualization is a creation option:diff --git a/sdks/c/include/boxlite.h b/sdks/c/include/boxlite.hindex cab0348e1..e4bdc5e37 100644--- a/sdks/c/include/boxlite.h+++ b/sdks/c/include/boxlite.h@@ -717,6 +717,10 @@ typedef struct CRuntimeMetrics {// Runtime metrics completion.typedef void (*CRuntimeMetricsCb)(struct CRuntimeMetrics*, CBoxliteError*, void*);+// Mount completion on the drain thread. Both pointers are borrowed for the+// duration of the callback. Copy the JSON to keep it beyond that call.+typedef void (*CBoxMountCb)(const char*, const CBoxliteError*, void*);+typedef struct BoxNetworkHandle CBoxNetworkHandle;typedef struct TunnelForwarderHandle CTunnelForwarderHandle;@@ -1698,6 +1702,42 @@ enum BoxliteErrorCode boxlite_runtime_metrics(CBoxliteRuntime *runtime,void *user_data,CBoxliteError *out_error);+// Deliver a host directory to a Box. The callback receives the resulting+// mount as JSON with source, target, read_only and state fields. A running+// Box reports `mounted`; a stopped one saves the mount and reports+// `configured` for its next start. The Box is never started.+// Input strings are required and copied before returning.+enum BoxliteErrorCode boxlite_box_mount_add(CBoxHandle *handle,+ const char *source,+ const char *target,+ bool read_only,+ CBoxMountCb cb,+ void *user_data,+ CBoxliteError *out_error);++// Lazily detach the mount at target, or discard one a stopped Box saved as+// `configured`. On success the callback receives JSON null. The Box is never+// started.+enum BoxliteErrorCode boxlite_box_mount_remove(CBoxHandle *handle,+ const char *target,+ CBoxMountCb cb,+ void *user_data,+ CBoxliteError *out_error);++// Read the mounts of the Box as a JSON array, including any saved as+// `configured` for its next start. The Box is never started.+enum BoxliteErrorCode boxlite_box_mount_list(CBoxHandle *handle,+ CBoxMountCb cb,+ void *user_data,+ CBoxliteError *out_error);++// Read the mount at target as JSON. An absent target returns JSON null.+enum BoxliteErrorCode boxlite_box_mount_get(CBoxHandle *handle,+ const char *target,+ CBoxMountCb cb,+ void *user_data,+ CBoxliteError *out_error);+// Replace inbound policy from {"mode":"enabled","allow_net":[]}.// Blocks until applied or rejected. Strings are borrowed for the call.enum BoxliteErrorCode boxlite_network_update_inbound(CBoxNetworkHandle *network,diff --git a/sdks/c/src/archive.rs b/sdks/c/src/archive.rsindex 697797a8e..e1a1c0aa0 100644--- a/sdks/c/src/archive.rs+++ b/sdks/c/src/archive.rs@@ -213,6 +213,7 @@ unsafe fn import_box(let runtime = runtime_ref.runtime.clone();let tokio_rt = runtime_ref.tokio_rt.clone();let queue = runtime_ref.queue.clone();+ let liveness = Arc::clone(&runtime_ref.liveness);let box_tokio_rt = tokio_rt.clone();let task_tokio_rt = tokio_rt.clone();let box_queue = queue.clone();@@ -231,6 +232,7 @@ unsafe fn import_box(box_id,tokio_rt: box_tokio_rt,queue: box_queue,+ liveness,}))});push_event(@@ -273,7 +275,7 @@ unsafe fn parse_optional_name(value: *const c_char) -> Result<Option<String>, Bo}}-unsafe fn parse_required_string(+pub(crate) unsafe fn parse_required_string(value: *const c_char,parameter: &str,) -> Result<String, BoxliteError> {diff --git a/sdks/c/src/box_handle.rs b/sdks/c/src/box_handle.rsindex 21a88482c..99a50fa51 100644--- a/sdks/c/src/box_handle.rs+++ b/sdks/c/src/box_handle.rs@@ -22,7 +22,7 @@ use crate::event_queue::{CBoxStopBoxCb, EventQueue, RuntimeEvent, push_event,};use crate::options::OptionsHandle;-use crate::runtime::RuntimeHandle;+use crate::runtime::{RuntimeHandle, RuntimeLiveness};use crate::util::c_str_to_string;use crate::{CBoxHandle, CBoxliteError, CBoxliteOptions, CBoxliteRuntime};@@ -36,6 +36,7 @@ pub struct BoxHandle {pub box_id: BoxID,pub tokio_rt: Arc<TokioRuntime>,pub queue: Arc<EventQueue>,+ pub liveness: Arc<RuntimeLiveness>,}#[unsafe(no_mangle)]@@ -165,6 +166,7 @@ unsafe fn create_box(let runtime_clone = runtime_ref.runtime.clone();let tokio_rt = runtime_ref.tokio_rt.clone();let queue = runtime_ref.queue.clone();+ let liveness = Arc::clone(&runtime_ref.liveness);let user_data_addr = user_data as usize;let task_tokio_rt = tokio_rt.clone();let task_queue = queue.clone();@@ -180,6 +182,7 @@ unsafe fn create_box(box_id,tokio_rt: task_tokio_rt,queue: task_queue.clone(),+ liveness,});crate::event_queue::OwnedFfiPtr::new(boxed)});@@ -226,6 +229,7 @@ unsafe fn get_or_create_box(let runtime_clone = runtime_ref.runtime.clone();let tokio_rt = runtime_ref.tokio_rt.clone();let queue = runtime_ref.queue.clone();+ let liveness = Arc::clone(&runtime_ref.liveness);let user_data_addr = user_data as usize;let task_tokio_rt = tokio_rt.clone();let task_queue = queue.clone();@@ -241,6 +245,7 @@ unsafe fn get_or_create_box(box_id,tokio_rt: task_tokio_rt,queue: task_queue.clone(),+ liveness,});(crate::event_queue::OwnedFfiPtr::new(boxed), created)});@@ -320,6 +325,7 @@ unsafe fn attach_box(let runtime_clone = runtime_ref.runtime.clone();let tokio_rt = runtime_ref.tokio_rt.clone();let queue = runtime_ref.queue.clone();+ let liveness = Arc::clone(&runtime_ref.liveness);let user_data_addr = user_data as usize;let task_tokio_rt = tokio_rt.clone();let task_queue = queue.clone();@@ -333,6 +339,7 @@ unsafe fn attach_box(box_id,tokio_rt: task_tokio_rt,queue: task_queue.clone(),+ liveness,});Ok(crate::event_queue::OwnedFfiPtr::new(boxed))}diff --git a/sdks/c/src/event_queue.rs b/sdks/c/src/event_queue.rsindex 0e3aa4a6b..8447a93ae 100644--- a/sdks/c/src/event_queue.rs+++ b/sdks/c/src/event_queue.rs@@ -405,6 +405,11 @@ impl<T> Drop for OwnedFfiPtr<T> {pub enum RuntimeEvent {AgentCompletion(Box<dyn FnOnce() + Send>),AgentSubscription(Box<dyn FnOnce() + Send>),+ Mounts {+ cb: crate::mounts::MountsFn,+ user_data: usize,+ result: Result<CString, BoxliteError>,+ },AgentCreate {callback: unsafe extern "C" fn(*mut crate::agents::CAgent,diff --git a/sdks/c/src/lib.rs b/sdks/c/src/lib.rsindex 53564a6e4..c3153b57c 100644--- a/sdks/c/src/lib.rs+++ b/sdks/c/src/lib.rs@@ -20,6 +20,7 @@ mod exec;mod images;mod info;mod metrics;+mod mounts;mod network;mod options;mod registries;@@ -98,6 +99,7 @@ pub use exec::*;pub use images::*;pub use info::*;pub use metrics::*;+pub use mounts::*;pub use network::*;pub use options::*;pub use registries::*;diff --git a/sdks/c/src/mounts.rs b/sdks/c/src/mounts.rsnew file mode 100644index 000000000..ea8f932f3--- /dev/null+++ b/sdks/c/src/mounts.rs@@ -0,0 +1,161 @@+use std::ffi::{CString, c_char, c_void};+use std::ptr;+use std::sync::Arc;++use boxlite::{BoxliteError, MountOptions};+use serde::Serialize;++use crate::archive::{TokioRuntimeDropGuard, parse_required_string};+use crate::error::{+ BoxliteErrorCode, error_to_c_error, error_to_code, null_pointer_error, write_error,+};+use crate::event_queue::{RuntimeEvent, push_event};+use crate::{CBoxHandle, CBoxliteError};++pub(crate) type MountsFn = extern "C" fn(*const c_char, *const CBoxliteError, *mut c_void);++/// Mount completion on the drain thread. Both pointers are borrowed for the+/// duration of the callback. Copy the JSON to keep it beyond that call.+pub type CBoxMountCb = Option<extern "C" fn(*const c_char, *const CBoxliteError, *mut c_void)>;++enum MountOp {+ Add(MountOptions),+ Remove(String),+ List,+ Get(String),+}++fn json(value: impl Serialize) -> Result<CString, BoxliteError> {+ let bytes =+ serde_json::to_vec(&value).map_err(|err| BoxliteError::Internal(err.to_string()))?;+ CString::new(bytes).map_err(|err| BoxliteError::Internal(err.to_string()))+}++pub(crate) unsafe fn dispatch_mounts(+ result: Result<CString, BoxliteError>,+ cb: MountsFn,+ user_data: usize,+) {+ match result {+ Ok(json) => cb(json.as_ptr(), ptr::null(), user_data as *mut c_void),+ Err(error) => {+ let mut error = error_to_c_error(error);+ cb(ptr::null(), &error, user_data as *mut c_void);+ unsafe { crate::boxlite_error_free(&mut error) };+ }+ }+}++unsafe fn schedule(+ handle: *mut CBoxHandle,+ op: Result<MountOp, BoxliteError>,+ cb: CBoxMountCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ let refuse = |error: BoxliteError| {+ let code = error_to_code(&error);+ unsafe { write_error(out_error, error) };+ code+ };+ let cb = crate::unwrap_cb_or_return!(cb, out_error);+ let Some(handle) = (unsafe { handle.as_ref() }) else {+ return refuse(null_pointer_error("handle"));+ };+ let op = match op {+ Ok(op) => op,+ Err(error) => return refuse(error),+ };+ if let Err(error) = crate::util::ensure_runtime_live(&handle.liveness, "access mounts") {+ return refuse(error);+ }+ let mount = handle.handle.mount();+ let queue = Arc::clone(&handle.queue);+ let runtime = Arc::clone(&handle.tokio_rt);+ let user_data = user_data as usize;+ handle.tokio_rt.spawn(async move {+ // The operation can outlive the caller's box and runtime handles.+ let _runtime = TokioRuntimeDropGuard::new(runtime);+ let result = match op {+ MountOp::Add(request) => mount.add(request).await.and_then(json),+ MountOp::Remove(target) => mount.remove(target).await.and_then(json),+ MountOp::List => mount.list().await.and_then(json),+ MountOp::Get(target) => mount.get(target).await.and_then(json),+ };+ push_event(+ &queue,+ RuntimeEvent::Mounts {+ cb,+ user_data,+ result,+ },+ )+ .await;+ });+ BoxliteErrorCode::Ok+}++/// Deliver a host directory to a Box. The callback receives the resulting+/// mount as JSON with source, target, read_only and state fields. A running+/// Box reports `mounted`; a stopped one saves the mount and reports+/// `configured` for its next start. The Box is never started.+/// Input strings are required and copied before returning.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_box_mount_add(+ handle: *mut CBoxHandle,+ source: *const c_char,+ target: *const c_char,+ read_only: bool,+ cb: CBoxMountCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ let op = unsafe { parse_required_string(source, "source") }.and_then(|source| {+ Ok(MountOp::Add(MountOptions {+ source: source.into(),+ target: unsafe { parse_required_string(target, "target") }?.into(),+ read_only,+ }))+ });+ unsafe { schedule(handle, op, cb, user_data, out_error) }+}++/// Lazily detach the mount at target, or discard one a stopped Box saved as+/// `configured`. On success the callback receives JSON null. The Box is never+/// started.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_box_mount_remove(+ handle: *mut CBoxHandle,+ target: *const c_char,+ cb: CBoxMountCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ let op = unsafe { parse_required_string(target, "target") }.map(MountOp::Remove);+ unsafe { schedule(handle, op, cb, user_data, out_error) }+}++/// Read the mounts of the Box as a JSON array, including any saved as+/// `configured` for its next start. The Box is never started.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_box_mount_list(+ handle: *mut CBoxHandle,+ cb: CBoxMountCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ unsafe { schedule(handle, Ok(MountOp::List), cb, user_data, out_error) }+}++/// Read the mount at target as JSON. An absent target returns JSON null.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_box_mount_get(+ handle: *mut CBoxHandle,+ target: *const c_char,+ cb: CBoxMountCb,+ user_data: *mut c_void,+ out_error: *mut CBoxliteError,+) -> BoxliteErrorCode {+ let op = unsafe { parse_required_string(target, "target") }.map(MountOp::Get);+ unsafe { schedule(handle, op, cb, user_data, out_error) }+}diff --git a/sdks/c/src/runtime.rs b/sdks/c/src/runtime.rsindex 737b6d865..9c1ff525e 100644--- a/sdks/c/src/runtime.rs+++ b/sdks/c/src/runtime.rs@@ -601,6 +601,13 @@ unsafe fn dispatch_event(event: RuntimeEvent) {RuntimeEvent::AgentCompletion(dispatch) | RuntimeEvent::AgentSubscription(dispatch) => {dispatch()}+ RuntimeEvent::Mounts {+ cb,+ user_data,+ result,+ } => {+ crate::mounts::dispatch_mounts(result, cb, user_data);+ }RuntimeEvent::AgentCreate {callback,user_data,diff --git a/sdks/c/tests/test_null_callback.c b/sdks/c/tests/test_null_callback.cindex b7cd256a0..1e4df0859 100644--- a/sdks/c/tests/test_null_callback.c+++ b/sdks/c/tests/test_null_callback.c@@ -95,6 +95,19 @@ static void test_runtime_shutdown_null_cb(CBoxliteRuntime *rt) {assert_null_cb_rejected(code, &err, "boxlite_runtime_shutdown(cb=NULL)");}+static void test_mounts_null_cb(void) {+ CBoxliteError err = (CBoxliteError){0};+ BoxliteErrorCode code =+ boxlite_box_mount_add(NULL, "/host", "/target", false, NULL, NULL, &err);+ assert_null_cb_rejected(code, &err, "boxlite_box_mount_add(cb=NULL)");+ code = boxlite_box_mount_remove(NULL, "/target", NULL, NULL, &err);+ assert_null_cb_rejected(code, &err, "boxlite_box_mount_remove(cb=NULL)");+ code = boxlite_box_mount_list(NULL, NULL, NULL, &err);+ assert_null_cb_rejected(code, &err, "boxlite_box_mount_list(cb=NULL)");+ code = boxlite_box_mount_get(NULL, "/target", NULL, NULL, &err);+ assert_null_cb_rejected(code, &err, "boxlite_box_mount_get(cb=NULL)");+}+int main(void) {printf("\n═══════════════════════════════════════\n");printf(" BoxLite C SDK - NULL callback rejection\n");@@ -106,11 +119,12 @@ int main(void) {test_runtime_metrics_null_cb(rt);test_list_info_null_cb(rt);test_runtime_shutdown_null_cb(rt);+ test_mounts_null_cb();boxlite_runtime_free(rt);printf("\n═══════════════════════════════════════\n");- printf(" ✅ ALL NULL-CB TESTS PASSED (4 tests)\n");+ printf(" ✅ ALL NULL-CB TESTS PASSED\n");printf("═══════════════════════════════════════\n");return 0;}diff --git a/sdks/go/README.md b/sdks/go/README.mdindex 5203e61e3..34fe61109 100644--- a/sdks/go/README.md+++ b/sdks/go/README.md@@ -375,6 +375,32 @@ A macOS REST client can request fractional CPUs from a supporting Linux server.Rebuild against the matching C header/library because CPU fields and parameters now use `double`.See [fractional CPUs](../../docs/guides/resource-limits.md#fractional-cpus-linux) for validation, cgroup delegation, and REST support.+## Runtime directory mounts (release candidate)++`box.Mount()` exposes `Add`, `Remove`, `List`, and `Get` for a Linux x86_64+native Box. For a local Box with a custom kernel, use+`WithExperimentalFeatures("native-vmm", "custom-kernel")`. For REST, `Source` names+a directory on the server host.++```go+mount := box.Mount()+info, err := mount.Add(ctx, boxlite.MountOptions{+ Source: "/srv/projects/demo", Target: "/workspace", ReadOnly: true,+})+```++`Add` returns the mount for that operation: `MountMounted` on a running Box, or+`MountConfigured` when a stopped Box saves it for its next start. `Get` returns `nil`+for an absent target, and `Remove` of one fails with an error recognized by `IsNotFound`.+These calls never start a Box; see the [CLI contract](../../docs/reference/cli/README.md#boxlite-mount)+for the states and lazy removal.++Cancelling the Go context only ends the wait, so inspect with `Get` or `List` before+retrying. After `Runtime.Close`, mount calls return `ErrRuntimeClosed` before submission;+after `Runtime.Shutdown`, they return an error recognized by `IsStopped`.++Use the C SDK library and header shipped with the matching Go SDK version.+## Service TunnelsThe same route workflow works with local and remote runtimes:diff --git a/sdks/go/box_close_race_test.go b/sdks/go/box_close_race_test.goindex f0182116f..76d3bb663 100644--- a/sdks/go/box_close_race_test.go+++ b/sdks/go/box_close_race_test.go@@ -96,6 +96,8 @@ func TestBoxMethodsAfterCloseReturnInvalidState(t *testing.T) {}ctx := context.Background()+ mount := box.Mount()+ options := MountOptions{Source: "/host/source", Target: "/workspace"}checks := map[string]func() error{"Metrics": func() error { _, err := box.Metrics(ctx); return err },"Info": func() error { _, err := box.Info(ctx); return err },@@ -110,6 +112,10 @@ func TestBoxMethodsAfterCloseReturnInvalidState(t *testing.T) {"CopyOut": func() error { return box.CopyOut(ctx, "/src", "/tmp/dst") },"CopyOutStream": func() error { return box.CopyOutStream(ctx, "/src", io.Discard) },"CopyInStream": func() error { return box.CopyInStream(ctx, "/dst", strings.NewReader("x")) },+ "MountAdd": func() error { _, err := mount.Add(ctx, options); return err },+ "MountRemove": func() error { return mount.Remove(ctx, options.Target) },+ "MountList": func() error { _, err := mount.List(ctx); return err },+ "MountGet": func() error { _, err := mount.Get(ctx, options.Target); return err },}for name, call := range checks {if err := call(); !IsInvalidState(err) {diff --git a/sdks/go/bridge.c b/sdks/go/bridge.cindex 04d06f4c3..2f004a1ae 100644--- a/sdks/go/bridge.c+++ b/sdks/go/bridge.c@@ -41,6 +41,7 @@ extern void goBoxliteOnRegistryRemove(CBoxliteError *err, void *ud);extern void goBoxliteOnInfo(CBoxInfo *info, CBoxliteError *err, void *ud);extern void goBoxliteOnInfoList(CBoxInfoList *list, CBoxliteError *err, void *ud);extern void goBoxliteOnExecutionInfoList(CExecutionInfoList *list, CBoxliteError *err, void *ud);+extern void goBoxliteOnMount(char *json, CBoxliteError *err, void *ud);extern void goBoxliteOnBoxMetrics(CBoxMetrics *m, CBoxliteError *err, void *ud);extern void goBoxliteOnRuntimeMetrics(CRuntimeMetrics *m, CBoxliteError *err, void *ud);@@ -97,6 +98,10 @@ CBoxRegistryRemoveCb cbRegistryRemove(void) { return (CBoxRegistryRemoveCb)goBoxCBoxInfoCb cbInfo(void) { return (CBoxInfoCb)goBoxliteOnInfo; }CBoxInfoListCb cbInfoList(void) { return (CBoxInfoListCb)goBoxliteOnInfoList; }CExecutionInfoListCb cbExecutionInfoList(void) { return (CExecutionInfoListCb)goBoxliteOnExecutionInfoList; }+static void onMount(const char *json, const CBoxliteError *err, void *ud) {+ goBoxliteOnMount((char *)json, (CBoxliteError *)err, ud);+}+CBoxMountCb cbMount(void) { return onMount; }CBoxMetricsCb cbBoxMetrics(void) { return (CBoxMetricsCb)goBoxliteOnBoxMetrics; }CRuntimeMetricsCb cbRuntimeMetrics(void) { return (CRuntimeMetricsCb)goBoxliteOnRuntimeMetrics; }diff --git a/sdks/go/bridge.h b/sdks/go/bridge.hindex 7fbd83b8c..874d29d41 100644--- a/sdks/go/bridge.h+++ b/sdks/go/bridge.h@@ -41,6 +41,7 @@ extern CBoxRegistryRemoveCb cbRegistryRemove(void);extern CBoxInfoCb cbInfo(void);extern CBoxInfoListCb cbInfoList(void);extern CExecutionInfoListCb cbExecutionInfoList(void);+extern CBoxMountCb cbMount(void);extern CBoxMetricsCb cbBoxMetrics(void);extern CRuntimeMetricsCb cbRuntimeMetrics(void);diff --git a/sdks/go/mounts.go b/sdks/go/mounts.gonew file mode 100644index 000000000..17c1f9769--- /dev/null+++ b/sdks/go/mounts.go@@ -0,0 +1,168 @@+package boxlite++/*+#include "bridge.h"+#include <stdlib.h>+*/+import "C"+import (+ "context"+ "encoding/json"+ "fmt"+ "runtime/cgo"+ "strings"+ "unicode/utf8"+ "unsafe"+)++// MountOptions delivers Source from the runtime host at Target in the box.+type MountOptions struct {+ Source string+ Target string+ ReadOnly bool+}++// MountState reports the progress of a runtime mount.+type MountState string++const (+ // MountConfigured is saved for delivery when the box next starts.+ MountConfigured MountState = "configured"+ MountPreparing MountState = "preparing"+ MountMounted MountState = "mounted"+ MountDetaching MountState = "detaching"+)++// MountInfo describes one directory mount of a box.+type MountInfo struct {+ Source string `json:"source"`+ Target string `json:"target"`+ ReadOnly bool `json:"read_only"`+ State MountState `json:"state"`+}++// Mount controls runtime directory mounts of one box. It refers to its Box,+// so it stays usable until the box is closed and has no Close of its own.+type Mount struct{ box *Box }++// Mount returns the mount namespace without starting the box.+func (b *Box) Mount() *Mount { return &Mount{box: b} }++// Add delivers a directory and reports the mount for those options, confirmed+// as MountMounted by a running box. A stopped box is never started: it saves+// the mount and reports MountConfigured.+func (m *Mount) Add(ctx context.Context, options MountOptions) (MountInfo, error) {+ if err := validateMountPath(options.Source); err != nil {+ return MountInfo{}, err+ }+ if err := validateMountPath(options.Target); err != nil {+ return MountInfo{}, err+ }+ return callMounts[MountInfo](ctx, m.box, func(box *C.CBoxHandle, data unsafe.Pointer, cerr *C.CBoxliteError) C.enum_BoxliteErrorCode {+ source := toCString(options.Source)+ defer C.free(unsafe.Pointer(source))+ target := toCString(options.Target)+ defer C.free(unsafe.Pointer(target))+ return C.boxlite_box_mount_add(box, source, target, C.bool(options.ReadOnly), C.cbMount(), data, cerr)+ })+}++// Remove lazily detaches a runtime mount, so existing references stay usable.+// On a stopped box it discards the saved mount instead. The box is never started.+func (m *Mount) Remove(ctx context.Context, target string) error {+ if err := validateMountPath(target); err != nil {+ return err+ }+ // The C side reports a completed removal as the JSON text null.+ _, err := callMounts[struct{}](ctx, m.box, func(box *C.CBoxHandle, data unsafe.Pointer, cerr *C.CBoxliteError) C.enum_BoxliteErrorCode {+ path := toCString(target)+ defer C.free(unsafe.Pointer(path))+ return C.boxlite_box_mount_remove(box, path, C.cbMount(), data, cerr)+ })+ return err+}++// List returns the mounts of the box without starting it. A mount saved for+// the next start has state MountConfigured.+func (m *Mount) List(ctx context.Context) ([]MountInfo, error) {+ return callMounts[[]MountInfo](ctx, m.box, func(box *C.CBoxHandle, data unsafe.Pointer, cerr *C.CBoxliteError) C.enum_BoxliteErrorCode {+ return C.boxlite_box_mount_list(box, C.cbMount(), data, cerr)+ })+}++// Get reports the mount at target, or nil when the target has no mount.+func (m *Mount) Get(ctx context.Context, target string) (*MountInfo, error) {+ if err := validateMountPath(target); err != nil {+ return nil, err+ }+ return callMounts[*MountInfo](ctx, m.box, func(box *C.CBoxHandle, data unsafe.Pointer, cerr *C.CBoxliteError) C.enum_BoxliteErrorCode {+ path := toCString(target)+ defer C.free(unsafe.Pointer(path))+ return C.boxlite_box_mount_get(box, path, C.cbMount(), data, cerr)+ })+}++// validateMountPath refuses a path that would not cross the C boundary+// unchanged: C.CString stops at a NUL byte, and Rust rejects invalid UTF-8.+func validateMountPath(path string) error {+ if !utf8.ValidString(path) || strings.IndexByte(path, 0) >= 0 {+ return &Error{Code: ErrInvalidArgument, Message: "mount path must be valid UTF-8 without NUL"}+ }+ return nil+}++func callMounts[T any](ctx context.Context, box *Box, submit func(*C.CBoxHandle, unsafe.Pointer, *C.CBoxliteError) C.enum_BoxliteErrorCode) (T, error) {+ var result T+ if err := ctx.Err(); err != nil {+ return result, err+ }+ if box == nil || box.runtime == nil {+ return result, errBoxClosed+ }+ select {+ case <-box.runtime.closing:+ return result, ErrRuntimeClosed+ default:+ }+ handle, unlock, err := box.acquire()+ if err != nil {+ return result, err+ }+ box.runtime.ensureDrainRunning()+ ch := make(chan handleResult[string], 1)+ h := registerHandleForDispatch(cgo.NewHandle(ch))+ // A late callback can only claim a handle that its caller still owns.+ defer deleteHandleForDispatch(h)+ var cerr C.CBoxliteError+ code := submit(handle, handleToPtr(h), &cerr)+ unlock()+ if code != C.Ok {+ return result, freeError(&cerr)+ }+ select {+ case response := <-ch:+ if response.err != nil {+ return result, response.err+ }+ if err := json.Unmarshal([]byte(response.value), &result); err != nil {+ return result, fmt.Errorf("decode mount result: %w", err)+ }+ return result, nil+ case <-ctx.Done():+ return result, ctx.Err()+ case <-box.runtime.closing:+ return result, ErrRuntimeClosed+ }+}++//export goBoxliteOnMount+func goBoxliteOnMount(payload *C.char, cerr *C.CBoxliteError, userData unsafe.Pointer) {+ h := ptrToHandle(userData)+ if h == 0 || !claimHandleForDispatch(h) {+ return+ }+ defer h.Delete()+ // Borrowed C data is needed only while the caller is still waiting.+ ch := h.Value().(chan handleResult[string])+ ch <- handleResult[string]{value: cString(payload), err: borrowedAgentError(cerr)}+}diff --git a/sdks/go/mounts_test.go b/sdks/go/mounts_test.gonew file mode 100644index 000000000..648fc8f1b--- /dev/null+++ b/sdks/go/mounts_test.go@@ -0,0 +1,244 @@+package boxlite++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"+)++// Each case is one box status. A running box confirms MountMounted and may+// report another state later, so Add must return its own reply. A stopped box+// only saves the mount, and no mount call may start it.+func TestRuntimeMountsRoundTrip(t *testing.T) {+ const target = "/mount name & more"+ const base = "/v1/boxes/box1/mounts"+ options := MountOptions{Source: "/host/source", Target: target, ReadOnly: true}+ for _, tc := range []struct {+ status string+ added MountState+ later MountState+ }{+ {"running", MountMounted, MountDetaching},+ {"stopped", MountConfigured, MountConfigured},+ } {+ t.Run(tc.status, func(t *testing.T) {+ var mu sync.Mutex+ var saved *MountInfo+ // Requests outside the mount routes, such as one that starts the box.+ var other []string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ mu.Lock()+ defer mu.Unlock()+ switch {+ case mountTestMetadataFor(w, r, tc.status):+ case r.URL.Path == base && r.Method == http.MethodPost:+ var info MountInfo+ want := MountInfo{Source: options.Source, Target: target, ReadOnly: true}+ if err := json.NewDecoder(r.Body).Decode(&info); err != nil || info != want {+ t.Errorf("unexpected mount request: %+v, %v", info, err)+ w.WriteHeader(400)+ return+ }+ info.State = tc.added+ w.WriteHeader(201)+ _ = json.NewEncoder(w).Encode(info)+ info.State = tc.later+ saved = &info+ case r.URL.Path == base && r.Method == http.MethodGet:+ mounts := []MountInfo{}+ if saved != nil {+ mounts = append(mounts, *saved)+ }+ _ = json.NewEncoder(w).Encode(map[string][]MountInfo{"mounts": mounts})+ case r.URL.Path == base+"/by-target" && r.URL.Query().Get("target") == target:+ if r.Method == http.MethodDelete {+ if saved == nil {+ w.WriteHeader(404)+ _, _ = fmt.Fprint(w, `{"error":{"code":"not_found","message":"no mount"}}`)+ return+ }+ saved = nil+ w.WriteHeader(204)+ } else {+ _ = json.NewEncoder(w).Encode(saved)+ }+ default:+ other = append(other, r.Method+" "+r.URL.Path)+ w.WriteHeader(404)+ }+ }))+ defer server.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ runtime, mount := openTestMount(t, ctx, server.URL)+ defer runtime.Close()+ added, err := mount.Add(ctx, options)+ want := MountInfo{Source: options.Source, Target: target, ReadOnly: true, State: tc.added}+ if err != nil || added != want {+ t.Fatalf("Add = %+v, %v; want %+v", added, err, want)+ }+ all, err := mount.List(ctx)+ if err != nil || len(all) != 1 || all[0].State != tc.later {+ t.Fatalf("List = %+v, %v; want one %s mount", all, err, tc.later)+ }+ if got, err := mount.Get(ctx, target); err != nil || got == nil || *got != all[0] {+ t.Fatalf("Get = %+v, %v; want %+v", got, err, all)+ }+ if err := mount.Remove(ctx, target); err != nil {+ t.Fatal(err)+ }+ if got, err := mount.Get(ctx, target); got != nil || err != nil {+ t.Fatalf("Get after Remove = %+v, %v", got, err)+ }+ if err := mount.Remove(ctx, target); !IsNotFound(err) {+ t.Fatalf("Remove of an absent target = %v", err)+ }+ mu.Lock()+ defer mu.Unlock()+ for _, route := range other {+ t.Errorf("a mount call sent %s; it must not start the box", route)+ }+ })+ }+}++// Shutdown closes the liveness the retained Box handle shares, so C refuses+// the call before it could save a declaration on the stopped box.+func TestRuntimeMountsRefuseAddAfterShutdown(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if mountTestMetadataFor(w, r, "running") {+ return+ }+ t.Errorf("mount request after runtime shutdown: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusServiceUnavailable)+ }))+ defer server.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ runtime, mount := openTestMount(t, ctx, server.URL)+ defer runtime.Close()+ if err := runtime.Shutdown(ctx, time.Second); err != nil {+ t.Fatal(err)+ }+ options := MountOptions{Source: "/host/source", Target: "/workspace"}+ if _, err := mount.Add(ctx, options); !IsStopped(err) {+ t.Fatalf("Add after Shutdown = %v, want stopped", err)+ }+}++func TestRuntimeMountsReleaseWaitersOnCancelAndClose(t *testing.T) {+ for _, closeRuntime := range []bool{false, true} {+ t.Run(fmt.Sprintf("close_runtime=%v", closeRuntime), func(t *testing.T) {+ arrived := make(chan struct{})+ release := make(chan struct{})+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if mountTestMetadataFor(w, r, "running") {+ return+ }+ close(arrived)+ <-release+ _, _ = fmt.Fprint(w, `{"mounts":[]}`)+ }))+ defer server.Close()+ deadline, done := context.WithTimeout(context.Background(), 10*time.Second)+ defer done()+ runtime, mount := openTestMount(t, deadline, server.URL)+ var closed chan struct{}+ defer func() {+ close(release)+ if closed == nil {+ _ = runtime.Close()+ } else {+ <-closed+ }+ }()+ ctx, cancel := context.WithCancel(deadline)+ defer cancel()+ result := make(chan error, 1)+ go func() {+ _, err := mount.List(ctx)+ result <- err+ }()+ select {+ case <-arrived:+ case <-deadline.Done():+ t.Fatal("mount list never reached the server")+ }+ var expected error = context.Canceled+ if closeRuntime {+ closed = make(chan struct{})+ go func() {+ _ = runtime.Close()+ close(closed)+ }()+ expected = ErrRuntimeClosed+ } else {+ cancel()+ }+ select {+ case err := <-result:+ if !errors.Is(err, expected) {+ t.Fatalf("List returned %v, want %v", err, expected)+ }+ case <-deadline.Done():+ t.Fatal("mount list waiter was not released")+ }+ })+ }+}++func TestRuntimeMountsRejectUnusablePathsBeforeTheNativeCall(t *testing.T) {+ ctx := context.Background()+ // Without a box, a path that passes validation would report a closed box.+ mount := new(Mount)+ for _, path := range []string{"/bad\x00path", "/bad\xff"} {+ _, source := mount.Add(ctx, MountOptions{Source: path, Target: "/workspace"})+ _, target := mount.Add(ctx, MountOptions{Source: "/host", Target: path})+ _, get := mount.Get(ctx, path)+ for operation, err := range map[string]error{+ "add source": source, "add target": target, "get": get, "remove": mount.Remove(ctx, path),+ } {+ if !IsInvalidArgument(err) {+ t.Errorf("%s(%q) = %v, want invalid argument", operation, path, err)+ }+ }+ }+}++// mountTestMetadataFor answers the requests a mount call makes besides its own:+// the runtime capabilities and the metadata of a box1 in the given status.+func mountTestMetadataFor(w http.ResponseWriter, r *http.Request, status string) bool {+ switch r.URL.Path {+ case "/v1/config":+ _, _ = fmt.Fprint(w, `{"capabilities":{"runtime_mounts_enabled":true}}`)+ case "/v1/boxes/box1":+ _, _ = fmt.Fprintf(w, `{"box_id":"box1","status":%q,"image":"alpine:latest","cpus":1,"memory_mib":256,"created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}`, status)+ default:+ return false+ }+ return true+}++func openTestMount(t *testing.T, ctx context.Context, url string) (*Runtime, *Mount) {+ t.Helper()+ runtime, err := NewRest(BoxliteRestOptions{URL: url})+ if err != nil {+ t.Fatal(err)+ }+ box, err := runtime.Get(ctx, "box1")+ if err != nil {+ _ = runtime.Close()+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = box.Close() })+ return runtime, box.Mount()+}diff --git a/sdks/node/Cargo.toml b/sdks/node/Cargo.tomlindex f1c82a269..314aabdb4 100644--- a/sdks/node/Cargo.toml+++ b/sdks/node/Cargo.toml@@ -27,6 +27,10 @@ futures = "0.3"# Loggingtracing = "0.1"+# Local directory mounts are implemented by the native backend on this target.+[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]+boxlite = { path = "../../src/boxlite", features = ["native"] }+[dev-dependencies]boxlite = { path = "../../src/boxlite", features = ["test-support"] }diff --git a/sdks/node/README.md b/sdks/node/README.mdindex 0429b6afd..bae053ea9 100644--- a/sdks/node/README.md+++ b/sdks/node/README.md@@ -136,6 +136,40 @@ main();## API Reference+### Runtime directory mounts (release candidate)++Directory mounts require a Linux x86_64 native Box and the `native-vmm` experimental feature.+Reopen an existing Box after its creator releases the runtime home, or connect through REST when `boxlite serve` owns that home; see [creating a native Box](../../docs/guides/native-vmm.md).++```typescript+import { JsBoxlite, type MountOptions } from "@boxlite-ai/boxlite";++const runtime = new JsBoxlite({}, "native-vmm,custom-kernel");+const box = await runtime.get("dev");+if (!box) throw new Error("Native Box 'dev' was not found");++const options: MountOptions = {+ source: "/srv/projects/demo",+ target: "/workspace",+ readOnly: true,+};+const mounted = await box.mount.add(options);+const current = await box.mount.get("/workspace"); // null when absent+const mounts = await box.mount.list();+await box.mount.remove("/workspace");+```++No mount operation starts the Box: `add` saves a stopped Box's mount for its next start as+`configured`, and returns `mounted` on a running Box after guest confirmation. `get` and+`list` include saved mounts. `remove` drops a saved declaration or lazily detaches a live+mount, preserving open descriptors, and fails with code `not_found` for an absent target.+The four states are described in the [CLI reference](../../docs/reference/cli/README.md#boxlite-mount).++`SimpleBox.mount` forwards to its existing Box and throws before that Box exists.+For REST, enable the feature on the server; source paths refer to that server's filesystem.+Mount methods take no `AbortSignal`; abandoning a Promise only stops waiting, so inspect with+`get` or `list` before retrying.+### Remote BoxLite server (REST)Connect to a remote BoxLite server instead of the local runtime.diff --git a/sdks/node/lib/index.ts b/sdks/node/lib/index.tsindex f19a9bf15..2c06d4663 100644--- a/sdks/node/lib/index.ts+++ b/sdks/node/lib/index.ts@@ -47,6 +47,10 @@ export type {ImageAliasEvent,ImageUsage,ImageVersion,+ MountHandle,+ MountInfo,+ MountOptions,+ MountState,NewRegistryCredential,RegistryCredential,RegistryHandle,@@ -75,7 +79,7 @@ export type BoxliteConstructor = Omit<JsBoxliteConstructor,"rest" | "withDefaultConfig"> & {- new (options: JsOptions): Boxlite;+ new (options: JsOptions, experimentalFeatures?: string): Boxlite;withDefaultConfig(): Boxlite;rest(options: BoxliteRestOptions): Boxlite;};@@ -84,7 +88,7 @@ const nativeBoxlite = getJsBoxlite();const NativeBoxliteRestOptions = getNativeBoxliteRestOptions();class BoxliteWithBagRest extends (nativeBoxlite as unknown as {- new (options: JsOptions): JsBoxliteInstance;+ new (options: JsOptions, experimentalFeatures?: string): JsBoxliteInstance;}) {static rest(options: BoxliteRestOptions): Boxlite {return nativeBoxlite.rest(diff --git a/sdks/node/lib/native-contracts.ts b/sdks/node/lib/native-contracts.tsindex d089d287c..88caa0667 100644--- a/sdks/node/lib/native-contracts.ts+++ b/sdks/node/lib/native-contracts.ts@@ -643,6 +643,37 @@ export interface JsSshHandle {disable(): Promise<JsSshStatus>;}+export interface MountOptions {+ source: string;+ target: string;+ readOnly?: boolean;+}++/**+ * `configured` is saved for the box's next start, `preparing` is not yet+ * confirmed by the guest, `mounted` is visible in the container and+ * `detaching` is being removed.+ */+export type MountState = "configured" | "preparing" | "mounted" | "detaching";++export interface MountInfo {+ source: string;+ target: string;+ readOnly: boolean;+ state: MountState;+}++/** Runtime directory mounts of one box, reached as `box.mount`. */+export interface MountHandle {+ /** Deliver a directory; a stopped box saves it for its next start. */+ add(options: MountOptions): Promise<MountInfo>;+ /** Fails with code `not_found` when no mount is at `target`. */+ remove(target: string): Promise<void>;+ list(): Promise<MountInfo[]>;+ /** The mount at `target`, or `null` when no mount is there. */+ get(target: string): Promise<MountInfo | null>;+}+export interface JsNetworkHandle {updateInbound(spec: {mode: "enabled" | "disabled";@@ -763,6 +794,7 @@ export interface JsBox {readonly snapshot: JsSnapshotHandle;readonly network: JsNetworkHandle;readonly ssh: JsSshHandle;+ readonly mount: MountHandle;cloneBox(options?: JsCloneOptions | null,name?: string | null,@@ -820,7 +852,7 @@ export interface JsBoxlite {}export interface JsBoxliteConstructor {- new (options: JsOptions): JsBoxlite;+ new (options: JsOptions, experimentalFeatures?: string): JsBoxlite;withDefaultConfig(): JsBoxlite;initDefault(options: JsOptions): void;/** Connect to a remote BoxLite REST server. Takes the nativediff --git a/sdks/node/lib/simplebox.ts b/sdks/node/lib/simplebox.tsindex 8b9d00688..51c41fabd 100644--- a/sdks/node/lib/simplebox.ts+++ b/sdks/node/lib/simplebox.ts@@ -22,6 +22,7 @@ import type {JsSshCaConfig,JsSshConfig,JsSshStatus,+ MountHandle,JsVolumeSpec,NativeBoxConnection,NativeBoxTunnel,@@ -621,6 +622,12 @@ export class SimpleBox {};}+ /** Access the existing box's runtime mounts without starting it. */+ get mount(): MountHandle {+ if (!this._box) throw new Error("Box has not been created");+ return this._box.mount;+ }+protected _runtime: BoxRuntime;protected _box: BoxLike | null = null;protected _boxPromise: Promise<BoxLike> | null = null;diff --git a/sdks/node/src/box_handle.rs b/sdks/node/src/box_handle.rsindex c5197f1d3..da98cec67 100644--- a/sdks/node/src/box_handle.rs+++ b/sdks/node/src/box_handle.rs@@ -8,6 +8,7 @@ use crate::copy::{JsCopyOptions, into_copy_options};use crate::exec::JsExecution;use crate::info::JsBoxInfo;use crate::metrics::JsBoxMetrics;+use crate::mounts::JsMountHandle;use crate::network::JsNetworkHandle;use crate::snapshot_options::{JsCloneOptions, JsExportOptions};use crate::snapshots::JsSnapshotHandle;@@ -137,6 +138,12 @@ impl JsBox {JsSshHandle::from(self.handle.as_ref())}+ /// Get runtime directory mounts without starting the box.+ #[napi(getter)]+ pub fn mount(&self) -> JsMountHandle {+ JsMountHandle(self.handle.mount())+ }+/// Get the network handle for this box.#[napi(getter)]pub fn network(&self) -> JsNetworkHandle {diff --git a/sdks/node/src/lib.rs b/sdks/node/src/lib.rsindex 2d51653d7..e81ce07a5 100644--- a/sdks/node/src/lib.rs+++ b/sdks/node/src/lib.rs@@ -16,6 +16,7 @@ mod executions;mod images;mod info;mod metrics;+mod mounts;mod network;mod options;mod registries;@@ -43,6 +44,7 @@ pub use info::{JsBoxInfo, JsBoxStateInfo, JsHealthState, JsHealthStatus, JsNetworkInfo, JsPublishedPort,};pub use metrics::{JsBoxMetrics, JsRuntimeMetrics};+pub use mounts::{JsMountHandle, JsMountInfo, JsMountOptions};pub use network::{JsBoxConnection, JsBoxTunnel, JsNetworkHandle, JsSocketAddress, JsTunnelForwarder,};diff --git a/sdks/node/src/mounts.rs b/sdks/node/src/mounts.rsnew file mode 100644index 000000000..36cfcad5c--- /dev/null+++ b/sdks/node/src/mounts.rs@@ -0,0 +1,91 @@+use boxlite::{MountHandle, MountInfo, MountOptions};+use napi::bindgen_prelude::*;+use napi_derive::napi;++use crate::util::map_err;++#[napi(object)]+pub struct JsMountOptions {+ pub source: String,+ pub target: String,+ pub read_only: Option<bool>,+}++#[napi(object)]+pub struct JsMountInfo {+ pub source: String,+ pub target: String,+ pub read_only: bool,+ pub state: String,+}++impl From<MountInfo> for JsMountInfo {+ fn from(info: MountInfo) -> Self {+ Self {+ source: info.source.display().to_string(),+ target: info.target.display().to_string(),+ read_only: info.read_only,+ state: info.state.to_string(),+ }+ }+}++/// Runtime directory mounts of one box, reached as `box.mount`.+///+/// A mount's `state` is `configured` while it is saved for the box's next+/// start, `preparing` until the guest confirms it, `mounted` once it is+/// visible in the container and `detaching` while its removal is incomplete.+/// No operation starts the box.+#[napi]+pub struct JsMountHandle(pub(crate) MountHandle);++#[napi]+impl JsMountHandle {+ /// Deliver a host directory into the container.+ ///+ /// A running box answers once the guest confirmed the mount. A stopped+ /// box saves it for its next start and answers `configured`.+ #[napi]+ pub async fn add(&self, options: JsMountOptions) -> Result<JsMountInfo> {+ self.0+ .add(MountOptions {+ source: options.source.into(),+ target: options.target.into(),+ read_only: options.read_only.unwrap_or_default(),+ })+ .await+ .map(JsMountInfo::from)+ .map_err(map_err)+ }++ /// Remove the mount at `target`, saved or live. Fails with code+ /// `not_found` when no mount is there.+ #[napi]+ pub async fn remove(&self, target: String) -> Result<()> {+ self.0.remove(target).await.map_err(map_err)+ }++ /// Every mount of the box, saved or live.+ #[napi]+ pub async fn list(&self) -> Result<Vec<JsMountInfo>> {+ Ok(self+ .0+ .list()+ .await+ .map_err(map_err)?+ .into_iter()+ .map(JsMountInfo::from)+ .collect())+ }++ /// The mount at `target`, or `null` when no mount is there.+ #[napi]+ pub async fn get(&self, target: String) -> Result<Option<JsMountInfo>> {+ Ok(self+ .0+ .get(target)+ .await+ .map_err(map_err)?+ .map(JsMountInfo::from))+ }+}diff --git a/sdks/node/src/runtime.rs b/sdks/node/src/runtime.rsindex 86948f9a8..f458dd08f 100644--- a/sdks/node/src/runtime.rs+++ b/sdks/node/src/runtime.rs@@ -1,5 +1,6 @@use std::sync::Arc;+use boxlite::experimental::{ExperimentalFeatures, RuntimeBuilder};use boxlite::{BoxArchive, BoxOptions, BoxliteOptions, BoxliteRuntime};use napi::bindgen_prelude::*;use napi_derive::napi;@@ -29,17 +30,24 @@ impl JsBoxlite {////// # Arguments/// * `options` - Runtime configuration (e.g., custom home directory)+ /// * `experimental_features` - Comma-separated opt-ins for the local runtime////// # Example/// ```javascript/// const runtime = new Boxlite({ homeDir: '/custom/path' });/// ```#[napi(constructor)]- pub fn new(options: JsOptions) -> Result<Self> {+ pub fn new(options: JsOptions, experimental_features: Option<String>) -> Result<Self> {+ let features =+ ExperimentalFeatures::parse(experimental_features.as_deref().unwrap_or_default())+ .map_err(map_err)?;let core_opts = js_options_into_core(options)?;// Executable-owned logging init (the library no longer auto-installs a subscriber).let _ = boxlite::init_logging_for(&core_opts.home_dir);- let runtime = BoxliteRuntime::new(core_opts).map_err(map_err)?;+ let runtime = RuntimeBuilder::new(core_opts)+ .with_features(features)+ .build()+ .map_err(map_err)?;Ok(Self {runtime: Arc::new(runtime),diff --git a/sdks/node/tests/runtime-mounts.integration.test.ts b/sdks/node/tests/runtime-mounts.integration.test.tsnew file mode 100644index 000000000..27dea9ba2--- /dev/null+++ b/sdks/node/tests/runtime-mounts.integration.test.ts@@ -0,0 +1,174 @@+import { once } from "node:events";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { text } from "node:stream/consumers";+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import {+ BoxliteRestOptions,+ JsBoxlite,+ SimpleBox,+ errorCode,+ type Boxlite,+} from "../lib/index.js";++const boxId = "runtime-mounts-box";+const target = "/workspace/a & b";+const collection = `/v1/boxes/${boxId}/mounts`;+const detail = `${collection}/by-target?target=%2Fworkspace%2Fa+%26+b`;+const start = `/v1/boxes/${boxId}/start`;+const boxInfo = {+ box_id: boxId,+ status: "running",+ image: "alpine:latest",+ cpus: 1,+ memory_mib: 256,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ privileged: false, // read back before a SimpleBox may reuse the box+};++type Reply = { status: number; body?: unknown };++// A loopback server answers the box API's mount routes, so what the test+// reads back, and what the server saw, crossed the REST client and the binding.+describe("runtime mounts on a REST runtime", () => {+ let server: Server;+ let replies: Map<string, Reply>;+ let requests: Array<{ route: string; body: string }>;+ let runtime: Boxlite;++ beforeEach(async () => {+ replies = new Map();+ requests = [];+ server = createServer(async (req, res) => {+ const route = `${req.method} ${req.url}`;+ requests.push({ route, body: await text(req) });+ const { status, body } = replies.get(route) ?? { status: 404, body: {} };+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify(body));+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const { port } = server.address() as AddressInfo;+ runtime = JsBoxlite.rest(+ new BoxliteRestOptions({ url: `http://127.0.0.1:${port}` }),+ );+ });++ afterEach(async () => {+ runtime.close();+ const closed = once(server, "close");+ server.close();+ server.closeAllConnections();+ await closed;+ });++ test("runtime mounts share the Node and SimpleBox REST contract", async () => {+ const options = { source: "/host/project", target };+ const mount = { ...options, read_only: false, state: "mounted" };+ replies.set("GET /v1/config", {+ status: 200,+ body: { capabilities: { runtime_mounts_enabled: true } },+ });+ replies.set(`GET /v1/boxes/${boxId}`, { status: 200, body: boxInfo });+ replies.set(`POST ${collection}`, { status: 201, body: mount });+ replies.set(`GET ${collection}`, {+ status: 200,+ body: { mounts: [mount] },+ });+ replies.set(`GET ${detail}`, { status: 200, body: mount });+ replies.set(`DELETE ${detail}`, { status: 204 });++ const simple = new SimpleBox({+ image: "alpine:latest",+ runtime,+ name: boxId,+ reuseExisting: true,+ });+ expect(() => simple.mount).toThrow("Box has not been created");+ expect(await simple.getId()).toBe(boxId);+ const box = (await runtime.get(boxId))!;+ expect(await simple.mount.add(options)).toEqual({+ ...options,+ readOnly: false,+ state: "mounted",+ });+ const posted = requests.filter(+ ({ route }) => route === `POST ${collection}`,+ );+ expect(posted.map(({ body }) => JSON.parse(body))).toEqual([+ { ...options, read_only: false },+ ]);+ mount.state = "detaching";+ expect((await box.mount.get(target))?.state).toBe("detaching");+ expect(await simple.mount.list()).toEqual([+ { ...options, readOnly: false, state: "detaching" },+ ]);+ await simple.mount.remove(target);+ replies.set(`GET ${detail}`, { status: 200, body: null });+ replies.set(`GET ${collection}`, { status: 200, body: { mounts: [] } });+ replies.set(`DELETE ${detail}`, {+ status: 404,+ body: { error: { code: "not_found", message: "no mount" } },+ });+ expect(await box.mount.get(target)).toBeNull();+ expect(await box.mount.list()).toEqual([]);+ await expect(box.mount.remove(target).catch(errorCode)).resolves.toBe(+ "not_found",+ );+ const routes = requests.map(({ route }) => route);+ expect(routes).toContain(`GET ${detail}`);+ expect(routes).toContain(`DELETE ${detail}`);+ });++ test("a server without the capability answers unsupported", async () => {+ replies.set("GET /v1/config", {+ status: 200,+ body: { capabilities: { runtime_mounts_enabled: false } },+ });+ replies.set(`GET /v1/boxes/${boxId}`, { status: 200, body: boxInfo });+ const box = (await runtime.get(boxId))!;+ await expect(box.mount.list().catch(errorCode)).resolves.toBe(+ "unsupported",+ );+ });++ test("a stopped box saves a configured mount without starting", async () => {+ const options = { source: "/host/project", target };+ const saved = { ...options, read_only: false, state: "configured" };+ replies.set("GET /v1/config", {+ status: 200,+ body: { capabilities: { runtime_mounts_enabled: true } },+ });+ replies.set(`GET /v1/boxes/${boxId}`, {+ status: 200,+ body: { ...boxInfo, status: "stopped" },+ });+ replies.set(`POST ${collection}`, { status: 201, body: saved });+ replies.set(`GET ${collection}`, {+ status: 200,+ body: { mounts: [saved] },+ });+ replies.set(`GET ${detail}`, { status: 200, body: saved });+ replies.set(`DELETE ${detail}`, { status: 204 });++ const simple = new SimpleBox({+ image: "alpine:latest",+ runtime,+ name: boxId,+ reuseExisting: true,+ });+ expect(await simple.getId()).toBe(boxId);+ const box = (await runtime.get(boxId))!;+ const expected = { ...options, readOnly: false, state: "configured" };+ expect(await simple.mount.add(options)).toEqual(expected);+ expect(await box.mount.get(target)).toEqual(expected);+ expect(await simple.mount.list()).toEqual([expected]);+ await box.mount.remove(target);+ replies.set(`GET ${detail}`, { status: 200, body: null });+ replies.set(`GET ${collection}`, { status: 200, body: { mounts: [] } });+ expect(await box.mount.get(target)).toBeNull();+ expect(await simple.mount.list()).toEqual([]);+ expect(requests.map(({ route }) => route)).not.toContain(`POST ${start}`);+ });+});diff --git a/sdks/python/Cargo.toml b/sdks/python/Cargo.tomlindex cb83aebb1..ccb2ecf43 100644--- a/sdks/python/Cargo.toml+++ b/sdks/python/Cargo.toml@@ -28,6 +28,10 @@ futures = "0.3.31"tracing = "0.1.44"serde_json = "1.0"+# Local directory mounts are implemented by the native backend on this target.+[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]+boxlite = { path = "../../src/boxlite", features = ["native"] }+[dev-dependencies]boxlite = { path = "../../src/boxlite", features = ["test-support"] }# `cargo test --no-default-features` links libpython but does not start andiff --git a/sdks/python/README.md b/sdks/python/README.mdindex c282f819f..d323fefce 100644--- a/sdks/python/README.md+++ b/sdks/python/README.md@@ -258,6 +258,39 @@ await runtime.images.registries.remove(login.id) # refused while a box pulls thSee [the Python reference](../../docs/reference/python/README.md#boxliteregistryhandle).+### Runtime directory mounts (release candidate)++Directory mounts require a Linux x86_64 native Box and the `native-vmm` experimental feature.+Reopen an existing Box after its creator releases the runtime home, or connect through REST when `boxlite serve` owns that home; see [creating a native Box](../../docs/guides/native-vmm.md).++```python+from boxlite import Boxlite, MountOptions, Options++runtime = Boxlite(Options(), experimental_features="native-vmm,custom-kernel")+box = await runtime.get("dev")+if box is None:+ raise LookupError("native Box 'dev' was not found")++mounted = await box.mount.add(+ MountOptions(source="/srv/projects/demo", target="/workspace", read_only=True)+)+current = await box.mount.get("/workspace") # None when absent+mounts = await box.mount.list()+await box.mount.remove("/workspace")+```++No mount operation starts the Box: `add` saves a stopped Box's mount for its next start as+`configured`, and returns `mounted` on a running Box after guest confirmation. `get` and+`list` include saved mounts. `remove` drops a saved declaration or lazily detaches a live+mount, preserving open descriptors, and raises `NotFoundError` for an absent target.+The four states are described in the [CLI reference](../../docs/reference/cli/README.md#boxlite-mount).++`SyncBox.mount` provides the same calls without `await`; construct its runtime with+`SyncBoxlite(Options(), experimental_features=...)`. `SimpleBox.mount` and `SyncSimpleBox.mount`+forward to their existing Box and raise `RuntimeError` before that Box exists.+For REST, enable the feature on the server; source paths refer to that server's filesystem.+Cancelling an await only stops waiting, so inspect with `get` or `list` before retrying.+### Remote BoxLite server (REST)Connect to a remote BoxLite server instead of the local runtime. Authdiff --git a/sdks/python/boxlite/__init__.py b/sdks/python/boxlite/__init__.pyindex f8f820f40..c273c60f6 100644--- a/sdks/python/boxlite/__init__.py+++ b/sdks/python/boxlite/__init__.py@@ -48,6 +48,9 @@ try:ImageVersion,InboundNetworkInfo,InboundNetworkSpec,+ MountHandle,+ MountInfo,+ MountOptions,NetworkHandle,NetworkInfo,NetworkSpec,@@ -105,6 +108,9 @@ try:"OutboundNetworkInfo","InboundNetworkInfo","Box",+ "MountHandle",+ "MountInfo",+ "MountOptions","Execution","ExecutionInfo","Executions",@@ -270,6 +276,7 @@ try:SyncExecution,SyncExecutions,SyncImageHandle,+ SyncMountHandle,SyncNetworkHandle,SyncRegistryHandle,SyncSimpleBox,@@ -293,6 +300,7 @@ try:"SyncExecution","SyncExecutions","SyncImageHandle",+ "SyncMountHandle","SyncNetworkHandle","SyncRegistryHandle","SyncSimpleBox",diff --git a/sdks/python/boxlite/simplebox.py b/sdks/python/boxlite/simplebox.pyindex 9c1117686..3785ee1ba 100644--- a/sdks/python/boxlite/simplebox.py+++ b/sdks/python/boxlite/simplebox.py@@ -18,6 +18,7 @@ if TYPE_CHECKING:Execution,ExecutionInfo,InboundNetworkSpec,+ MountHandle,OutboundNetworkSpec,TunnelForwarder,TunnelOptions,@@ -158,6 +159,13 @@ class SimpleBox:return Agents(resolve=resolve)+ @property+ def mount(self) -> "MountHandle":+ """Access the existing box's runtime mounts without starting it."""+ if self._box is None:+ raise RuntimeError("Box has not been created")+ return self._box.mount+def __init__(self,image: str | None = None,diff --git a/sdks/python/boxlite/sync_api/__init__.py b/sdks/python/boxlite/sync_api/__init__.pyindex a99391190..9799a4d4f 100644--- a/sdks/python/boxlite/sync_api/__init__.py+++ b/sdks/python/boxlite/sync_api/__init__.py@@ -50,6 +50,7 @@ from ._domains import SyncDomainHandlefrom ._execution import SyncExecStderr, SyncExecStdout, SyncExecutionfrom ._executions import SyncExecutionsfrom ._images import SyncImageHandle+from ._mounts import SyncMountHandlefrom ._network import SyncNetworkHandle, SyncTunnelForwarderfrom ._registries import SyncRegistryHandlefrom ._simplebox import SyncSimpleBox@@ -72,6 +73,7 @@ __all__ = [ # noqa: RUF022 - grouped by API area, not alphabetical"SyncCheckpointHandle","SyncDomainHandle","SyncImageHandle",+ "SyncMountHandle","SyncNetworkHandle","SyncSshHandle","SyncRegistryHandle",diff --git a/sdks/python/boxlite/sync_api/_box.py b/sdks/python/boxlite/sync_api/_box.pyindex f2fd75959..7dbde3715 100644--- a/sdks/python/boxlite/sync_api/_box.py+++ b/sdks/python/boxlite/sync_api/_box.py@@ -7,6 +7,7 @@ Box metadata is intentionally available only through the async ``Box.info()`` APfrom typing import TYPE_CHECKINGfrom ._agents import SyncAgents+from ._mounts import SyncMountHandleif TYPE_CHECKING:from ..boxlite import Box, BoxMetrics, TunnelOptions@@ -47,6 +48,11 @@ class SyncBox:"""Get the agent namespace without starting the Box."""return SyncAgents(lambda: self)+ @property+ def mount(self) -> SyncMountHandle:+ """Get the runtime mount namespace without starting the box."""+ return SyncMountHandle(self)+def __init__(self,runtime: "SyncBoxlite",diff --git a/sdks/python/boxlite/sync_api/_boxlite.py b/sdks/python/boxlite/sync_api/_boxlite.pyindex b00a08f52..58b99f8ec 100644--- a/sdks/python/boxlite/sync_api/_boxlite.py+++ b/sdks/python/boxlite/sync_api/_boxlite.py@@ -65,16 +65,17 @@ class SyncBoxlite:- When task completes, callback switches back to user fiber"""- def __init__(self, options: "Options") -> None:+ def __init__(self, options: "Options", *, experimental_features: str = "") -> None:"""Create a new SyncBoxlite instance.Args:options: Runtime options (e.g., custom home_dir).Use SyncBoxlite.default() for default runtime.+ experimental_features: Comma-separated opt-ins for the local runtime."""from ..boxlite import Boxlite- self._adopt(Boxlite(options))+ self._adopt(Boxlite(options, experimental_features=experimental_features))def _adopt(self, boxlite: "Boxlite") -> None:"""Wrap an async runtime; the dispatcher starts on __enter__/start()."""diff --git a/sdks/python/boxlite/sync_api/_mounts.py b/sdks/python/boxlite/sync_api/_mounts.pynew file mode 100644index 000000000..b55289ae1--- /dev/null+++ b/sdks/python/boxlite/sync_api/_mounts.py@@ -0,0 +1,39 @@+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from ..boxlite import MountInfo, MountOptions+ from ._box import SyncBox++__all__ = ["SyncMountHandle"]+++class SyncMountHandle:+ """Runtime directory mounts on an existing Box.++ ``state`` is ``"configured"`` while a mount is saved for the Box's next+ start, ``"preparing"`` until the guest confirms it, ``"mounted"`` once it+ is visible in the container and ``"detaching"`` while its removal is+ incomplete. No operation starts the Box.+ """++ def __init__(self, box: "SyncBox") -> None:+ self._box = box++ def add(self, options: "MountOptions") -> "MountInfo":+ """Deliver a directory; a stopped Box saves it and answers ``configured``."""+ return self._box._sync(self._box._box.mount.add(options))++ def remove(self, target: str) -> None:+ """Lazily detach the mount at target, or drop it while still saved.++ Raises ``NotFoundError`` when no mount is there.+ """+ self._box._sync(self._box._box.mount.remove(target))++ def list(self) -> "list[MountInfo]":+ """List the Box's runtime mounts, saved or live."""+ return self._box._sync(self._box._box.mount.list())++ def get(self, target: str) -> "MountInfo | None":+ """Read the mount at target, if present."""+ return self._box._sync(self._box._box.mount.get(target))diff --git a/sdks/python/boxlite/sync_api/_simplebox.py b/sdks/python/boxlite/sync_api/_simplebox.pyindex 6aca4631e..2da4b6a64 100644--- a/sdks/python/boxlite/sync_api/_simplebox.py+++ b/sdks/python/boxlite/sync_api/_simplebox.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Optionalfrom ..exec import ExecResult, _close_exec_stdinfrom ._agents import SyncAgents+from ._mounts import SyncMountHandleif TYPE_CHECKING:from ..boxlite import TunnelOptions@@ -53,6 +54,13 @@ class SyncSimpleBox:return SyncAgents(resolve)+ @property+ def mount(self) -> SyncMountHandle:+ """Access the existing box's runtime mounts without starting it."""+ if self._box is None:+ raise RuntimeError("Box has not been created")+ return self._box.mount+def __init__(self,image: str | None = None,diff --git a/sdks/python/src/box_handle.rs b/sdks/python/src/box_handle.rsindex d0fd8879b..37bb01a3c 100644--- a/sdks/python/src/box_handle.rs+++ b/sdks/python/src/box_handle.rs@@ -5,6 +5,7 @@ use crate::exec::PyExecution;use crate::executions::PyExecutions;use crate::info::PyBoxInfo;use crate::metrics::PyBoxMetrics;+use crate::mounts::PyMountHandle;use crate::network::PyNetworkHandle;use crate::snapshot_options::{PyCloneOptions, PyExportOptions};use crate::snapshots::PySnapshotHandle;@@ -80,6 +81,12 @@ impl PyBox {PySshHandle::new(self.handle.ssh())}+ /// Get runtime directory mounts without starting the box.+ #[getter]+ fn mount(&self) -> PyMountHandle {+ PyMountHandle(self.handle.mount())+ }+#[pyo3(signature = (command, args=None, env=None, tty=false, user=None, timeout_secs=None, cwd=None))]#[allow(clippy::too_many_arguments)]fn exec<'a>(diff --git a/sdks/python/src/lib.rs b/sdks/python/src/lib.rsindex 127dff5e0..07a3ea91e 100644--- a/sdks/python/src/lib.rs+++ b/sdks/python/src/lib.rs@@ -10,6 +10,7 @@ mod executions;mod images;mod info;mod metrics;+mod mounts;mod network;mod options;mod registries;@@ -67,6 +68,9 @@ fn boxlite_python(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<PyContainerCapabilities>()?;m.add_class::<PyBoxlite>()?;m.add_class::<PyBox>()?;+ m.add_class::<mounts::PyMountHandle>()?;+ m.add_class::<mounts::PyMountOptions>()?;+ m.add_class::<mounts::PyMountInfo>()?;m.add_class::<PyExecution>()?;m.add_class::<PyExecutions>()?;m.add_class::<PyExecutionInfo>()?;diff --git a/sdks/python/src/mounts.rs b/sdks/python/src/mounts.rsnew file mode 100644index 000000000..b7316d5f2--- /dev/null+++ b/sdks/python/src/mounts.rs@@ -0,0 +1,110 @@+use boxlite::{MountHandle, MountInfo, MountOptions};+use pyo3::prelude::*;++use crate::util::map_err;++#[pyclass(name = "MountOptions", get_all, set_all)]+pub(crate) struct PyMountOptions {+ source: String,+ target: String,+ read_only: bool,+}++#[pymethods]+impl PyMountOptions {+ #[new]+ #[pyo3(signature = (*, source, target, read_only = false))]+ fn new(source: String, target: String, read_only: bool) -> Self {+ Self {+ source,+ target,+ read_only,+ }+ }+}++#[pyclass(name = "MountInfo", frozen, get_all)]+pub(crate) struct PyMountInfo {+ source: String,+ target: String,+ read_only: bool,+ state: String,+}++impl From<MountInfo> for PyMountInfo {+ fn from(info: MountInfo) -> Self {+ Self {+ source: info.source.display().to_string(),+ target: info.target.display().to_string(),+ read_only: info.read_only,+ state: info.state.to_string(),+ }+ }+}++/// Runtime directory mounts of one box, reached as `box.mount`.+///+/// A mount's `state` is `configured` while it is saved for the box's next+/// start, `preparing` until the guest confirms it, `mounted` once it is+/// visible in the container and `detaching` while its removal is incomplete.+/// No operation starts the box.+#[pyclass(name = "MountHandle")]+pub(crate) struct PyMountHandle(pub(crate) MountHandle);++#[pymethods]+impl PyMountHandle {+ /// Deliver a host directory into the container.+ ///+ /// A running box answers once the guest confirmed the mount. A stopped+ /// box saves it for its next start and answers `configured`.+ fn add<'py>(&self, py: Python<'py>, options: &PyMountOptions) -> PyResult<Bound<'py, PyAny>> {+ let mount = self.0.clone();+ let options = MountOptions {+ source: (&options.source).into(),+ target: (&options.target).into(),+ read_only: options.read_only,+ };+ pyo3_async_runtimes::tokio::future_into_py(py, async move {+ mount+ .add(options)+ .await+ .map(PyMountInfo::from)+ .map_err(map_err)+ })+ }++ /// Remove the mount at `target`, saved or live. Raises `NotFoundError`+ /// when no mount is there.+ fn remove<'py>(&self, py: Python<'py>, target: String) -> PyResult<Bound<'py, PyAny>> {+ let mount = self.0.clone();+ pyo3_async_runtimes::tokio::future_into_py(py, async move {+ mount.remove(target).await.map_err(map_err)+ })+ }++ /// Every mount of the box, saved or live.+ fn list<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {+ let mount = self.0.clone();+ pyo3_async_runtimes::tokio::future_into_py(py, async move {+ Ok(mount+ .list()+ .await+ .map_err(map_err)?+ .into_iter()+ .map(PyMountInfo::from)+ .collect::<Vec<_>>())+ })+ }++ /// The mount at `target`, or `None` when no mount is there.+ fn get<'py>(&self, py: Python<'py>, target: String) -> PyResult<Bound<'py, PyAny>> {+ let mount = self.0.clone();+ pyo3_async_runtimes::tokio::future_into_py(py, async move {+ Ok(mount+ .get(target)+ .await+ .map_err(map_err)?+ .map(PyMountInfo::from))+ })+ }+}diff --git a/sdks/python/src/runtime.rs b/sdks/python/src/runtime.rsindex 3a22131ce..83f9c274b 100644--- a/sdks/python/src/runtime.rs+++ b/sdks/python/src/runtime.rs@@ -1,5 +1,6 @@use std::sync::Arc;+use boxlite::experimental::{ExperimentalFeatures, RuntimeBuilder};use boxlite::{BoxArchive, BoxOptions, BoxliteOptions, BoxliteRuntime};use pyo3::prelude::*;@@ -20,11 +21,16 @@ pub(crate) struct PyBoxlite {#[pymethods]impl PyBoxlite {#[new]- fn new(options: PyOptions) -> PyResult<Self> {+ #[pyo3(signature = (options, *, experimental_features = ""))]+ fn new(options: PyOptions, experimental_features: &str) -> PyResult<Self> {+ let features = ExperimentalFeatures::parse(experimental_features).map_err(map_err)?;let core_opts = options.into_core()?;// Executable-owned logging init (the library no longer auto-installs a subscriber).let _ = boxlite::init_logging_for(&core_opts.home_dir);- let runtime = BoxliteRuntime::new(core_opts).map_err(map_err)?;+ let runtime = RuntimeBuilder::new(core_opts)+ .with_features(features)+ .build()+ .map_err(map_err)?;Ok(Self {runtime: Arc::new(runtime),diff --git a/sdks/python/tests/test_runtime_mounts.py b/sdks/python/tests/test_runtime_mounts.pynew file mode 100644index 000000000..c466bf89b--- /dev/null+++ b/sdks/python/tests/test_runtime_mounts.py@@ -0,0 +1,221 @@+import importlib.util+import json+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from threading import Thread+from urllib.parse import urlencode++import pytest++native_present = importlib.util.find_spec("boxlite.boxlite") is not None+sync_present = False+if native_present:+ from boxlite import Boxlite, BoxliteRestOptions, MountOptions, SimpleBox+ from boxlite.errors import NotFoundError, UnsupportedError++ # greenlet is an optional dependency of the sync API. An environment with+ # the native extension but without it must skip the sync test instead of+ # failing the whole collection, as test_codebox_timeout_forwarding.py does.+ try:+ from boxlite.sync_api import SyncBoxlite, SyncSimpleBox++ sync_present = True+ except ImportError:+ pass++pytestmark = pytest.mark.skipif(not native_present, reason="native extension not built")++BOX = "runtime-mounts-box"+TARGET = "/workspace/my files & logs"+BOX_PATH = f"/v1/boxes/{BOX}"+COLLECTION = f"{BOX_PATH}/mounts"+DETAIL = f"{COLLECTION}/by-target?{urlencode({'target': TARGET})}"+START = f"{BOX_PATH}/start"+BOX_INFO = {+ "box_id": BOX,+ "status": "running",+ "image": "alpine:latest",+ "cpus": 1,+ "memory_mib": 256,+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-01T00:00:00Z",+ "privileged": False, # read back before a SimpleBox may reuse the box+}+++def mount_server():+ requests = []+ record = {+ "source": "/host/project",+ "target": TARGET,+ "read_only": False,+ "state": "mounted",+ }+ config = {"capabilities": {"runtime_mounts_enabled": True}}+ replies = {+ ("GET", "/v1/config"): (200, config),+ ("GET", BOX_PATH): (200, BOX_INFO),+ ("POST", f"{BOX_PATH}/start"): (200, BOX_INFO),+ ("POST", f"{BOX_PATH}/stop"): (200, BOX_INFO),+ ("POST", COLLECTION): (201, record),+ ("GET", COLLECTION): (200, {"mounts": [record]}),+ ("GET", DETAIL): (200, record),+ ("DELETE", DETAIL): (204, None),+ }++ class Handler(BaseHTTPRequestHandler):+ def answer(self):+ size = int(self.headers.get("Content-Length", 0))+ requests.append((self.command, self.path, self.rfile.read(size).decode()))+ status, reply = replies.get((self.command, self.path), (404, {}))+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ if status != 204:+ self.wfile.write(json.dumps(reply).encode())++ do_GET = do_POST = do_DELETE = answer++ def log_message(self, *args):+ pass++ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}", replies, requests, record+ finally:+ server.shutdown()+ thread.join()+++def fields(info):+ return (info.source, info.target, info.read_only, info.state)+++def posted_mount(requests):+ [body] = [+ body+ for method, path, body in requests+ if (method, path) == ("POST", COLLECTION)+ ]+ return json.loads(body)+++def routes(requests):+ """Every (method, path) the stub answered."""+ return [(method, path) for method, path, _ in requests]+++def stopped_box(replies, record):+ """Make the stub answer a stopped box whose mount is only saved."""+ replies["GET", BOX_PATH] = (200, {**BOX_INFO, "status": "stopped"})+ record["state"] = "configured"+++async def test_runtime_mounts_async_and_simple_box(mount_server):+ url, replies, requests, record = mount_server+ runtime = Boxlite.rest(BoxliteRestOptions(url=url))+ box = await runtime.get(BOX)+ async with SimpleBox(+ image="alpine:latest", runtime=runtime, name=BOX, reuse_existing=True+ ) as simple:+ mount = simple.mount+ added = await mount.add(MountOptions(source="/host/project", target=TARGET))+ assert fields(added) == ("/host/project", TARGET, False, "mounted")+ assert posted_mount(requests) == {+ "source": "/host/project",+ "target": TARGET,+ "read_only": False,+ }+ record["state"] = "detaching"+ assert (await box.mount.list())[0].state == "detaching"+ assert (await mount.get(TARGET)).state == "detaching"+ await mount.remove(TARGET)+ assert ("DELETE", DETAIL, "") in requests+ replies["GET", DETAIL] = (200, None)+ replies["GET", COLLECTION] = (200, {"mounts": []})+ assert await mount.get(TARGET) is None+ assert await mount.list() == []++[email protected](not sync_present, reason="greenlet not installed")+def test_runtime_mounts_sync_and_simple_box(mount_server):+ url, replies, requests, record = mount_server+ record.update(source="/host/readonly", read_only=True)+ with SyncBoxlite.rest(BoxliteRestOptions(url=url)) as runtime:+ box = runtime.get(BOX)+ with SyncSimpleBox(+ image="alpine:latest", runtime=runtime, name=BOX, reuse_existing=True+ ) as simple:+ mount = simple.mount+ options = MountOptions(+ source="/host/readonly", target=TARGET, read_only=True+ )+ assert fields(mount.add(options)) == (+ "/host/readonly",+ TARGET,+ True,+ "mounted",+ )+ assert posted_mount(requests) == {+ "source": "/host/readonly",+ "target": TARGET,+ "read_only": True,+ }+ assert fields(mount.list()[0]) == fields(mount.get(TARGET))+ mount.remove(TARGET)+ assert ("DELETE", DETAIL, "") in requests+ replies["GET", DETAIL] = (200, None)+ assert box.mount.get(TARGET) is None+++async def test_stopped_add_saves_a_configured_mount_without_starting(mount_server):+ url, replies, requests, record = mount_server+ stopped_box(replies, record)+ runtime = Boxlite.rest(BoxliteRestOptions(url=url))+ box = await runtime.get(BOX)++ added = await box.mount.add(MountOptions(source="/host/project", target=TARGET))++ assert fields(added) == ("/host/project", TARGET, False, "configured")+ assert posted_mount(requests) == {+ "source": "/host/project",+ "target": TARGET,+ "read_only": False,+ }+ assert fields(await box.mount.get(TARGET)) == fields(added)+ assert [fields(info) for info in await box.mount.list()] == [fields(added)]+ await box.mount.remove(TARGET)+ assert ("DELETE", DETAIL, "") in requests+ replies["GET", DETAIL] = (200, None)+ replies["GET", COLLECTION] = (200, {"mounts": []})+ assert await box.mount.get(TARGET) is None+ assert await box.mount.list() == []+ assert ("POST", START) not in routes(requests)+++async def test_absent_and_unsupported_mounts_keep_their_error_classes(mount_server):+ url, replies, _, _ = mount_server+ absent = (404, {"error": {"code": "not_found", "message": "no mount"}})+ replies["GET", DETAIL] = absent+ replies["DELETE", DETAIL] = absent+ runtime = Boxlite.rest(BoxliteRestOptions(url=url))+ box = await runtime.get(BOX)++ with pytest.raises(NotFoundError, match="no mount"):+ await box.mount.get(TARGET)+ with pytest.raises(NotFoundError, match="no mount"):+ await box.mount.remove(TARGET)++ # Capabilities are static for a server, so each client reads them once.+ replies["GET", "/v1/config"] = (+ 200,+ {"capabilities": {"runtime_mounts_enabled": False}},+ )+ box = await Boxlite.rest(BoxliteRestOptions(url=url)).get(BOX)+ with pytest.raises(UnsupportedError, match="runtime directory mounts"):+ await box.mount.get(TARGET)diff --git a/sdks/python/tests/test_sync_boxlite_mock.py b/sdks/python/tests/test_sync_boxlite_mock.pyindex 22d8a7822..5be47fc34 100644--- a/sdks/python/tests/test_sync_boxlite_mock.py+++ b/sdks/python/tests/test_sync_boxlite_mock.py@@ -54,9 +54,16 @@ class _NativeImages:class _NativeBoxlite:"""Stands in for the native Boxlite and records which factory made it."""- def __init__(self, options=None, made_by: str = "Boxlite(options)") -> None:+ def __init__(+ self,+ options=None,+ made_by: str = "Boxlite(options)",+ *,+ experimental_features="",+ ) -> None:self.options = optionsself.made_by = made_by+ self.experimental_features = experimental_featuresself.images = _NativeImages()@classmethod@@ -76,13 +83,15 @@ def _native_stand_in(monkeypatch):class TestFactories:- def test_the_constructor_wraps_a_runtime_built_from_its_options(self):+ @pytest.mark.parametrize("features", ["", "native-vmm,custom-kernel"])+ def test_the_constructor_wraps_a_runtime_built_from_its_options(self, features):options = object()- runtime = SyncBoxlite(options)+ runtime = SyncBoxlite(options, experimental_features=features)assert runtime.runtime.made_by == "Boxlite(options)"assert runtime.runtime.options is options+ assert runtime.runtime.experimental_features == featuresdef test_rest_wraps_the_runtime_boxlite_rest_made(self):options = object()diff --git a/src/boxlite/src/db/boxes.rs b/src/boxlite/src/db/boxes.rsindex 1036be384..593b63c36 100644--- a/src/boxlite/src/db/boxes.rs+++ b/src/boxlite/src/db/boxes.rs@@ -493,7 +493,7 @@ mod tests {for (client, target) in [(&store, "/work"), (&other, "/second")] {client.update_mounts(TEST_ID_1, |mounts| {- mounts.declare(crate::MountRequest {+ mounts.declare(crate::MountOptions {source: "/srv/data".into(),target: target.into(),read_only: true,@@ -566,7 +566,7 @@ mod tests {reopened.update_mounts(TEST_ID_1, |mounts| {mounts.forget("/work");- mounts.declare(crate::MountRequest {+ mounts.declare(crate::MountOptions {source: "/srv/data".into(),target: "/late".into(),read_only: false,diff --git a/src/boxlite/src/db/boxes/mounts.rs b/src/boxlite/src/db/boxes/mounts.rsindex 16d8922dd..e0283087d 100644--- a/src/boxlite/src/db/boxes/mounts.rs+++ b/src/boxlite/src/db/boxes/mounts.rs@@ -20,7 +20,7 @@ use std::fmt::Display;use super::BoxStore;use crate::db::db_err;-use crate::litebox::mounts::{MountInfo, MountProgress, MountRequest, MountState};+use crate::litebox::mounts::{MountInfo, MountOptions, MountProgress, MountState};use crate::runtime::advanced_options::AdvancedBoxOptions;use crate::runtime::options::{BoxOptions, MountSpec, MountType, VolumeSpec};use crate::runtime::types::BoxState;@@ -31,7 +31,7 @@ use crate::volumes::{ContainerMount, ContainerMountPayload};struct Saved {/// Added directories, and `None` where a directory was removed.#[serde(default)]- changes: BTreeMap<String, Option<MountRequest>>,+ changes: BTreeMap<String, Option<MountOptions>>,/// The progress of the run that last wrote one. No other run shows it.#[serde(default, skip_serializing_if = "Option::is_none")]run: Option<Run>,@@ -52,20 +52,20 @@ pub(crate) struct Mounts {pub state: BoxState,/// The directories the box boots with, by normalized target: the ones it/// was created with, with every committed change applied.- pub declarations: BTreeMap<String, MountRequest>,+ pub declarations: BTreeMap<String, MountOptions>,/// Last committed progress of the current VM run, by target.pub progress: BTreeMap<String, MountProgress>,/// Creation targets that are no directory declaration: files and managed volumes.pub(crate) unmanaged: BTreeSet<String>,/// Creation targets whose source is a file: no directory can sit below one.pub(crate) files: BTreeSet<String>,- changes: BTreeMap<String, Option<MountRequest>>,+ changes: BTreeMap<String, Option<MountOptions>>,}/// The mounts of the creation formats, split by what their sources are on the/// host.struct Creation {- directories: BTreeMap<String, MountRequest>,+ directories: BTreeMap<String, MountOptions>,unmanaged: BTreeSet<String>,files: BTreeSet<String>,}@@ -140,7 +140,7 @@ impl Creation {} else {this.directories.insert(key.clone(),- MountRequest {+ MountOptions {source: source.into(),target: key.into(),read_only,@@ -228,7 +228,7 @@ impl Mounts {/// Record what a change did to the target: a directory is declared there,/// or the target is free again, whatever its source is now.- fn apply(&mut self, target: &str, change: Option<MountRequest>) {+ fn apply(&mut self, target: &str, change: Option<MountOptions>) {self.changes.insert(target.to_owned(), change.clone());match change {Some(request) => {@@ -243,7 +243,7 @@ impl Mounts {}/// Save a declaration for the next start.- pub(crate) fn declare(&mut self, request: MountRequest) {+ pub(crate) fn declare(&mut self, request: MountOptions) {let target = request.target.to_string_lossy().into_owned();self.apply(&target, Some(request));}@@ -384,7 +384,7 @@ impl Mounts {/// A start cannot use a declared directory. The target leads the message: it/// is what the caller can query, and remove, while the box is stopped.-fn undeliverable(request: &MountRequest, cause: impl Display) -> BoxliteError {+fn undeliverable(request: &MountOptions, cause: impl Display) -> BoxliteError {BoxliteError::InvalidState(format!("cannot deliver the directory declared at {}: source {} {cause}",request.target.display(),diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rsindex 13cca05a1..01dd5df52 100644--- a/src/boxlite/src/lib.rs+++ b/src/boxlite/src/lib.rs@@ -60,7 +60,7 @@ pub use litebox::snapshot_mgr::SnapshotInfo;pub use litebox::{AttachOptions, BoxCommand, CopyOptions, ExecResult, ExecStderr, ExecStdin, ExecStdout,Execution, ExecutionId, ExecutionInfo, ExecutionsHandle, HealthState, HealthStatus,- MountHandle, MountInfo, MountRequest, MountState, SyncExecResult, collect_sync_execution,+ MountHandle, MountInfo, MountOptions, MountState, SyncExecResult, collect_sync_execution,validate_sync_exec,};pub use litebox::{diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rsindex 25d144c38..9deae5b2c 100644--- a/src/boxlite/src/litebox/box_impl.rs+++ b/src/boxlite/src/litebox/box_impl.rs@@ -1868,9 +1868,9 @@ impl crate::runtime::backend::BoxBackend for BoxImpl {#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]async fn mount_add(&self,- request: crate::litebox::mounts::MountRequest,+ options: crate::litebox::mounts::MountOptions,) -> BoxliteResult<crate::litebox::mounts::MountInfo> {- BoxImpl::mount_add(self, request).await+ BoxImpl::mount_add(self, options).await}#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]diff --git a/src/boxlite/src/litebox/box_impl/mounts.rs b/src/boxlite/src/litebox/box_impl/mounts.rsindex f08b7d05d..494f9c23d 100644--- a/src/boxlite/src/litebox/box_impl/mounts.rs+++ b/src/boxlite/src/litebox/box_impl/mounts.rs@@ -23,7 +23,7 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};use super::{BoxImpl, BoxRun};use crate::db::{BoxStore, Mounts};use crate::experimental::ExperimentalFeature;-use crate::litebox::mounts::{MountInfo, MountProgress, MountRequest, MountState, target_key};+use crate::litebox::mounts::{MountInfo, MountOptions, MountProgress, MountState, target_key};use crate::lock::OwnedLockGuard;use crate::portal::interfaces::ContainerInterface;use crate::runtime::id::BoxID;@@ -236,8 +236,8 @@ struct CheckedRequest {impl CheckedRequest {/// The request to keep as a declaration and as progress.- fn request(&self) -> MountRequest {- MountRequest {+ fn request(&self) -> MountOptions {+ MountOptions {source: PathBuf::from(&self.source),target: PathBuf::from(&self.target),read_only: self.read_only,@@ -252,7 +252,7 @@ impl CheckedRequest {/// Validate a request. Invalid input stops here, before any descriptor, record/// or declaration exists.-fn checked_request(request: &MountRequest) -> BoxliteResult<CheckedRequest> {+fn checked_request(request: &MountOptions) -> BoxliteResult<CheckedRequest> {if !request.source.is_absolute() {return Err(BoxliteError::InvalidArgument(format!("source must be an absolute host path: {:?}",@@ -451,10 +451,10 @@ impl BoxImpl {/// Deliver a host directory into the container, or save it for the next/// start of a stopped box.- pub(crate) async fn mount_add(&self, request: MountRequest) -> BoxliteResult<MountInfo> {+ pub(crate) async fn mount_add(&self, options: MountOptions) -> BoxliteResult<MountInfo> {self.require_runtime_mounts()?;self.require_aggregate_mounts()?;- let request = checked_request(&request)?;+ let request = checked_request(&options)?;// The host filesystem may sit on slow storage.let source = request.source.clone();let (directory, root) =diff --git a/src/boxlite/src/litebox/clone_export.rs b/src/boxlite/src/litebox/clone_export.rsindex 54517b2d0..92259a241 100644--- a/src/boxlite/src/litebox/clone_export.rs+++ b/src/boxlite/src/litebox/clone_export.rs@@ -383,7 +383,7 @@ fn do_export_finalize(#[cfg(all(test, feature = "native", target_os = "linux", target_arch = "x86_64"))]mod tests {- use crate::litebox::mounts::MountRequest;+ use crate::litebox::mounts::MountOptions;use crate::litebox::mounts::tests::Fixture;use crate::litebox::state::BoxStatus;use crate::runtime::options::MountSpec;@@ -407,7 +407,7 @@ mod tests {.store().update_mounts(fx.id.as_str(), |mounts| {mounts.forget("/orig");- mounts.declare(MountRequest {+ mounts.declare(MountOptions {source: added.path().into(),target: "/added".into(),read_only: true,diff --git a/src/boxlite/src/litebox/mod.rs b/src/boxlite/src/litebox/mod.rsindex 212cffd70..b27576a2b 100644--- a/src/boxlite/src/litebox/mod.rs+++ b/src/boxlite/src/litebox/mod.rs@@ -35,7 +35,7 @@ pub use exec::{};pub use executions::ExecutionsHandle;pub(crate) use manager::BoxManager;-pub use mounts::{MountHandle, MountInfo, MountRequest, MountState};+pub use mounts::{MountHandle, MountInfo, MountOptions, MountState};pub use network::{BoxConnection, BoxReader, BoxTunnel, BoxWriter, NetworkHandle, SocketAddress, TunnelForwarder,TunnelOptions,diff --git a/src/boxlite/src/litebox/mounts.rs b/src/boxlite/src/litebox/mounts.rsindex 768d96445..7160e78f2 100644--- a/src/boxlite/src/litebox/mounts.rs+++ b/src/boxlite/src/litebox/mounts.rs@@ -26,7 +26,7 @@ pub(crate) mod tests;/// A host directory and its destination in the container.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct MountRequest {+pub struct MountOptions {/// Host directory to deliver. A symbolic link is refused at open.pub source: PathBuf,/// Absolute container path below `/`, without `..`. Missing directories@@ -34,6 +34,7 @@ pub struct MountRequest {/// link, is refused.pub target: PathBuf,/// Whether the container sees the directory read-only.+ #[serde(default)]pub read_only: bool,}@@ -50,6 +51,27 @@ pub enum MountState {Detaching,}+impl fmt::Display for MountState {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(match self {+ Self::Configured => "configured",+ Self::Preparing => "preparing",+ Self::Mounted => "mounted",+ Self::Detaching => "detaching",+ })+ }+}++// SQLite retains the variant names; public mount details use lowercase states.+#[derive(Serialize, Deserialize)]+#[serde(remote = "MountState", rename_all = "snake_case")]+enum PublicMountState {+ Configured,+ Preparing,+ Mounted,+ Detaching,+}+/// A mount as callers see it. The identities the shim and the guest record stay internal.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct MountInfo {@@ -60,13 +82,14 @@ pub struct MountInfo {/// Whether the container sees the directory read-only.pub read_only: bool,/// Where the mount is in its lifecycle.+ #[serde(with = "PublicMountState")]pub state: MountState,}/// Last committed progress of one mount in one VM run.#[derive(Clone, Debug, Serialize, Deserialize)]pub(crate) struct MountProgress {- pub request: MountRequest,+ pub request: MountOptions,pub state: MountState,/// The request that owns the entry. A step of any other request leaves it alone.pub request_id: [u8; 16],@@ -77,7 +100,7 @@ pub(crate) struct MountProgress {pub delivered_at_start: bool,}-impl MountRequest {+impl MountOptions {/// The request as callers see it in `state`.pub(crate) fn info(&self, state: MountState) -> MountInfo {MountInfo {@@ -123,8 +146,8 @@ impl MountHandle {/// Save a directory declaration. A stopped box returns [`MountState::Configured`]./// A running box returns [`MountState::Mounted`] after guest confirmation and commit.- pub async fn add(&self, request: MountRequest) -> BoxliteResult<MountInfo> {- self.backend.mount_add(request).await+ pub async fn add(&self, options: MountOptions) -> BoxliteResult<MountInfo> {+ self.backend.mount_add(options).await}/// Remove the declaration at `target`. On a running box the guest detaches thediff --git a/src/boxlite/src/litebox/mounts/tests.rs b/src/boxlite/src/litebox/mounts/tests.rsindex 0980b6a82..62f2fd111 100644--- a/src/boxlite/src/litebox/mounts/tests.rs+++ b/src/boxlite/src/litebox/mounts/tests.rs@@ -18,7 +18,7 @@ use crate::runtime::rt_impl::{RuntimeImpl, SharedRuntimeImpl};use crate::runtime::types::ContainerID;use crate::vmm::VmmKind;-use super::{MountRequest, MountState};+use super::{MountOptions, MountState};const WORK: &str = "/work";@@ -101,8 +101,8 @@ impl Fixture {)}- pub(crate) fn request(&self) -> MountRequest {- MountRequest {+ pub(crate) fn request(&self) -> MountOptions {+ MountOptions {source: self.source.clone(),target: WORK.into(),read_only: false,@@ -173,7 +173,7 @@ async fn paused_unsupported_and_unsafe_changes_are_refused() {let mut fx = Fixture::new(BoxStatus::Stopped);for target in ["/", "relative", "/a/../b"] {- let request = MountRequest {+ let request = MountOptions {target: target.into(),..fx.request()};@@ -182,7 +182,7 @@ async fn paused_unsupported_and_unsafe_changes_are_refused() {Err(BoxliteError::InvalidArgument(_))));}- let request = MountRequest {+ let request = MountOptions {source: fx.source.join("missing"),..fx.request()};@@ -216,7 +216,7 @@ async fn an_added_source_is_refused_once_it_is_a_link_in_any_spelling() {let fx = Fixture::new(BoxStatus::Stopped);let real = fx._home.path().join("real");std::fs::create_dir(&real).unwrap();- let request = MountRequest {+ let request = MountOptions {source: PathBuf::from(format!("{}{slash}", fx.source.display())),..fx.request()};@@ -242,7 +242,7 @@ async fn a_source_that_overlaps_a_delivered_directory_is_refused() {for directory in [&parent, &child, &sibling] {std::fs::create_dir_all(directory).unwrap();}- let add = |source: &Path, target: &str| MountRequest {+ let add = |source: &Path, target: &str| MountOptions {source: source.into(),target: target.into(),read_only: false,@@ -278,7 +278,7 @@ async fn a_target_at_or_around_the_containers_own_mounts_is_refused() {let bx = fx.handle();// The target is normalized first; the full matrix lives with the shared helper.for target in ["/dev/", "/tmp/work"] {- let request = MountRequest {+ let request = MountOptions {target: target.into(),..fx.request()};@@ -290,7 +290,7 @@ async fn a_target_at_or_around_the_containers_own_mounts_is_refused() {}// A path that only shares the spelling is another directory.- let beside = MountRequest {+ let beside = MountOptions {target: "/tmpwork".into(),..fx.request()};@@ -313,7 +313,7 @@ async fn a_target_with_a_mount_below_it_is_refused() {);let bx = fx.handle();// Applied after the box's own mounts, the directory would cover this one.- let request = MountRequest {+ let request = MountOptions {target: "/work".into(),..fx.request()};@@ -325,7 +325,7 @@ async fn a_target_with_a_mount_below_it_is_refused() {assert_eq!(bx.mount_get(Path::new("/work")).await.unwrap(), None);// Below that mount, nothing is covered.- let request = MountRequest {+ let request = MountOptions {target: "/work/inner/deeper".into(),..fx.request()};@@ -347,7 +347,7 @@ async fn a_target_below_a_file_the_box_was_created_with_is_refused() {let bx = fx.handle();// The file's mount leaves no path to mount a directory at.for target in ["/config/cache", "/config/deeper/still"] {- let request = MountRequest {+ let request = MountOptions {target: target.into(),..fx.request()};@@ -360,7 +360,7 @@ async fn a_target_below_a_file_the_box_was_created_with_is_refused() {}// A path that only shares the spelling is another directory.- let request = MountRequest {+ let request = MountOptions {target: "/config-cache".into(),..fx.request()};diff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rsindex 030536a80..4e5b7af51 100644--- a/src/boxlite/src/rest/client.rs+++ b/src/boxlite/src/rest/client.rs@@ -926,6 +926,19 @@ impl ApiClient {ensure_capability("import", capabilities.import_enabled)}+ pub async fn require_runtime_mounts_enabled(&self) -> BoxliteResult<()> {+ let config = self.get_config().await?;+ let capabilities = config.capabilities.ok_or_else(|| {+ BoxliteError::Unsupported(+ "Remote server did not advertise runtime directory mounts capability".to_string(),+ )+ })?;+ ensure_capability(+ "runtime directory mounts",+ capabilities.runtime_mounts_enabled,+ )+ }+/// POST binary data with query params, parse JSON response.pub async fn post_bytes_for_json<T: DeserializeOwned>(&self,diff --git a/src/boxlite/src/rest/litebox.rs b/src/boxlite/src/rest/litebox.rsindex 4f4f87932..e449db5c3 100644--- a/src/boxlite/src/rest/litebox.rs+++ b/src/boxlite/src/rest/litebox.rs@@ -20,7 +20,8 @@ use crate::litebox::copy::CopyOptions;use crate::litebox::snapshot_mgr::SnapshotInfo;use crate::litebox::{AttachOptions, BoxCommand, BoxConnection, BoxTunnel, ExecResult, ExecStderr, ExecStdin,- ExecStdout, Execution, SshConfig, SshStatus, SyncExecResult, TunnelOptions,+ ExecStdout, Execution, MountInfo, MountOptions, SshConfig, SshStatus, SyncExecResult,+ TunnelOptions,};use crate::metrics::BoxMetrics;use crate::runtime::backend::{BoxBackend, BoxNetworkBackend, SnapshotBackend};@@ -34,8 +35,8 @@ use super::error::map_http_body;use super::exec::RestExecControl;use super::types::{BoxMetricsResponse, BoxResponse, CloneBoxRequest, CreateSnapshotRequest, ExecRequest,- ExecResponse, ExecutionStatusResponse, ExportBoxRequest, ListSnapshotsResponse,- SnapshotResponse,+ ExecResponse, ExecutionStatusResponse, ExportBoxRequest, ListMountsResponse,+ ListSnapshotsResponse, SnapshotResponse,};/// REST-backed box handle.@@ -724,6 +725,44 @@ impl BoxBackend for RestBox {Ok(crate::runtime::options::BoxArchive::new(output_path))}+ async fn mount_add(&self, options: MountOptions) -> BoxliteResult<MountInfo> {+ self.client.require_runtime_mounts_enabled().await?;+ mount_path(&options.source, "source")?;+ mount_path(&options.target, "target")?;+ self.client+ .post(&format!("/boxes/{}/mounts", self.id), &options)+ .await+ }++ async fn mount_remove(&self, target: &Path) -> BoxliteResult<()> {+ self.client.require_runtime_mounts_enabled().await?;+ self.client+ .delete_with_query(+ &format!("/boxes/{}/mounts/by-target", self.id),+ &[("target", mount_path(target, "target")?)],+ )+ .await+ }++ async fn mount_list(&self) -> BoxliteResult<Vec<MountInfo>> {+ self.client.require_runtime_mounts_enabled().await?;+ let response: ListMountsResponse = self+ .client+ .get(&format!("/boxes/{}/mounts", self.id))+ .await?;+ Ok(response.mounts)+ }++ async fn mount_get(&self, target: &Path) -> BoxliteResult<Option<MountInfo>> {+ self.client.require_runtime_mounts_enabled().await?;+ self.client+ .get_with_query(+ &format!("/boxes/{}/mounts/by-target", self.id),+ &[("target", mount_path(target, "target")?)],+ )+ .await+ }+async fn ssh_configure(&self, config: SshConfig) -> BoxliteResult<SshStatus> {// One request per call: the guest restarts SSH on every configure.let request = SshConfigRequest::new(&config);@@ -751,6 +790,11 @@ impl BoxBackend for RestBox {}}+fn mount_path<'a>(path: &'a Path, field: &str) -> BoxliteResult<&'a str> {+ path.to_str()+ .ok_or_else(|| BoxliteError::InvalidArgument(format!("mount {field} must be UTF-8")))+}+#[async_trait]impl BoxNetworkBackend for RestBox {async fn update_inbound(&self, config: InboundNetworkConfig) -> BoxliteResult<()> {diff --git a/src/boxlite/src/rest/runtime.rs b/src/boxlite/src/rest/runtime.rsindex 878e3d709..3087b9de6 100644--- a/src/boxlite/src/rest/runtime.rs+++ b/src/boxlite/src/rest/runtime.rs@@ -698,6 +698,8 @@ mod tests {use super::*;use crate::runtime::options::{PortProtocol, PortSpec};+ mod runtime_mounts;+#[test]fn remote_runtime_rejects_host_port_publication_with_tunnel_guidance() {let options = BoxOptions {diff --git a/src/boxlite/src/rest/runtime/tests/runtime_mounts.rs b/src/boxlite/src/rest/runtime/tests/runtime_mounts.rsnew file mode 100644index 000000000..ae7d4711f--- /dev/null+++ b/src/boxlite/src/rest/runtime/tests/runtime_mounts.rs@@ -0,0 +1,123 @@+use std::time::Duration;++use super::*;+use crate::{MountOptions, MountState};+use serde_json::{Value, json};++#[test]+fn mount_state_keeps_pr3_storage_and_public_json_compatible() {+ for (stored, public) in [+ ("Mounted", "mounted"),+ ("Preparing", "preparing"),+ ("Detaching", "detaching"),+ ("Configured", "configured"),+ ] {+ let state: MountState = serde_json::from_value(json!(stored)).unwrap();+ let body =+ json!({"source": "/srv/data", "target": "/work", "read_only": true, "state": public});+ let info: crate::MountInfo = serde_json::from_value(body.clone()).unwrap();+ assert_eq!(info.state, state);+ assert_eq!(serde_json::to_value(&info).unwrap(), body);+ assert_eq!(serde_json::to_value(state).unwrap(), stored);+ assert_eq!(state.to_string(), public);+ }+ let request: MountOptions = serde_json::from_value(json!({+ "source": "/srv/data", "target": "/work",+ }))+ .unwrap();+ assert!(!request.read_only);+}++#[tokio::test]+async fn rest_runtime_mounts_preserve_paths_and_three_distinct_outcomes() {+ let config = r#"{"capabilities":{"runtime_mounts_enabled":true}}"#;+ let mounted =+ r#"{"source":"/host/data","target":"/mount a&b","read_only":true,"state":"mounted"}"#;+ let list = r#"{"mounts":[{"source":"/host/data","target":"/mount a&b","read_only":true,"state":"mounted"}]}"#;+ let collection = "/v1/boxes/01HJK4TNRPQSXYZ8WM6NCVT9R5/mounts";+ let detail = format!("{collection}/by-target?target=%2Fmount+a%26b");+ let operations = [+ ("POST", collection, 201, mounted),+ ("GET", collection, 200, list),+ ("GET", &detail, 200, mounted),+ ("DELETE", &detail, 204, ""),+ ("GET", &detail, 200, "null"),+ (+ "GET",+ &detail,+ 404,+ r#"{"error":{"code":"not_found","message":"box missing"}}"#,+ ),+ ];+ let mut replies = vec![(200, BOX_RESPONSE), (200, config)];+ for (_, _, status, body) in operations {+ replies.push((status, body));+ }+ let (port, server) = exchange_server(replies).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let target = "/mount a&b";+ let requests = tokio::time::timeout(Duration::from_secs(10), async {+ let mounts = runtime.get("named").await.unwrap().unwrap().mount();+ let request = MountOptions {+ source: "/host/data".into(),+ target: target.into(),+ read_only: true,+ };+ let added = mounts.add(request).await.unwrap();+ assert_eq!(added.state, MountState::Mounted);+ assert_eq!(+ mounts.list().await.unwrap().as_slice(),+ std::slice::from_ref(&added)+ );+ assert_eq!(mounts.get(target).await.unwrap(), Some(added));+ mounts.remove(target).await.unwrap();+ assert_eq!(mounts.get(target).await.unwrap(), None);+ assert!(matches!(+ mounts.get(target).await,+ Err(BoxliteError::NotFound(_))+ ));+ server.await.unwrap()+ })+ .await+ .unwrap();+ let mut requests = requests.into_iter();+ assert_eq!(requests.next().unwrap().0, "GET /v1/boxes/named HTTP/1.1");+ // A server's capabilities are static, so the client reads them once.+ assert_eq!(requests.next().unwrap().0, "GET /v1/config HTTP/1.1");+ for (method, path, _, _) in operations {+ let (line, body) = requests.next().unwrap();+ assert_eq!(line, format!("{method} {path} HTTP/1.1"));+ if method == "POST" {+ assert_eq!(+ serde_json::from_str::<Value>(&body).unwrap(),+ json!({+ "source": "/host/data", "target": target, "read_only": true,+ })+ );+ }+ }+ assert_eq!(requests.next(), None);+}++#[tokio::test]+async fn rest_runtime_mounts_refuse_a_server_without_the_capability() {+ let (port, server) =+ exchange_server(vec![(200, BOX_RESPONSE), (200, r#"{"capabilities":{}}"#)]).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let result = tokio::time::timeout(Duration::from_secs(10), async {+ runtime+ .get("named")+ .await+ .unwrap()+ .unwrap()+ .mount()+ .list()+ .await+ })+ .await+ .unwrap();+ assert!(matches!(result, Err(BoxliteError::Unsupported(_))));+ server.await.unwrap();+}diff --git a/src/boxlite/src/rest/types.rs b/src/boxlite/src/rest/types.rsindex ba6bdbd87..a0c290a98 100644--- a/src/boxlite/src/rest/types.rs+++ b/src/boxlite/src/rest/types.rs@@ -110,6 +110,12 @@ pub(crate) struct ServerCapabilities {pub sync_exec_enabled: Option<bool>,pub volume_read_only_enabled: Option<bool>,pub typed_mounts_enabled: Option<bool>,+ pub runtime_mounts_enabled: Option<bool>,+}++#[derive(Debug, Deserialize)]+pub(crate) struct ListMountsResponse {+ pub mounts: Vec<crate::MountInfo>,}// ============================================================================diff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rsindex 206c17168..ae5dac719 100644--- a/src/boxlite/src/runtime/backend.rs+++ b/src/boxlite/src/runtime/backend.rs@@ -10,7 +10,7 @@ use async_trait::async_trait;use crate::litebox::copy::CopyOptions;use crate::litebox::snapshot_mgr::SnapshotInfo;use crate::litebox::{- AttachOptions, BoxCommand, BoxTunnel, Execution, LiteBox, MountInfo, MountRequest, SshConfig,+ AttachOptions, BoxCommand, BoxTunnel, Execution, LiteBox, MountInfo, MountOptions, SshConfig,SshStatus, SyncExecResult,};use crate::metrics::{BoxMetrics, RuntimeMetrics};@@ -147,7 +147,7 @@ pub(crate) trait BoxBackend: Send + Sync + Any {}/// Save a directory declaration and deliver it if the box is running.- async fn mount_add(&self, _request: MountRequest) -> BoxliteResult<MountInfo> {+ async fn mount_add(&self, _options: MountOptions) -> BoxliteResult<MountInfo> {Err(unsupported_mounts())}diff --git a/src/boxlite/tests/runtime_mounts.rs b/src/boxlite/tests/runtime_mounts.rsindex a082d2859..cfabb1a01 100644--- a/src/boxlite/tests/runtime_mounts.rs+++ b/src/boxlite/tests/runtime_mounts.rs@@ -7,7 +7,7 @@ mod common;use boxlite::runtime::options::{BoxOptions, BoxliteOptions, MountSpec, NetworkSpec, VolumeSpec};use boxlite::{- BoxCommand, BoxStatus, BoxliteError, Execution, LiteBox, MountInfo, MountRequest, MountState,+ BoxCommand, BoxStatus, BoxliteError, Execution, LiteBox, MountInfo, MountOptions, MountState,};use common::home::PerTestBoxHome;use futures::{FutureExt, StreamExt};@@ -22,8 +22,8 @@ fn source(probe: &str) -> tempfile::TempDir {dir}-fn request(source: &Path, target: &str, read_only: bool) -> MountRequest {- MountRequest {+fn request(source: &Path, target: &str, read_only: bool) -> MountOptions {+ MountOptions {source: source.into(),target: target.into(),read_only,diff --git a/src/cli/Cargo.toml b/src/cli/Cargo.tomlindex 087f9d7c8..2d81b1178 100644--- a/src/cli/Cargo.toml+++ b/src/cli/Cargo.toml@@ -86,6 +86,9 @@ gtmpl = "0.7"gtmpl_value = "0.5"[build-dependencies]+[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]+boxlite = { workspace = true, features = ["native"] }+[dev-dependencies]boxlite = { workspace = true, features = ["rest", "test-support"] }boxlite-test-utils = { path = "../test-utils" }diff --git a/src/cli/README.md b/src/cli/README.mdindex cb2237609..341af62c1 100644--- a/src/cli/README.md+++ b/src/cli/README.md@@ -322,6 +322,24 @@ Inbound accepts no list; disabled outbound accepts no `--allow-net`. Each commanone direction without retaining earlier rules. See [networking](../../docs/guides/networking.md#updating-a-running-box)for runtime support, connection lifetime and persistence.+### Runtime directory mounts (release candidate)++Manage host directory mounts on a Linux x86_64 native Box. Enable `native-vmm`+for mounts and `custom-kernel` when reopening a Box that uses a custom kernel:++```bash+export BOXLITE_EXPERIMENTAL=native-vmm,custom-kernel+boxlite mount add dev --source /srv/projects/demo --box-path /workspace --read-only+boxlite mount ls dev+boxlite mount inspect dev --box-path /workspace --format json+boxlite mount rm dev --box-path /workspace+```++None of these commands starts a stopped Box, and `mount` appears in help only with+`native-vmm` enabled. With `--url`, `--source` names a directory on the server host.+See the [CLI reference](../../docs/reference/cli/README.md#boxlite-mount) for flags,+mount states and errors.+### Guest SSH```bashdiff --git a/src/cli/src/cli.rs b/src/cli/src/cli.rsindex d29548f1f..705a18153 100644--- a/src/cli/src/cli.rs+++ b/src/cli/src/cli.rs@@ -265,6 +265,13 @@ const fn box_command_scope(name: &'static str, children: &'static [CommandScope]}}+const MOUNT_SCOPES: &[CommandScope] = &[+ box_command_scope("add", &[]),+ box_command_scope("rm", &[]),+ box_command_scope("ls", &[]),+ box_command_scope("inspect", &[]),+];+const AGENT_SCOPES: &[CommandScope] = &[box_command_scope("create", &[]),box_command_scope("close", &[]),@@ -429,6 +436,7 @@ const COMMAND_SCOPES: &[CommandScope] = &[globals: BOX_GLOBALS,children: NETWORK_SCOPES,},+ box_command_scope("mount", MOUNT_SCOPES),CommandScope {name: "ssh",globals: BOX_GLOBALS,@@ -477,7 +485,9 @@ const COMMAND_SCOPES: &[CommandScope] = &[/// are folded explicitly because propagation selects one level's `MatchedArg`/// rather than appending values from independently defined levels.pub fn command() -> Command {- let command = Cli::command();+ let mounts_enabled = experimental_features_from_env()+ .is_ok_and(|features| features.is_enabled(ExperimentalFeature::NativeVmm));+ let command = Cli::command().mut_subcommand("mount", |command| command.hide(!mounts_enabled));let global_args = command.get_arguments().filter(|argument| argument.is_global_set())@@ -868,6 +878,10 @@ pub enum Commands {/// Manage box networkingNetwork(crate::commands::network::NetworkArgs),+ /// Manage runtime directory mounts+ #[command(hide = true)]+ Mount(crate::commands::mount::MountArgs),+/// Connect to guest SSH using system OpenSSH////// With no operation option, generate or reuse CLI-managed client and host keys,@@ -989,18 +1003,18 @@ end"}fn completion_command() -> Command {- // clap_complete's AOT generators enumerate hidden arguments. Runtime,- // help, and scoped globals already share `command()`; this final projection- // removes only experimental arguments from completion discovery.- command()+ // AOT generators enumerate hidden arguments and commands.+ let command = command().mut_subcommand("run", without_hidden_arguments)- .mut_subcommand("create", without_hidden_arguments)+ .mut_subcommand("create", without_hidden_arguments);+ without_hidden_arguments(command).version(env!("CARGO_PKG_VERSION"))}fn without_hidden_arguments(command: Command) -> Command {let name = match command.get_name() {"run" => "run","create" => "create",+ "boxlite" => "boxlite",other => panic!("completion projection is not defined for {other}"),};let about = command.get_about().cloned();@@ -1011,7 +1025,11 @@ fn without_hidden_arguments(command: Command) -> Command {.filter(|argument| !argument.is_hide_set()).cloned().collect::<Vec<_>>();- let subcommands = command.get_subcommands().cloned().collect::<Vec<_>>();+ let subcommands = command+ .get_subcommands()+ .filter(|child| child.get_name() != "mount" || !child.is_hide_set())+ .cloned()+ .collect::<Vec<_>>();let mut projected = Command::new(name).display_order(display_order)diff --git a/src/cli/src/commands/mod.rs b/src/cli/src/commands/mod.rsindex 56f9a5909..0be702222 100644--- a/src/cli/src/commands/mod.rs+++ b/src/cli/src/commands/mod.rs@@ -16,6 +16,7 @@ pub mod inspect;pub mod kill;pub mod list;pub mod logs;+pub mod mount;pub mod network;pub mod pull;pub mod restart;diff --git a/src/cli/src/commands/mount.rs b/src/cli/src/commands/mount.rsnew file mode 100644index 000000000..05349cf14--- /dev/null+++ b/src/cli/src/commands/mount.rs@@ -0,0 +1,194 @@+use std::io::Write;+use std::path::PathBuf;++use boxlite::{BoxliteError, MountInfo, MountOptions, experimental::ExperimentalFeature};+use clap::{Args, Subcommand};+use tabled::Tabled;++use crate::cli::GlobalFlags;+use crate::formatter::{self, OutputFormat};++#[derive(Args, Debug)]+pub struct MountArgs {+ #[command(subcommand)]+ command: MountCommand,+}++#[derive(Subcommand, Debug)]+enum MountCommand {+ /// Add a host directory to a box+ ///+ /// A running box mounts the directory after guest confirmation. A stopped+ /// box stays stopped and saves a `configured` declaration for its next start.+ Add {+ /// Box ID or name+ #[arg(value_name = "BOX")]+ box_id: String,+ /// Host directory to deliver+ ///+ /// It must exist when added and whenever the box starts. With `--url`,+ /// this is a directory on the server host.+ #[arg(long, value_name = "HOST_DIR")]+ source: PathBuf,+ /// Absolute container path to mount the directory at+ #[arg(long, value_name = "CONTAINER_PATH")]+ box_path: PathBuf,+ /// Deny writes from the box+ #[arg(long)]+ read_only: bool,+ },+ /// Remove the directory mounted at a container path+ ///+ /// A running box detaches it lazily, preserving open files. A stopped box+ /// only drops the declaration; later starts do not deliver it again.+ Rm {+ /// Box ID or name+ #[arg(value_name = "BOX")]+ box_id: String,+ /// Container path of the mount to remove+ #[arg(long, value_name = "CONTAINER_PATH")]+ box_path: PathBuf,+ },+ /// List the directory mounts of a box+ ///+ /// `configured` is saved for the next start. `preparing`, `mounted` and+ /// `detaching` are the last committed progress of the current run;+ /// `mounted` means the guest confirmed the mount. Does not start the box.+ Ls {+ /// Box ID or name+ #[arg(value_name = "BOX")]+ box_id: String,+ #[arg(long, value_enum, default_value = "table")]+ format: OutputFormat,+ },+ /// Show the directory mounted at a container path+ ///+ /// A target without a mount prints `null` as JSON. A stopped box reports+ /// the declaration of its next start and is not started.+ Inspect {+ /// Box ID or name+ #[arg(value_name = "BOX")]+ box_id: String,+ /// Container path of the mount to show+ #[arg(long, value_name = "CONTAINER_PATH")]+ box_path: PathBuf,+ #[arg(long, value_enum, default_value = "table")]+ format: OutputFormat,+ },+}++#[derive(Tabled)]+struct MountRow<'a> {+ #[tabled(rename = "SOURCE")]+ source: std::path::Display<'a>,+ #[tabled(rename = "TARGET")]+ target: std::path::Display<'a>,+ #[tabled(rename = "MODE")]+ mode: &'static str,+ #[tabled(rename = "STATE")]+ state: boxlite::MountState,+}++impl<'a> From<&'a MountInfo> for MountRow<'a> {+ fn from(info: &'a MountInfo) -> Self {+ Self {+ source: info.source.display(),+ target: info.target.display(),+ mode: if info.read_only { "ro" } else { "rw" },+ state: info.state,+ }+ }+}++fn print_mounts<'a, T>(value: &'a T, format: OutputFormat) -> anyhow::Result<()>+where+ T: serde::Serialize,+ &'a T: IntoIterator<Item = &'a MountInfo>,+{+ formatter::print_output(&mut std::io::stdout().lock(), value, format, |writer, _| {+ let table = formatter::create_table(value.into_iter().map(MountRow::from));+ writeln!(writer, "{table}")?;+ Ok(())+ })+}++pub async fn execute(args: MountArgs, global: &GlobalFlags) -> anyhow::Result<()> {+ global+ .experimental_features()+ .require(ExperimentalFeature::NativeVmm)?;+ let box_id = match &args.command {+ MountCommand::Add { box_id, .. }+ | MountCommand::Rm { box_id, .. }+ | MountCommand::Ls { box_id, .. }+ | MountCommand::Inspect { box_id, .. } => box_id,+ };+ let runtime = global.create_runtime()?;+ let handle = runtime+ .get(box_id)+ .await?+ .ok_or_else(|| BoxliteError::NotFound(format!("box {box_id}")))?;+ let mount = handle.mount();+ match args.command {+ MountCommand::Add {+ source,+ box_path,+ read_only,+ ..+ } => {+ let info = mount+ .add(MountOptions {+ source,+ target: box_path,+ read_only,+ })+ .await?;+ print_mounts(&Some(info), OutputFormat::Table)+ }+ MountCommand::Rm { box_path, .. } => Ok(mount.remove(box_path).await?),+ MountCommand::Ls { format, .. } => print_mounts(&mount.list().await?, format),+ MountCommand::Inspect {+ box_path, format, ..+ } => print_mounts(&mount.get(box_path).await?, format),+ }+}++#[cfg(test)]+mod tests {+ use assert_cmd::Command;+ use predicates::prelude::PredicateBooleanExt;+ use predicates::str::contains;++ #[test]+ fn runtime_mount_command_is_hidden_until_opted_in() {+ let cli = crate::ssh_cloud_fixture::cli_executable();+ Command::new(&cli)+ .env_remove("BOXLITE_EXPERIMENTAL")+ .arg("--help")+ .assert()+ .success()+ .stdout(contains("runtime directory mounts").not());+ Command::new(&cli)+ .env_remove("BOXLITE_EXPERIMENTAL")+ .args(["mount", "ls", "box"])+ .assert()+ .failure()+ .stderr(contains("BOXLITE_EXPERIMENTAL=native-vmm"));+ Command::new(&cli)+ .env("BOXLITE_EXPERIMENTAL", "native-vmm")+ .arg("--help")+ .assert()+ .success()+ .stdout(contains("runtime directory mounts"));+ for (features, visible) in [(None, false), (Some("native-vmm"), true)] {+ let mut command = Command::new(&cli);+ match features {+ Some(value) => command.env("BOXLITE_EXPERIMENTAL", value),+ None => command.env_remove("BOXLITE_EXPERIMENTAL"),+ };+ let output = command.args(["completion", "bash"]).output().unwrap();+ assert!(output.status.success());+ let completion = String::from_utf8(output.stdout).unwrap();+ assert_eq!(completion.contains("boxlite,mount)"), visible);+ }+ }+}diff --git a/src/cli/src/commands/serve/README.md b/src/cli/src/commands/serve/README.mdindex 44e031581..c0992e5b6 100644--- a/src/cli/src/commands/serve/README.md+++ b/src/cli/src/commands/serve/README.md@@ -184,6 +184,33 @@ Without a key the console opens directly, like the API itself.| POST | `/v1/boxes/{box_id}/start` | `boxes::start_box` | Start a stopped box || POST | `/v1/boxes/{box_id}/stop` | `boxes::stop_box` | Stop a running box |+### Runtime directory mounts++On Linux x86_64, enable `BOXLITE_EXPERIMENTAL=native-vmm`:++```sh+BOXLITE_EXPERIMENTAL=native-vmm boxlite serve+```++| Method | Path under `/v1/boxes/{box_id}` | Result |+| --- | --- | --- |+| POST | `/mounts` | `201` with mount details |+| GET | `/mounts` | `200 {"mounts": [...]}` |+| GET | `/mounts/by-target?target=...` | `200` with details or `null` |+| DELETE | `/mounts/by-target?target=...` | `204`; an absent target is `404` |++POST accepts `source`, `target`, and optional `read_only` (default `false`); for example,+`{"source":"/srv/projects/demo","target":"/workspace","read_only":true}`.+All routes use the server's authentication and browser guard, never start a box, and+answer `unsupported` until the feature is enabled. `GET /v1/config` then advertises+`runtime_mounts_enabled`. A missing box returns `404`; a malformed body or target+returns `400`. Mount states and lazy removal follow the [CLI contract](../../../../../docs/reference/cli/README.md#boxlite-mount).++The server passes the supplied host path to `MountHandle`, so callers must be trusted to+choose host directories readable by the server process. Saved declarations reopen their+source on each start; a missing source reports its container target. A cancelled wait does+not undo an accepted change.+### Guest SSH| Method | Path | Handler | Description |diff --git a/src/cli/src/commands/serve/handlers/config.rs b/src/cli/src/commands/serve/handlers/config.rsindex bfe75fb73..dbba4319d 100644--- a/src/cli/src/commands/serve/handlers/config.rs+++ b/src/cli/src/commands/serve/handlers/config.rs@@ -1,10 +1,14 @@//! Configuration discovery endpoint.-use axum::Json;+use axum::{Extension, Json};++use boxlite::experimental::ExperimentalFeatures;use super::super::types::{ServerCapabilities, ServerConfig};-pub(in crate::commands::serve) async fn get_config() -> Json<ServerConfig> {+pub(in crate::commands::serve) async fn get_config(+ features: Option<Extension<ExperimentalFeatures>>,+) -> Json<ServerConfig> {Json(ServerConfig {capabilities: ServerCapabilities {checkpoints_enabled: false,@@ -19,6 +23,8 @@ pub(in crate::commands::serve) async fn get_config() -> Json<ServerConfig> {sync_exec_enabled: true,volume_read_only_enabled: true,typed_mounts_enabled: true,+ runtime_mounts_enabled: features+ .is_some_and(|features| super::mounts::enabled(&features.0)),},})}@@ -31,18 +37,19 @@ mod tests {/// supports the field must advertise it, or clients refuse to send users.#[tokio::test]async fn config_advertises_exec_user() {- assert!(get_config().await.0.capabilities.exec_user_enabled);+ assert!(get_config(None).await.0.capabilities.exec_user_enabled);}#[tokio::test]async fn config_does_not_advertise_local_checkpoints() {- assert!(!get_config().await.0.capabilities.checkpoints_enabled);- assert!(!get_config().await.0.capabilities.memory_checkpoints_enabled);+ let capabilities = get_config(None).await.0.capabilities;+ assert!(!capabilities.checkpoints_enabled);+ assert!(!capabilities.memory_checkpoints_enabled);}#[tokio::test]async fn config_advertises_volume_mount_support() {- let capabilities = get_config().await.0.capabilities;+ let capabilities = get_config(None).await.0.capabilities;assert!(capabilities.volume_read_only_enabled);assert!(capabilities.typed_mounts_enabled);}diff --git a/src/cli/src/commands/serve/handlers/mod.rs b/src/cli/src/commands/serve/handlers/mod.rsindex 78b32604b..9e3a4087d 100644--- a/src/cli/src/commands/serve/handlers/mod.rs+++ b/src/cli/src/commands/serve/handlers/mod.rs@@ -6,6 +6,7 @@ pub(super) mod files;pub(super) mod images;pub(super) mod me;pub(super) mod metrics;+pub(super) mod mounts;pub(super) mod network;pub(super) mod snapshots;pub(super) mod ssh;diff --git a/src/cli/src/commands/serve/handlers/mounts.rs b/src/cli/src/commands/serve/handlers/mounts.rsnew file mode 100644index 000000000..5252ae996--- /dev/null+++ b/src/cli/src/commands/serve/handlers/mounts.rs@@ -0,0 +1,132 @@+//! Directory declarations use the same handle as embedded clients. The runtime+//! owns source authorization and delivery, including each subsequent start.++use std::borrow::Cow;+use std::sync::Arc;++use axum::Json;+use axum::extract::rejection::JsonRejection;+use axum::extract::{Path, RawQuery, Request, State};+use axum::http::StatusCode;+use axum::middleware::Next;+use axum::response::{IntoResponse, Response};+use boxlite::experimental::{ExperimentalFeature, ExperimentalFeatures};+use boxlite::{BoxliteError, MountHandle, MountOptions};+use percent_encoding::percent_decode_str;++use super::super::types::ListMountsResponse;+use super::super::{AppState, error_from_boxlite, get_or_fetch_box};++fn invalid_request(message: &str) -> Response {+ error_from_boxlite(&BoxliteError::InvalidArgument(message.into()))+}++/// A target identifies a mount, so it must arrive exactly once and as valid+/// UTF-8. axum's `Query` would replace invalid UTF-8 with U+FFFD, which could+/// then name a different mount.+fn target(query: Option<&str>) -> Result<String, &'static str> {+ let mut values = query+ .unwrap_or_default()+ .split('&')+ .filter_map(|pair| pair.strip_prefix("target="));+ let value = match (values.next(), values.next()) {+ (Some(value), None) if !value.is_empty() => value,+ _ => return Err("expected one nonempty 'target' query parameter"),+ };+ percent_decode_str(&value.replace('+', " "))+ .decode_utf8()+ .map(Cow::into_owned)+ .map_err(|_| "mount target must be valid UTF-8")+}++async fn with_mounts<T: IntoResponse>(+ state: &AppState,+ box_id: &str,+ operation: impl AsyncFnOnce(MountHandle) -> Result<T, BoxliteError>,+) -> Response {+ let handle = match get_or_fetch_box(state, box_id).await {+ Ok(handle) => handle,+ Err(response) => return response,+ };+ match operation(handle.mount()).await {+ Ok(value) => value.into_response(),+ Err(error) => error_from_boxlite(&error),+ }+}++pub(in crate::commands::serve) async fn add(+ State(state): State<Arc<AppState>>,+ Path(box_id): Path<String>,+ body: Result<Json<MountOptions>, JsonRejection>,+) -> Response {+ let request = match body {+ Ok(Json(request)) => request,+ Err(error) => return error_from_boxlite(&BoxliteError::InvalidArgument(error.body_text())),+ };+ with_mounts(&state, &box_id, async move |mount| {+ Ok((StatusCode::CREATED, Json(mount.add(request).await?)))+ })+ .await+}++pub(in crate::commands::serve) async fn list(+ State(state): State<Arc<AppState>>,+ Path(box_id): Path<String>,+) -> Response {+ with_mounts(&state, &box_id, async |mount| {+ Ok(Json(ListMountsResponse {+ mounts: mount.list().await?,+ }))+ })+ .await+}++pub(in crate::commands::serve) async fn get(+ State(state): State<Arc<AppState>>,+ Path(box_id): Path<String>,+ query: RawQuery,+) -> Response {+ let target = match target(query.0.as_deref()) {+ Ok(target) => target,+ Err(message) => return invalid_request(message),+ };+ with_mounts(&state, &box_id, async move |mount| {+ mount.get(target).await.map(Json)+ })+ .await+}++pub(in crate::commands::serve) async fn remove(+ State(state): State<Arc<AppState>>,+ Path(box_id): Path<String>,+ query: RawQuery,+) -> Response {+ let target = match target(query.0.as_deref()) {+ Ok(target) => target,+ Err(message) => return invalid_request(message),+ };+ with_mounts(&state, &box_id, async move |mount| {+ mount.remove(target).await?;+ Ok(StatusCode::NO_CONTENT)+ })+ .await+}++pub(super) fn enabled(features: &ExperimentalFeatures) -> bool {+ cfg!(all(target_os = "linux", target_arch = "x86_64"))+ && features.is_enabled(ExperimentalFeature::NativeVmm)+}++pub(in crate::commands::serve) async fn require_enabled(request: Request, next: Next) -> Response {+ if request+ .extensions()+ .get::<ExperimentalFeatures>()+ .is_some_and(enabled)+ {+ return next.run(request).await;+ }+ error_from_boxlite(&BoxliteError::Unsupported(+ "runtime directory mounts require BOXLITE_EXPERIMENTAL=native-vmm on a Linux x86_64 server"+ .into(),+ ))+}diff --git a/src/cli/src/commands/serve/mod.rs b/src/cli/src/commands/serve/mod.rsindex 50cef123a..5921d63a2 100644--- a/src/cli/src/commands/serve/mod.rs+++ b/src/cli/src/commands/serve/mod.rs@@ -1660,7 +1660,9 @@ fn activity_box_id<'a>(method: &Method, path: &'a str) -> Option<&'a str> {if tail == "ssh" && matches!(*method, Method::GET | Method::HEAD | Method::DELETE) {return None;}- if tail == "executions" && matches!(*method, Method::GET | Method::HEAD) {+ if matches!(tail, "executions" | "mounts" | "mounts/by-target")+ && matches!(*method, Method::GET | Method::HEAD)+ {return None;}Some(box_id)@@ -2051,11 +2053,20 @@ async fn get_or_attach_main_session(fn build_router(state: Arc<AppState>) -> Router {use handlers::{- advanced, boxes, config, executions, files, images, me, metrics, network, snapshots, ssh,- volumes,+ advanced, boxes, config, executions, files, images, me, metrics, mounts, network,+ snapshots, ssh, volumes,};Router::new()+ .route(+ "/v1/boxes/{box_id}/mounts",+ post(mounts::add).get(mounts::list),+ )+ .route(+ "/v1/boxes/{box_id}/mounts/by-target",+ get(mounts::get).delete(mounts::remove),+ )+ .route_layer(middleware::from_fn(mounts::require_enabled))// Web console: the page, its files, and browser sign-in.route("/", get(web_console::index)).route(@@ -2257,7 +2268,8 @@ pub async fn execute(args: ServeArgs, global: &GlobalFlags) -> anyhow::Result<()tokio::spawn(reaper_loop(Arc::clone(&state)));let guard = browser_guard::BrowserGuard::new(&args.host, &args.allowed_hosts);- let app = serve_app(state.clone(), guard);+ let app = serve_app(state.clone(), guard)+ .layer(axum::Extension(global.experimental_features().clone()));let listener = tokio::net::TcpListener::bind((args.host.as_str(), args.port)).await?;let addr = listener.local_addr()?;check_bound_addr(addr, args.api_key.as_deref())?;@@ -2288,6 +2300,7 @@ mod tests {use std::time::Duration;mod executions;+ mod mounts;mod ssh;#[test]@@ -3387,6 +3400,12 @@ mod tests {assert_eq!(activity_box_id(&Method::DELETE, "/v1/boxes/abc/ssh"), None);assert_eq!(activity_box_id(&Method::HEAD, "/v1/boxes/abc/ssh"), None);+ for path in ["/v1/boxes/abc/mounts", "/v1/boxes/abc/mounts/by-target"] {+ assert_eq!(activity_box_id(&Method::GET, path), None);+ assert_eq!(activity_box_id(&Method::HEAD, path), None);+ }+ assert_eq!(activity_box_id(&post, "/v1/boxes/abc/mounts"), Some("abc"));+// Pollers must never hold a box open. A client watching `status` once a// second would otherwise reset the window before every sweep.assert_eq!(activity_box_id(&Method::GET, "/v1/boxes/abc"), None);diff --git a/src/cli/src/commands/serve/tests/mounts.rs b/src/cli/src/commands/serve/tests/mounts.rsnew file mode 100644index 000000000..1a385068b--- /dev/null+++ b/src/cli/src/commands/serve/tests/mounts.rs@@ -0,0 +1,119 @@+use axum::Extension;+use boxlite::experimental::ExperimentalFeatures;+use serde_json::Value;++use super::*;++async fn start_app(enabled: bool, authenticated: bool) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))+ .await+ .unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let mut state = lifecycle_state();+ if authenticated {+ state.api_key = Some("mount-test-key".into());+ }+ let mut router = serve_app(+ Arc::new(state),+ browser_guard::BrowserGuard::new("127.0.0.1", &[]),+ );+ if enabled {+ router = router.layer(Extension(+ ExperimentalFeatures::parse("native-vmm").unwrap(),+ ));+ }+ let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ (url, task)+}++const COLLECTION: &str = "/v1/boxes/missing/mounts";++async fn assert_error(response: reqwest::Response, status: StatusCode, code: &str) {+ assert_eq!(response.status(), status);+ assert_eq!(+ response.json::<Value>().await.unwrap()["error"]["code"],+ code+ );+}++#[tokio::test]+async fn runtime_mount_routes_gate_all_operations_before_parsing() {+ let (url, server) = start_app(false, false).await;+ let client = reqwest::Client::new();+ let config = client+ .get(format!("{url}/v1/config"))+ .send()+ .await+ .unwrap()+ .json::<Value>()+ .await+ .unwrap();+ assert_eq!(config["capabilities"]["runtime_mounts_enabled"], false);+ for (method, suffix) in [+ (reqwest::Method::POST, ""),+ (reqwest::Method::GET, ""),+ (reqwest::Method::GET, "/by-target"),+ (reqwest::Method::DELETE, "/by-target"),+ ] {+ let response = client+ .request(method, format!("{url}{COLLECTION}{suffix}"))+ .send()+ .await+ .unwrap();+ assert_error(response, StatusCode::BAD_REQUEST, "unsupported").await;+ }+ server.abort();+}++#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+#[tokio::test]+async fn runtime_mount_routes_preserve_authentication_and_strict_targets() {+ let (url, server) = start_app(true, true).await;+ let client = reqwest::Client::new();+ let config = client+ .get(format!("{url}/v1/config"))+ .send()+ .await+ .unwrap()+ .json::<Value>()+ .await+ .unwrap();+ assert_eq!(config["capabilities"]["runtime_mounts_enabled"], true);+ for (method, suffix) in [+ (reqwest::Method::POST, ""),+ (reqwest::Method::GET, ""),+ (reqwest::Method::GET, "/by-target"),+ (reqwest::Method::DELETE, "/by-target"),+ ] {+ let response = client+ .request(method, format!("{url}{COLLECTION}{suffix}"))+ .send()+ .await+ .unwrap();+ assert_error(response, StatusCode::UNAUTHORIZED, "unauthenticated").await;+ }+ for (method, suffix) in [+ (reqwest::Method::GET, "/by-target"),+ (reqwest::Method::GET, "/by-target?target="),+ (reqwest::Method::GET, "/by-target?target=%2Fbad%FF"),+ (reqwest::Method::DELETE, "/by-target?target=%2Fbad%FF"),+ (reqwest::Method::DELETE, "/by-target?target=/a&target=/b"),+ ] {+ let response = client+ .request(method, format!("{url}{COLLECTION}{suffix}"))+ .bearer_auth("mount-test-key")+ .send()+ .await+ .unwrap();+ assert_error(response, StatusCode::BAD_REQUEST, "invalid_argument").await;+ }+ let response = client+ .post(format!("{url}{COLLECTION}"))+ .bearer_auth("mount-test-key")+ .json(&serde_json::json!({"source": "/"}))+ .send()+ .await+ .unwrap();+ assert_error(response, StatusCode::BAD_REQUEST, "invalid_argument").await;+ server.abort();+}diff --git a/src/cli/src/commands/serve/types.rs b/src/cli/src/commands/serve/types.rsindex 922a574ae..c0beeb9b1 100644--- a/src/cli/src/commands/serve/types.rs+++ b/src/cli/src/commands/serve/types.rs@@ -418,6 +418,12 @@ pub(super) struct ServerCapabilities {pub sync_exec_enabled: bool,pub volume_read_only_enabled: bool,pub typed_mounts_enabled: bool,+ pub runtime_mounts_enabled: bool,+}++#[derive(Serialize)]+pub(super) struct ListMountsResponse {+ pub mounts: Vec<boxlite::MountInfo>,}// ============================================================================diff --git a/src/cli/src/formatter.rs b/src/cli/src/formatter.rsindex 2f87aff6c..61df00663 100644--- a/src/cli/src/formatter.rs+++ b/src/cli/src/formatter.rs@@ -8,7 +8,7 @@ use gtmpl_value::{FuncError, Value as GtmplValue};use serde::Serialize;use tabled::{Table, Tabled, settings::Style};-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub enum OutputFormat {Table,Json,diff --git a/src/cli/src/main.rs b/src/cli/src/main.rsindex b9b494582..dfcc2e8a5 100644--- a/src/cli/src/main.rs+++ b/src/cli/src/main.rs@@ -158,6 +158,7 @@ async fn run_cli(mut cli: Cli) -> i32 {cli::Commands::Logs(args) => commands::logs::execute(args, &global).await.map(|_| 0),cli::Commands::Stats(args) => commands::stats::execute(args, &global).await.map(|_| 0),cli::Commands::Network(args) => commands::network::execute(args, &global).await.map(|_| 0),+ cli::Commands::Mount(args) => commands::mount::execute(args, &global).await.map(|_| 0),cli::Commands::Ssh(args) => commands::ssh::execute(args, &global).await,cli::Commands::Agent(args) => commands::agent::execute(args, &global).await.map(|_| 0),cli::Commands::Serve(args) => commands::serve::execute(args, &global).await.map(|_| 0),diff --git a/src/cli/tests/common/serve.rs b/src/cli/tests/common/serve.rsindex 1f9757084..03b5f6784 100644--- a/src/cli/tests/common/serve.rs+++ b/src/cli/tests/common/serve.rs@@ -32,8 +32,20 @@ impl ServeChild {/// Start `boxlite serve` with extra `serve` arguments, e.g. `["--api-key",/// "k"]`; pass the same key as `api_key` when it authenticates clients.pub fn start_with(extra: &[&str], api_key: Option<&str>) -> Self {- let home = boxlite_test_utils::home::PerTestBoxHome::new();+ Self::start_with_home(+ boxlite_test_utils::home::PerTestBoxHome::new(),+ extra,+ api_key,+ None,+ )+ }+ pub fn start_with_home(+ home: boxlite_test_utils::home::PerTestBoxHome,+ extra: &[&str],+ api_key: Option<&str>,+ experimental_features: Option<&str>,+ ) -> Self {// Ask the OS for a free port, then release it — a small race with// whatever binds next, but the standard trick and good enough here.let port = std::net::TcpListener::bind("127.0.0.1:0")@@ -43,6 +55,9 @@ impl ServeChild {.port();let mut cmd = Command::new(cli_executable());+ if let Some(features) = experimental_features {+ cmd.env("BOXLITE_EXPERIMENTAL", features);+ }cmd.arg("--home").arg(&home.path);cmd.arg("--config").arg(super::write_registry_config(&home.path));diff --git a/src/cli/tests/runtime_mounts.rs b/src/cli/tests/runtime_mounts.rsnew file mode 100644index 000000000..f4d1f6e8b--- /dev/null+++ b/src/cli/tests/runtime_mounts.rs@@ -0,0 +1,210 @@+#![cfg(all(target_os = "linux", target_arch = "x86_64"))]++mod common;++use std::path::Path;+use std::time::Duration;++use boxlite::experimental::{ExperimentalFeatures, RuntimeBuilder, custom_kernel, native_vmm};+use boxlite::{BoxOptions, BoxliteOptions, NetworkSpec, RootfsSpec};+use boxlite_test_utils::home::PerTestBoxHome;+use common::serve::ServeChild;+use serde_json::{Value, json};+use tokio::process::Command;+use tokio::time::timeout;++const FEATURES: &str = "native-vmm,custom-kernel";+const TARGET: &str = "/mnt/runtime + mount & \u{fffd}";++async fn run(home: &Path, url: Option<&str>, args: &[&str]) -> std::process::Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_boxlite"));+ command+ .env("BOXLITE_EXPERIMENTAL", FEATURES)+ .env_remove("BOXLITE_REST_URL")+ .env_remove("BOXLITE_REST_PATH_PREFIX")+ .arg("--home")+ .arg(home)+ .kill_on_drop(true);+ if let Some(url) = url {+ command.args(["--url", url]);+ } else {+ command.args(["--context", "embedded"]);+ }+ timeout(Duration::from_secs(60), command.args(args).output())+ .await+ .unwrap_or_else(|_| panic!("{args:?}: CLI process did not exit"))+ .unwrap()+}++async fn output(home: &Path, url: Option<&str>, args: &[&str]) -> Vec<u8> {+ let result = run(home, url, args).await;+ assert!(+ result.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&result.stderr)+ );+ result.stdout+}++async fn assert_mounts(home: &Path, url: Option<&str>, id: &str, source: &Path, state: &str) {+ let expected = json!({+ "source": source,+ "target": TARGET,+ "read_only": true,+ "state": state,+ });+ let inspected: Value = serde_json::from_slice(+ &output(+ home,+ url,+ &[+ "mount",+ "inspect",+ id,+ "--box-path",+ TARGET,+ "--format",+ "json",+ ],+ )+ .await,+ )+ .unwrap();+ assert_eq!(inspected, expected);+ let listed: Value =+ serde_json::from_slice(&output(home, url, &["mount", "ls", id, "--format", "json"]).await)+ .unwrap();+ assert_eq!(listed, json!([expected]));+}++#[tokio::test(flavor = "multi_thread")]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn runtime_mounts_round_trip_across_cli_processes() {+ let home = PerTestBoxHome::new();+ let id = {+ let runtime = RuntimeBuilder::new(BoxliteOptions {+ home_dir: home.path.clone(),+ image_registries: boxlite_test_utils::test_registries(),+ ..Default::default()+ })+ .with_features(ExperimentalFeatures::parse(FEATURES).unwrap())+ .build()+ .unwrap();+ let mut options = BoxOptions {+ rootfs: RootfsSpec::Image("alpine:latest".into()),+ network: NetworkSpec::Disabled,+ detach: true,+ auto_delete: Some(0),+ cmd: Some(vec!["sleep".into(), "300".into()]),+ ..Default::default()+ };+ native_vmm::configure(&mut options);+ custom_kernel::configure(+ &mut options,+ custom_kernel::KernelOptions::new(std::env::var_os("VMM_KERNEL").expect("VMM_KERNEL"))+ .with_format(custom_kernel::KernelFormat::Elf),+ );+ runtime+ .create(options, None)+ .await+ .unwrap()+ .id()+ .to_string()+ };+ let scratch = tempfile::tempdir().unwrap();+ let source = scratch.path().canonicalize().unwrap().join("source");+ std::fs::create_dir(&source).unwrap();+ std::fs::write(source.join("value"), "from host\n").unwrap();+ let add = [+ "mount",+ "add",+ &id,+ "--source",+ source.to_str().unwrap(),+ "--box-path",+ TARGET,+ "--read-only",+ ];+ let remove = ["mount", "rm", &id, "--box-path", TARGET];+ let inspect = [+ "mount",+ "inspect",+ &id,+ "--box-path",+ TARGET,+ "--format",+ "json",+ ];++ // Each invocation reopens the local runtime without starting the box.+ let added = output(&home.path, None, &add).await;+ assert!(String::from_utf8(added).unwrap().contains("configured"));+ assert_mounts(&home.path, None, &id, &source, "configured").await;+ output(&home.path, None, &remove).await;+ assert_eq!(output(&home.path, None, &inspect).await, b"null\n");++ let home_path = home.path.clone();+ let mut serve = ServeChild::start_with_home(home, &[], None, Some(FEATURES));+ let url = serve.url();+ let remote = Some(url.as_str());+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(20))+ .build()+ .unwrap();+ let endpoint = format!("{url}/v1/boxes/{id}");+ let lifecycle = async || -> Value {+ let info: Value = client+ .get(&endpoint)+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap()+ .json()+ .await+ .unwrap();+ json!([info["status"], info["pid"]])+ };+ let idle = lifecycle().await;+ assert_eq!(idle, json!(["configured", null]));++ output(&home_path, remote, &add).await;+ assert_mounts(&home_path, remote, &id, &source, "configured").await;+ assert_eq!(lifecycle().await, idle);+ serve.restart();+ assert_mounts(&home_path, remote, &id, &source, "configured").await;+ assert_eq!(lifecycle().await, idle);++ output(&home_path, remote, &["start", &id]).await;+ assert_mounts(&home_path, remote, &id, &source, "mounted").await;+ let file = format!("{TARGET}/value");+ assert_eq!(+ output(&home_path, remote, &["exec", &id, "--", "cat", &file]).await,+ b"from host\n"+ );+ output(&home_path, remote, &remove).await;+ assert_eq!(output(&home_path, remote, &inspect).await, b"null\n");++ // Add through the same CLI while the VM is already running.+ let added = output(&home_path, remote, &add).await;+ assert!(String::from_utf8(added).unwrap().contains("mounted"));+ assert_mounts(&home_path, remote, &id, &source, "mounted").await;+ assert_eq!(+ output(&home_path, remote, &["exec", &id, "--", "cat", &file]).await,+ b"from host\n"+ );+ output(&home_path, remote, &remove).await;+ assert_eq!(output(&home_path, remote, &inspect).await, b"null\n");+ let listed: Value = serde_json::from_slice(+ &output(+ &home_path,+ remote,+ &["mount", "ls", &id, "--format", "json"],+ )+ .await,+ )+ .unwrap();+ assert_eq!(listed, json!([]));+ assert!(!run(&home_path, remote, &remove).await.status.success());+ output(&home_path, remote, &["rm", "--force", &id]).await;+}