From cf0c49835badb0b2677556514feafaa21ae7d3d0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:04:43 +0000 Subject: [PATCH 01/29] chore(vendor): bump tinybox submodule Update the vendored tinybox submodule to the latest upstream commit. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/tinybox | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/tinybox b/vendor/tinybox index e3f2a779c3a..63232cabf16 160000 --- a/vendor/tinybox +++ b/vendor/tinybox @@ -1 +1 @@ -Subproject commit e3f2a779c3a9e409324c36c6a7567568808c5261 +Subproject commit 63232cabf1642109a4e0b3e3a049680f8aca030f From c5a3419f5000ce76f7db18c888c0ce9249713bfc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:11:25 +0000 Subject: [PATCH 02/29] build(deps): add tinybox-openshell dependency Wire the new tinybox-openshell crate into the workspace lockfile so the core crate can depend on it. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 10 +++ .../config/schema/runtime_openshell_tests.rs | 76 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs diff --git a/Cargo.lock b/Cargo.lock index ea780d8895f..f585c93a836 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9377,6 +9377,7 @@ dependencies = [ "tinybox-jail", "tinybox-linux", "tinybox-microvm", + "tinybox-openshell", "tinybox-ssh", "tinybus", "tinybus-module", @@ -9387,6 +9388,15 @@ dependencies = [ "uuid", ] +[[package]] +name = "tinybox-openshell" +version = "0.2.3" +dependencies = [ + "async-trait", + "serde_json", + "tinybox-core", +] + [[package]] name = "tinybox-ssh" version = "0.2.3" diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs b/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs new file mode 100644 index 00000000000..66521a52e57 --- /dev/null +++ b/crates/openhuman-core/src/config/schema/runtime_openshell_tests.rs @@ -0,0 +1,76 @@ +use super::*; + +#[test] +fn defaults_give_one_core_256_mib_and_a_fifteen_minute_idle_ttl() { + let config = OpenShellRuntimeConfig::default(); + assert_eq!(config.image, DEFAULT_OPENSHELL_IMAGE); + assert_eq!(config.cpu_millis, 1_000); + assert_eq!(config.memory_mb, 256); + assert_eq!(config.idle_ttl_secs, 900); + assert_eq!(config.max_live, 50); +} + +#[test] +fn an_empty_table_keeps_every_default() { + let config: OpenShellRuntimeConfig = toml::from_str("").unwrap(); + assert_eq!(config, OpenShellRuntimeConfig::default()); +} + +#[test] +fn the_serde_form_pins_its_field_names() { + let config = OpenShellRuntimeConfig { + image: "registry.example/agent:1".into(), + cpu_millis: 500, + memory_mb: 128, + idle_ttl_secs: 60, + max_live: 3, + }; + let value = serde_json::to_value(&config).unwrap(); + assert_eq!( + value, + serde_json::json!({ + "image": "registry.example/agent:1", + "cpu_millis": 500, + "memory_mb": 128, + "idle_ttl_secs": 60, + "max_live": 3, + }) + ); + let back: OpenShellRuntimeConfig = serde_json::from_value(value).unwrap(); + assert_eq!(back, config); +} + +#[test] +fn memory_converts_to_whole_mebibytes() { + let config = OpenShellRuntimeConfig::default(); + assert_eq!(config.memory_bytes(), Some(256 * 1024 * 1024)); + assert_eq!(config.memory_bytes().unwrap() % (1024 * 1024), 0); +} + +#[test] +fn memory_that_overflows_bytes_has_no_byte_count() { + let config = OpenShellRuntimeConfig { + memory_mb: u64::MAX, + ..OpenShellRuntimeConfig::default() + }; + assert_eq!(config.memory_bytes(), None); +} + +#[test] +fn the_runtime_table_reads_its_openshell_section() { + let runtime: super::super::RuntimeConfig = toml::from_str( + r#" + [openshell] + image = "registry.example/agent:2" + max_live = 7 + "#, + ) + .unwrap(); + assert_eq!(runtime.openshell.image, "registry.example/agent:2"); + assert_eq!(runtime.openshell.max_live, 7); + assert_eq!(runtime.openshell.idle_ttl_secs, 900); + assert_eq!( + super::super::RuntimeConfig::default().openshell, + OpenShellRuntimeConfig::default() + ); +} From 18cce72c7df9b492b33d7c474b1d887a0283c327 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:11:31 +0000 Subject: [PATCH 03/29] test(config): cover openshell backend wire name Add a test asserting that SandboxBackend::OpenShell serializes to the string "openshell" and that a TOML config using that value deserializes back to the OpenShell variant, guarding the on-the-wire representation against accidental renames. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/config/schema/security_tests.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/openhuman-core/src/config/schema/security_tests.rs b/crates/openhuman-core/src/config/schema/security_tests.rs index 04c27f37742..1b059b204a9 100644 --- a/crates/openhuman-core/src/config/schema/security_tests.rs +++ b/crates/openhuman-core/src/config/schema/security_tests.rs @@ -8,6 +8,16 @@ fn security_config_defaults() { assert_eq!(sec.audit.max_size_mb, 100); } +#[test] +fn the_openshell_backend_is_named_openshell_on_the_wire() { + assert_eq!( + serde_json::to_value(SandboxBackend::OpenShell).unwrap(), + serde_json::json!("openshell") + ); + let config: SandboxConfig = toml::from_str("backend = \"openshell\"").unwrap(); + assert!(matches!(config.backend, SandboxBackend::OpenShell)); +} + #[test] fn sandbox_config_default() { let sb = SandboxConfig::default(); From 5f6a3b37dc045a25c026cb612f0b826a909461b7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:12:26 +0000 Subject: [PATCH 04/29] feat(config): register openshell runtime config module Wire the new runtime_openshell schema module into the config schema tree so its types are compiled and available alongside the other runtime configuration modules. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/config/schema/mod.rs | 1 + crates/openhuman-core/src/config/schema/runtime_openshell.rs | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 crates/openhuman-core/src/config/schema/runtime_openshell.rs diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index a8fc84cda5d..72204ba43b5 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -104,6 +104,7 @@ mod proxy; mod routes; mod runtime; mod runtime_local_jail; +mod runtime_openshell; mod scheduler_gate; mod security; mod task_sources; diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell.rs b/crates/openhuman-core/src/config/schema/runtime_openshell.rs new file mode 100644 index 00000000000..9d662c516de --- /dev/null +++ b/crates/openhuman-core/src/config/schema/runtime_openshell.rs @@ -0,0 +1,5 @@ +//! `[runtime.openshell]` — the boxes the OpenShell sandbox backend creates. + +#[cfg(test)] +#[path = "runtime_openshell_tests.rs"] +mod tests; From c042cef0d47ecbe0848b2ecb99ccc8f04adcffcc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:13:52 +0000 Subject: [PATCH 05/29] feat(config): add openshell runtime config and sandbox backend Adds an `[runtime.openshell]` section describing the image, CPU, memory, idle TTL and live-box cap for boxes created by the OpenShell sandbox backend, along with an `openshell` variant of the sandbox backend enum. This lets the TinyBox module be configured from the core config file instead of hardcoded defaults. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/config/schema/mod.rs | 1 + .../src/config/schema/runtime.rs | 4 ++ .../src/config/schema/runtime_openshell.rs | 57 +++++++++++++++++++ .../src/config/schema/security.rs | 4 ++ 4 files changed, 66 insertions(+) diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index 72204ba43b5..93e76282aff 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -156,6 +156,7 @@ pub use runtime::{ DockerRuntimeConfig, ReliabilityConfig, RuntimeConfig, SchedulerConfig, ShellConfig, }; pub use runtime_local_jail::LocalJailConfig; +pub use runtime_openshell::{OpenShellRuntimeConfig, DEFAULT_OPENSHELL_IMAGE}; pub use scheduler_gate::{PauseReason, Policy, SchedulerGateConfig, SchedulerGateMode}; pub use security::{ AuditConfig, ResourceLimitsConfig, SandboxBackend, SandboxConfig, SecurityConfig, diff --git a/crates/openhuman-core/src/config/schema/runtime.rs b/crates/openhuman-core/src/config/schema/runtime.rs index 527e3ad77a4..dfb09271d27 100644 --- a/crates/openhuman-core/src/config/schema/runtime.rs +++ b/crates/openhuman-core/src/config/schema/runtime.rs @@ -15,6 +15,9 @@ pub struct RuntimeConfig { /// Filesystem grants for the local OS jail (`[runtime.local_jail]`). #[serde(default)] pub local_jail: super::LocalJailConfig, + /// Boxes for the OpenShell sandbox backend (`[runtime.openshell]`). + #[serde(default)] + pub openshell: super::OpenShellRuntimeConfig, #[serde(default)] pub reasoning_enabled: Option, /// Reasoning ("thinking") effort for agent turns: `none`, `minimal`, @@ -107,6 +110,7 @@ impl Default for RuntimeConfig { kind: default_runtime_kind(), docker: DockerRuntimeConfig::default(), local_jail: super::LocalJailConfig::default(), + openshell: super::OpenShellRuntimeConfig::default(), reasoning_enabled: None, reasoning_effort: None, reasoning_effort_by_model: BTreeMap::new(), diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell.rs b/crates/openhuman-core/src/config/schema/runtime_openshell.rs index 9d662c516de..40b693ed07f 100644 --- a/crates/openhuman-core/src/config/schema/runtime_openshell.rs +++ b/crates/openhuman-core/src/config/schema/runtime_openshell.rs @@ -1,4 +1,61 @@ //! `[runtime.openshell]` — the boxes the OpenShell sandbox backend creates. +//! +//! With `[security.sandbox] backend = "openshell"`, every sandboxed shell +//! command runs in a box the TinyBox module creates on an NVIDIA OpenShell +//! gateway. Each tenant (profile and agent) gets one box, created on its first +//! command, reused after that, and closed once it has been idle for +//! `idle_ttl_secs`. `max_live` caps the boxes alive at once across the +//! process. The idle TTL and the cap are read when the first box is needed, so +//! changing them takes effect on the next core start; the image and limits +//! apply to every box created after a change. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// The image a box starts from when none is configured: the OpenShell +/// community base sandbox, which carries the `/sandbox` workspace, `sh` and +/// `timeout` the backend relies on. +pub const DEFAULT_OPENSHELL_IMAGE: &str = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest"; + +const MEBIBYTE: u64 = 1024 * 1024; + +/// `[runtime.openshell]`: what each OpenShell box is created with, and how +/// many may live at once. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(default)] +pub struct OpenShellRuntimeConfig { + /// OCI image reference every new box starts from. + pub image: String, + /// CPU allowance per box, in thousandths of a core. + pub cpu_millis: u32, + /// Memory per box, in mebibytes. OpenShell only accepts whole mebibytes, + /// which is why the setting is not in bytes. + pub memory_mb: u64, + /// Seconds a box may sit idle before it is closed. + pub idle_ttl_secs: u64, + /// The most boxes alive at once in this process. + pub max_live: usize, +} + +impl OpenShellRuntimeConfig { + /// [`Self::memory_mb`] in bytes, always a whole number of mebibytes, or + /// `None` when that many bytes does not fit in a `u64`. + pub fn memory_bytes(&self) -> Option { + self.memory_mb.checked_mul(MEBIBYTE) + } +} + +impl Default for OpenShellRuntimeConfig { + fn default() -> Self { + Self { + image: DEFAULT_OPENSHELL_IMAGE.to_owned(), + cpu_millis: 1_000, + memory_mb: 256, + idle_ttl_secs: 900, + max_live: 50, + } + } +} #[cfg(test)] #[path = "runtime_openshell_tests.rs"] diff --git a/crates/openhuman-core/src/config/schema/security.rs b/crates/openhuman-core/src/config/schema/security.rs index eb9faaf49f6..ef2e1bb4bde 100644 --- a/crates/openhuman-core/src/config/schema/security.rs +++ b/crates/openhuman-core/src/config/schema/security.rs @@ -43,6 +43,10 @@ pub enum SandboxBackend { Firejail, Bubblewrap, Docker, + /// One long-lived box per tenant on an NVIDIA OpenShell gateway, through + /// the TinyBox module (`[runtime.openshell]`). + #[serde(rename = "openshell")] + OpenShell, None, } From 5800c9859862e6c639f10f5f29487cd8559ba131 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:14:46 +0000 Subject: [PATCH 06/29] chore(config): re-export OpenShellRuntimeConfig Adds OpenShellRuntimeConfig to the config module's public re-exports so it can be used by downstream code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/config/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs index e5d8edbeedb..6ce414ed2fe 100644 --- a/crates/openhuman-core/src/config/mod.rs +++ b/crates/openhuman-core/src/config/mod.rs @@ -53,6 +53,7 @@ pub use schema::{ DockerRuntimeConfig, EmailConfig, EmbeddingRouteConfig, GitbooksConfig, HttpHeader, HttpRequestConfig, IMessageConfig, IntegrationToggle, IntegrationsConfig, LarkConfig, LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, McpAuthConfig, McpClientConfig, + OpenShellRuntimeConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, ObservabilityConfig, OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, ProviderRoute, From e8bdf57189ae998da2c24475e57435be29d12c8c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:15:51 +0000 Subject: [PATCH 07/29] feat(sandbox): add scripted driver fixture for openshell tests Introduce a scripted driver fixture that lets sandbox tests drive the openshell driver through predetermined responses. This makes it possible to exercise driver behaviour deterministically without a live backend. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openshell/scripted_driver_fixture.rs | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs new file mode 100644 index 00000000000..90017a1a0c2 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/scripted_driver_fixture.rs @@ -0,0 +1,166 @@ +//! Test-only [`BoxDriver`] stand-in: records every call and answers execs from +//! a script, so the registry's lifecycle is testable without a TinyBox module. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use tokio::sync::Notify; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; + +/// One call the registry made. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Call { + Create(BoxSettings), + Exec { resource: String, exec: BoxExec }, + Close(String), +} + +/// How the next exec answers. +pub(crate) enum ExecStep { + /// Reply with this output. + Reply(BoxOutput), + /// Fail with this error. + Fail(BoxError), + /// Never answer. + Hang, + /// Wait for the notification, then reply `ok`. + WaitThenReply(Arc), + /// Wait for the notification, then fail. + WaitThenFail(Arc, BoxError), +} + +/// A driver that mints `box-` ids and follows its exec script; an exec past +/// the end of the script replies `ok` with exit code 0. +#[derive(Default)] +pub(crate) struct ScriptedDriver { + calls: Mutex>, + next_id: AtomicUsize, + script: Mutex>, + create_delay: Mutex, + create_failures: AtomicUsize, + close_fails: AtomicBool, +} + +impl ScriptedDriver { + pub(crate) fn new() -> Arc { + Arc::new(Self::default()) + } + + pub(crate) fn then(&self, step: ExecStep) { + self.script.lock().unwrap().push_back(step); + } + + pub(crate) fn slow_create(&self, delay: Duration) { + *self.create_delay.lock().unwrap() = delay; + } + + pub(crate) fn fail_next_creates(&self, count: usize) { + self.create_failures.store(count, Ordering::SeqCst); + } + + pub(crate) fn fail_closes(&self) { + self.close_fails.store(true, Ordering::SeqCst); + } + + pub(crate) fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + + pub(crate) fn created(&self) -> usize { + self.calls() + .iter() + .filter(|call| matches!(call, Call::Create(_))) + .count() + } + + pub(crate) fn closed(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Close(resource) => Some(resource), + _ => None, + }) + .collect() + } + + pub(crate) fn exec_resources(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|call| match call { + Call::Exec { resource, .. } => Some(resource), + _ => None, + }) + .collect() + } + + pub(crate) fn last_exec(&self) -> Option { + self.calls().into_iter().rev().find_map(|call| match call { + Call::Exec { exec, .. } => Some(exec), + _ => None, + }) + } + + fn record(&self, call: Call) { + self.calls.lock().unwrap().push(call); + } +} + +pub(crate) fn ok_output() -> BoxOutput { + BoxOutput { + exit_code: 0, + stdout: b"ok".to_vec(), + stderr: Vec::new(), + } +} + +#[async_trait] +impl BoxDriver for ScriptedDriver { + async fn create(&self, settings: &BoxSettings) -> Result { + self.record(Call::Create(settings.clone())); + let delay = *self.create_delay.lock().unwrap(); + tokio::time::sleep(delay).await; + let failures = self.create_failures.load(Ordering::SeqCst); + if failures > 0 { + self.create_failures.store(failures - 1, Ordering::SeqCst); + return Err(BoxError::Driver("create refused".into())); + } + Ok(format!( + "box-{}", + self.next_id.fetch_add(1, Ordering::SeqCst) + )) + } + + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result { + self.record(Call::Exec { + resource: resource.to_owned(), + exec: exec.clone(), + }); + let step = self.script.lock().unwrap().pop_front(); + match step { + None => Ok(ok_output()), + Some(ExecStep::Reply(output)) => Ok(output), + Some(ExecStep::Fail(error)) => Err(error), + Some(ExecStep::Hang) => std::future::pending().await, + Some(ExecStep::WaitThenReply(gate)) => { + gate.notified().await; + Ok(ok_output()) + } + Some(ExecStep::WaitThenFail(gate, error)) => { + gate.notified().await; + Err(error) + } + } + } + + async fn close(&self, resource: &str) -> Result<(), BoxError> { + self.record(Call::Close(resource.to_owned())); + if self.close_fails.load(Ordering::SeqCst) { + return Err(BoxError::Driver("close refused".into())); + } + Ok(()) + } +} From 113f340949dcbeab7a8e3b35723a626a86942d73 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:16:37 +0000 Subject: [PATCH 08/29] test(sandbox): add registry tests for openshell sandbox Adds unit tests covering the openshell sandbox registry, exercising registration and lookup behaviour so regressions in the registry are caught. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/registry_tests.rs | 492 ++++++++++++++++++ 1 file changed, 492 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/registry_tests.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs new file mode 100644 index 00000000000..a7dda048b93 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs @@ -0,0 +1,492 @@ +use super::*; +use crate::sandbox::openshell::scripted_driver::{ok_output, Call, ExecStep, ScriptedDriver}; +use std::collections::BTreeMap; +use tokio::sync::Notify; + +const TTL: Duration = Duration::from_secs(900); + +fn limits(max_live: usize) -> RegistryLimits { + RegistryLimits { + idle_ttl: TTL, + max_live, + } +} + +fn settings() -> BoxSettings { + BoxSettings { + image: "registry.example/agent:1".into(), + cpu_millis: 1_000, + memory_bytes: 256 * 1024 * 1024, + } +} + +fn request(command: &str) -> BoxRequest { + BoxRequest { + command: command.into(), + env: BTreeMap::new(), + timeout: Duration::from_secs(30), + } +} + +/// An embedded user: no profile, the user's id as the agent. +fn user(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +fn registry(driver: &Arc, max_live: usize) -> Arc> { + BoxRegistry::new(Arc::clone(driver), limits(max_live)) +} + +#[tokio::test(start_paused = true)] +async fn one_tenant_reuses_its_box_across_commands() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + + let first = boxes + .exec(&user("u1"), &settings(), &request("echo hi")) + .await + .unwrap(); + boxes + .exec(&user("u1"), &settings(), &request("pwd")) + .await + .unwrap(); + + assert_eq!(first.stdout, "ok"); + assert_eq!(first.exit_code, 0); + assert!(!first.timed_out); + assert_eq!(driver.created(), 1); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-0"]); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn the_box_enforces_the_deadline_from_its_own_workspace() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + let mut request = request("ls | wc -l"); + request.env.insert("LANG".into(), "C.UTF-8".into()); + + boxes.exec(&user("u1"), &settings(), &request).await.unwrap(); + + let exec = driver.last_exec().unwrap(); + assert_eq!( + exec.argv, + vec!["timeout", "-k", "5", "30", "sh", "-c", "ls | wc -l"] + ); + assert_eq!(exec.cwd, "/sandbox"); + assert_eq!(exec.env, request.env); + assert_eq!(exec.deadline, Duration::from_secs(30) + BACKSTOP_MARGIN); + assert_eq!(driver.calls()[0], Call::Create(settings())); +} + +#[test] +fn deadlines_round_up_to_whole_seconds_of_at_least_one() { + assert_eq!(whole_seconds(Duration::from_millis(1_500)), 2); + assert_eq!(whole_seconds(Duration::from_secs(30)), 30); + assert_eq!(whole_seconds(Duration::ZERO), 1); +} + +#[tokio::test(start_paused = true)] +async fn embedded_users_of_one_host_get_separate_boxes() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + + boxes + .exec(&user("alice"), &settings(), &request("id")) + .await + .unwrap(); + boxes + .exec(&user("bob"), &settings(), &request("id")) + .await + .unwrap(); + + assert_eq!(driver.created(), 2); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-1"]); +} + +#[tokio::test(start_paused = true)] +async fn concurrent_first_commands_create_one_box() { + let driver = ScriptedDriver::new(); + driver.slow_create(Duration::from_secs(3)); + let boxes = registry(&driver, 10); + + let runs = (0..5).map(|n| { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request(&format!("echo {n}"))) + .await + }) + }); + for run in futures::future::join_all(runs).await { + run.unwrap().unwrap(); + } + + assert_eq!(driver.created(), 1); + assert!(driver.exec_resources().iter().all(|id| id == "box-0")); +} + +#[tokio::test(start_paused = true)] +async fn reap_closes_a_box_once_it_has_been_idle_for_the_ttl() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + let finished = Instant::now(); + + assert_eq!(boxes.reap(finished + TTL - Duration::from_secs(1)).await, 0); + assert!(driver.closed().is_empty()); + assert_eq!(boxes.reap(finished + TTL).await, 1); + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 0); + + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + assert_eq!(driver.created(), 2); +} + +#[tokio::test(start_paused = true)] +async fn reap_never_closes_a_box_with_a_command_in_flight() { + let driver = ScriptedDriver::new(); + let gate = Arc::new(Notify::new()); + driver.then(ExecStep::WaitThenReply(Arc::clone(&gate))); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + tokio::task::yield_now().await; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + assert_eq!(boxes.reap(Instant::now() + TTL * 4).await, 0); + assert!(driver.closed().is_empty()); + + gate.notify_one(); + running.await.unwrap().unwrap(); + assert_eq!(boxes.reap(Instant::now() + TTL).await, 1); +} + +#[tokio::test(start_paused = true)] +async fn the_background_reaper_closes_idle_boxes() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + boxes.start_reaper(); + boxes.start_reaper(); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + tokio::time::sleep(TTL + REAP_EVERY_AT_MOST * 2).await; + + assert_eq!(driver.closed(), vec!["box-0"]); +} + +#[test] +fn the_reaper_ticks_at_half_the_ttl_capped_and_never_zero() { + assert_eq!(reap_interval(TTL), REAP_EVERY_AT_MOST); + assert_eq!( + reap_interval(Duration::from_secs(20)), + Duration::from_secs(10) + ); + assert_eq!(reap_interval(Duration::ZERO), Duration::from_secs(1)); +} + +#[tokio::test(start_paused = true)] +async fn a_new_tenant_is_refused_when_no_idle_box_can_be_reaped() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 1); + boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap(); + + let refused = boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap_err(); + + assert_eq!(refused, BoxError::AtCapacity); + assert_eq!( + refused.to_string(), + "the sandbox service is at capacity; try again shortly" + ); + assert_eq!(driver.created(), 1); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn reaping_an_idle_box_makes_room_for_a_new_tenant() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 1); + boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap(); + tokio::time::advance(TTL).await; + + boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap(); + + let calls = driver.calls(); + let closed = calls + .iter() + .position(|call| *call == Call::Close("box-0".into())) + .unwrap(); + let created = calls + .iter() + .rposition(|call| matches!(call, Call::Create(_))) + .unwrap(); + assert!(closed < created); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn a_failed_create_does_not_hold_a_slot() { + let driver = ScriptedDriver::new(); + driver.fail_next_creates(1); + let boxes = registry(&driver, 1); + + let failed = boxes + .exec(&user("alice"), &settings(), &request("true")) + .await + .unwrap_err(); + assert_eq!(failed, BoxError::Driver("create refused".into())); + assert_eq!(boxes.live(), 0); + + boxes + .exec(&user("bob"), &settings(), &request("true")) + .await + .unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn an_unknown_box_is_replaced_once_and_the_command_retried() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + let result = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(result.stdout, "ok"); + assert_eq!(driver.created(), 2); + assert_eq!(driver.exec_resources(), vec!["box-0", "box-1"]); +} + +#[tokio::test(start_paused = true)] +async fn a_second_unknown_box_fails_the_command() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + let failed = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap_err(); + + assert_eq!(failed, BoxError::UnknownResource); + assert_eq!(driver.created(), 2); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn other_exec_failures_keep_the_box() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::Driver("bus down".into()))); + let boxes = registry(&driver, 10); + + let failed = boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap_err(); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(failed, BoxError::Driver("bus down".into())); + assert_eq!(driver.created(), 1); +} + +#[tokio::test(start_paused = true)] +async fn an_exit_of_124_is_the_box_timing_the_command_out() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Reply(BoxOutput { + exit_code: 124, + stdout: b"partial".to_vec(), + stderr: Vec::new(), + })); + let boxes = registry(&driver, 10); + + let result = boxes + .exec(&user("u1"), &settings(), &request("sleep 99")) + .await + .unwrap(); + + assert!(result.timed_out); + assert_eq!(result.stdout, "partial"); + assert!(driver.closed().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn the_backstop_discards_a_box_that_does_not_answer() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Hang); + let boxes = registry(&driver, 10); + let started = Instant::now(); + + let result = boxes + .exec(&user("u1"), &settings(), &request("sleep 99")) + .await + .unwrap(); + + assert_eq!(started.elapsed(), Duration::from_secs(30) + BACKSTOP_MARGIN); + assert!(result.timed_out); + assert_eq!(result.exit_code, 124); + assert_eq!(driver.closed(), vec!["box-0"]); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + assert_eq!(driver.created(), 2); +} + +#[tokio::test(start_paused = true)] +async fn release_closes_the_tenants_box_only() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + for id in ["alice", "bob"] { + boxes + .exec(&user(id), &settings(), &request("true")) + .await + .unwrap(); + } + + boxes.release(&user("alice")).await; + boxes.release(&user("nobody")).await; + + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 1); +} + +#[tokio::test(start_paused = true)] +async fn a_released_box_is_not_recreated_by_a_command_still_running() { + let driver = ScriptedDriver::new(); + let gate = Arc::new(Notify::new()); + driver.then(ExecStep::WaitThenFail( + Arc::clone(&gate), + BoxError::UnknownResource, + )); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + boxes.release(&user("u1")).await; + gate.notify_one(); + + assert_eq!(running.await.unwrap().unwrap_err(), BoxError::Released); + assert_eq!(driver.created(), 1); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_closes_every_box() { + let driver = ScriptedDriver::new(); + let boxes = registry(&driver, 10); + for id in ["alice", "bob"] { + boxes + .exec(&user(id), &settings(), &request("true")) + .await + .unwrap(); + } + + boxes.shutdown().await; + + let mut closed = driver.closed(); + closed.sort(); + assert_eq!(closed, vec!["box-0", "box-1"]); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn a_failed_close_is_logged_not_raised() { + let driver = ScriptedDriver::new(); + driver.fail_closes(); + let boxes = registry(&driver, 10); + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + boxes.release(&user("u1")).await; + boxes.shutdown().await; + + assert_eq!(driver.closed(), vec!["box-0"]); + assert_eq!(boxes.live(), 0); +} + +#[tokio::test(start_paused = true)] +async fn an_abandoned_command_stops_holding_its_box() { + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Hang); + let boxes = registry(&driver, 10); + let running = { + let boxes = Arc::clone(&boxes); + tokio::spawn(async move { + boxes + .exec(&user("u1"), &settings(), &request("sleep 3600")) + .await + }) + }; + while driver.exec_resources().is_empty() { + tokio::task::yield_now().await; + } + + running.abort(); + assert!(running.await.unwrap_err().is_cancelled()); + + assert_eq!(boxes.reap(Instant::now() + TTL).await, 1); + assert_eq!(driver.closed(), vec!["box-0"]); +} + +#[test] +fn output_bytes_become_lossy_text() { + let result = finished(BoxOutput { + exit_code: 2, + stdout: vec![b'a', 0xff], + stderr: b"oops".to_vec(), + }); + assert_eq!(result.exit_code, 2); + assert_eq!(result.stdout, "a\u{fffd}"); + assert_eq!(result.stderr, "oops"); + assert!(!result.timed_out); + assert_eq!(finished(ok_output()).stdout, "ok"); +} From 15dbeaceb31bf869388206d4c06baf159963d79b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:16:56 +0000 Subject: [PATCH 09/29] test(sandbox): add bus driver tests for openshell sandbox Adds a test module covering the openshell bus driver so its message routing and lifecycle behaviour are exercised by the suite. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/bus_driver_tests.rs | 128 ++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs b/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs new file mode 100644 index 00000000000..54b08e41d38 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/bus_driver_tests.rs @@ -0,0 +1,128 @@ +use super::*; +use std::collections::BTreeMap; + +fn settings() -> BoxSettings { + BoxSettings { + image: "registry.example/agent:1".into(), + cpu_millis: 750, + memory_bytes: 256 * 1024 * 1024, + } +} + +fn info(state: &str) -> contract::ResourceInfo { + contract::ResourceInfo { + resource: contract::ResourceId("r-1".into()), + backend: BACKEND.into(), + state: state.into(), + published_ports: Vec::new(), + } +} + +#[test] +fn a_box_is_an_openshell_image_with_no_network_no_ports_and_no_host_env() { + let request = create_request(contract::ResourceId("r-1".into()), &settings()); + + assert_eq!(request.resource, contract::ResourceId("r-1".into())); + assert_eq!(request.backend, "openshell"); + assert_eq!( + request.workspace, + contract::Workspace::Image("registry.example/agent:1".into()) + ); + assert_eq!(request.network, contract::NetworkPolicy::Denied); + assert_eq!(request.host, contract::HostConfig::Local); + assert!(request.ports.is_empty()); + assert!(request.env.is_empty()); + assert_eq!(request.resources.cpu_millis, 750); + assert_eq!(request.resources.memory_bytes, 256 * 1024 * 1024); + assert_eq!( + request.resources.pids_max, + contract::ResourceLimits::default().pids_max + ); + assert_eq!( + request.resources.disk_bytes, + contract::ResourceLimits::default().disk_bytes + ); +} + +#[test] +fn an_exec_carries_argv_workdir_and_only_the_given_env() { + let mut env = BTreeMap::new(); + env.insert("LANG".to_owned(), "C.UTF-8".to_owned()); + let exec = BoxExec { + argv: vec!["sh".into(), "-c".into(), "true".into()], + cwd: "/sandbox".into(), + env: env.clone(), + deadline: Duration::from_secs(40), + }; + + let request = exec_request("r-1", &exec); + + assert_eq!(request.resource, contract::ResourceId("r-1".into())); + assert_eq!(request.argv, exec.argv); + assert_eq!(request.cwd.as_deref(), Some("/sandbox")); + assert_eq!(request.env, env); + assert_eq!(request.stdin, None); +} + +#[test] +fn the_bus_waits_past_the_registry_backstop() { + assert_eq!( + bus_deadline(Duration::from_secs(40)), + Duration::from_secs(40) + BUS_REPLY_GRACE + ); +} + +#[test] +fn a_failed_exec_in_a_live_box_is_a_driver_error() { + for state in ["ready", "running"] { + assert_eq!( + exec_failure("exec broke".into(), Ok(info(state))), + BoxError::Driver("exec broke".into()) + ); + } +} + +#[test] +fn a_failed_exec_in_a_dead_box_is_an_unknown_resource() { + for state in ["failed", "stopped", "archived"] { + assert_eq!( + exec_failure("exec broke".into(), Ok(info(state))), + BoxError::UnknownResource + ); + } +} + +#[test] +fn a_box_the_module_refuses_to_inspect_is_an_unknown_resource() { + let refused = tinybus::module::ModuleCallError::ModuleFault.to_string(); + assert_eq!( + exec_failure("exec broke".into(), Err(refused)), + BoxError::UnknownResource + ); +} + +#[test] +fn an_unreachable_module_is_a_driver_error_not_a_lost_box() { + let unreachable = tinybus::module::ModuleCallError::Unavailable.to_string(); + assert_eq!( + exec_failure("exec broke".into(), Err(unreachable)), + BoxError::Driver("exec broke".into()) + ); +} + +#[test] +fn output_is_passed_through_unchanged() { + let output = box_output(contract::ExecOutput { + exit_code: 3, + stdout: b"out".to_vec(), + stderr: b"err".to_vec(), + }); + assert_eq!( + output, + BoxOutput { + exit_code: 3, + stdout: b"out".to_vec(), + stderr: b"err".to_vec(), + } + ); +} From c3b3ac4c7434c84166fb375305325ea54e31e7c8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:17:10 +0000 Subject: [PATCH 10/29] test(sandbox): add tests for openshell sandbox module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/mod_tests.rs | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/mod_tests.rs diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs new file mode 100644 index 00000000000..da9e7342c33 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -0,0 +1,152 @@ +use super::*; +use crate::config::OpenShellRuntimeConfig; +use crate::core::runtime::NoTenant; +use scripted_driver::ScriptedDriver; +use std::collections::HashMap; +use std::ffi::OsString; + +fn embedded(id: &str) -> Tenant { + Tenant { + profile: None, + agent: Some(id.into()), + } +} + +#[test] +fn a_call_without_a_tenant_is_refused() { + let refused = tenant_for_box(Err(NoTenant)).unwrap_err(); + assert_eq!(refused, BoxError::NoTenant); + assert_eq!( + refused.to_string(), + "no tenant scope; refusing to run a command in a shared sandbox" + ); +} + +#[test] +fn the_whole_tenant_keys_the_box_not_just_its_profile() { + assert_eq!(tenant_for_box(Ok(embedded("u1"))), Ok(embedded("u1"))); +} + +#[test] +fn settings_come_from_the_runtime_table() { + let config = OpenShellRuntimeConfig { + image: "registry.example/agent:3".into(), + cpu_millis: 250, + memory_mb: 64, + idle_ttl_secs: 120, + max_live: 4, + }; + + assert_eq!( + BoxSettings::from_config(&config), + Ok(BoxSettings { + image: "registry.example/agent:3".into(), + cpu_millis: 250, + memory_bytes: 64 * 1024 * 1024, + }) + ); + assert_eq!( + RegistryLimits::from_config(&config), + RegistryLimits { + idle_ttl: Duration::from_secs(120), + max_live: 4, + } + ); +} + +#[test] +fn memory_too_large_for_bytes_is_refused() { + let config = OpenShellRuntimeConfig { + memory_mb: u64::MAX, + ..OpenShellRuntimeConfig::default() + }; + let refused = BoxSettings::from_config(&config).unwrap_err(); + assert_eq!(refused, BoxError::InvalidMemory { memory_mb: u64::MAX }); + assert!(refused.to_string().contains("too large")); +} + +#[test] +fn the_command_env_is_only_what_the_request_carries() { + let mut extra = HashMap::new(); + extra.insert(OsString::from("GIT_TERMINAL_PROMPT"), OsString::from("0")); + + let env = box_env(&extra).unwrap(); + + assert_eq!(env.len(), 1); + assert_eq!(env["GIT_TERMINAL_PROMPT"], "0"); +} + +#[cfg(unix)] +#[test] +fn a_non_utf8_env_is_refused_rather_than_altered() { + use std::os::unix::ffi::OsStringExt; + let mut extra = HashMap::new(); + extra.insert(OsString::from("BAD"), OsString::from_vec(vec![0xff])); + + assert_eq!(box_env(&extra).unwrap_err(), BoxError::NonUtf8Env); +} + +#[tokio::test(start_paused = true)] +async fn an_unscoped_command_creates_no_box() { + let driver = ScriptedDriver::new(); + let boxes = BoxRegistry::new( + Arc::clone(&driver), + RegistryLimits::from_config(&OpenShellRuntimeConfig::default()), + ); + + let refused = run_command( + &boxes, + Err(NoTenant), + &OpenShellRuntimeConfig::default(), + "id", + &HashMap::new(), + Duration::from_secs(10), + ) + .await + .unwrap_err(); + + assert_eq!(refused, BoxError::NoTenant); + assert!(driver.calls().is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_scoped_command_runs_in_its_tenants_box() { + let driver = ScriptedDriver::new(); + let config = OpenShellRuntimeConfig::default(); + let boxes = BoxRegistry::new(Arc::clone(&driver), RegistryLimits::from_config(&config)); + + let result = run_command( + &boxes, + Ok(embedded("u1")), + &config, + "id", + &HashMap::new(), + Duration::from_secs(10), + ) + .await + .unwrap(); + + assert_eq!(result.stdout, "ok"); + assert_eq!( + driver.calls()[0], + scripted_driver::Call::Create(BoxSettings::from_config(&config).unwrap()) + ); + let exec = driver.last_exec().unwrap(); + assert_eq!(exec.argv[3], "10"); + assert!(exec.env.is_empty()); +} + +#[cfg(not(feature = "modules"))] +#[tokio::test] +async fn without_module_support_execution_is_refused() { + let error = execute( + &crate::core::runtime::DispatchCtx::unbound(), + &crate::config::Config::default(), + "id", + &HashMap::new(), + Duration::from_secs(1), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("module support is disabled")); +} From 4fad69810481889df177f230234fb00f1a1776cb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:17:23 +0000 Subject: [PATCH 11/29] test(sandbox): cover openshell backend routing and serialization Add tests asserting that an explicit OpenShell selection routes to the OpenShell backend while dropping Docker overrides and host mounts, that OpenShell and Docker require the sandbox while Auto and None do not, and that the OpenShell handle reports Ready without a container id or isolation. Also verify the backend kind serializes to and from the "openshell" wire name. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/sandbox/ops_tests.rs | 56 +++++++++++++++++++ .../openhuman-core/src/sandbox/types_tests.rs | 10 ++++ 2 files changed, 66 insertions(+) diff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rs index 82fa3baadaf..cba350b6ce2 100644 --- a/crates/openhuman-core/src/sandbox/ops_tests.rs +++ b/crates/openhuman-core/src/sandbox/ops_tests.rs @@ -405,3 +405,59 @@ fn config_disables_sandbox_for_legacy_flag_or_component() { config.components.sandbox = false; assert!(config_disables_sandbox(&config)); } + +#[tokio::test] +async fn an_openshell_selection_routes_to_openshell_without_docker_or_host_mounts() { + let config = crate::config::Config::default(); + let mut sandbox = config.sandbox.clone(); + sandbox.backend = SandboxBackend::OpenShell; + let mut policy = resolve_sandbox_policy( + &DispatchCtx::unbound(), + SandboxMode::Sandboxed, + Path::new("/tmp/action"), + Path::new("/tmp/state"), + &RuntimeConfig { + kind: "docker".into(), + ..RuntimeConfig::default() + }, + false, + ); + policy.read_only_mounts.push("/usr/lib".into()); + policy.read_write_mounts.push("/home/u/.cargo".into()); + assert!(policy.docker_overrides.is_some()); + + let explicit = apply_requested_backend(&mut policy, &sandbox, &config.runtime, &config) + .await + .unwrap(); + + assert!(explicit); + assert_eq!(policy.backend, SandboxBackendKind::OpenShell); + assert!(policy.docker_overrides.is_none()); + assert!(policy.read_only_mounts.is_empty()); + assert!(policy.read_write_mounts.is_empty()); +} + +#[test] +fn an_explicit_openshell_backend_requires_the_sandbox() { + assert!(backend_requires_sandbox(&SandboxBackend::OpenShell)); + assert!(backend_requires_sandbox(&SandboxBackend::Docker)); + assert!(!backend_requires_sandbox(&SandboxBackend::Auto)); + assert!(!backend_requires_sandbox(&SandboxBackend::None)); +} + +#[tokio::test] +async fn the_openshell_handle_is_ready_without_pretending_to_be_a_container() { + let policy = SandboxPolicy { + backend: SandboxBackendKind::OpenShell, + ..unsandboxed_policy(Path::new("/tmp/action"), Path::new("/tmp/state")) + }; + + let handle = create_sandbox_backend_with_config(&policy, &crate::config::Config::default()) + .await + .unwrap(); + + assert_eq!(handle.kind, SandboxBackendKind::OpenShell); + assert_eq!(handle.status, SandboxStatus::Ready); + assert_eq!(handle.backend_id, None); + assert_eq!(handle.isolation, None); +} diff --git a/crates/openhuman-core/src/sandbox/types_tests.rs b/crates/openhuman-core/src/sandbox/types_tests.rs index fcbe0f0042e..e300dfebc78 100644 --- a/crates/openhuman-core/src/sandbox/types_tests.rs +++ b/crates/openhuman-core/src/sandbox/types_tests.rs @@ -67,3 +67,13 @@ fn sandbox_status_variants() { assert_ne!(SandboxStatus::Ready, SandboxStatus::Busy); assert_ne!(SandboxStatus::Busy, SandboxStatus::Error); } + +#[test] +fn the_openshell_kind_is_named_openshell_on_the_wire() { + assert_eq!( + serde_json::to_value(SandboxBackendKind::OpenShell).unwrap(), + serde_json::json!("openshell") + ); + let back: SandboxBackendKind = serde_json::from_value(serde_json::json!("openshell")).unwrap(); + assert_eq!(back, SandboxBackendKind::OpenShell); +} From 7525b17d1cc1dc3b102209a25cf312c1a22dd643 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:17:34 +0000 Subject: [PATCH 12/29] test(sandbox): cover openshell backend detection in doctor check Adds a test asserting that a configured OpenShell backend is reported as skipped when its first box is created, and wires the new sandbox test module into the config ops module so it runs. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/config/ops/sandbox.rs | 4 +++ .../src/config/ops/sandbox_tests.rs | 29 +++++++++++++++++++ .../src/doctor/checks/sandbox_tests.rs | 16 ++++++++++ 3 files changed, 49 insertions(+) create mode 100644 crates/openhuman-core/src/config/ops/sandbox_tests.rs diff --git a/crates/openhuman-core/src/config/ops/sandbox.rs b/crates/openhuman-core/src/config/ops/sandbox.rs index 2d908ab0846..d122fa3bdb5 100644 --- a/crates/openhuman-core/src/config/ops/sandbox.rs +++ b/crates/openhuman-core/src/config/ops/sandbox.rs @@ -168,3 +168,7 @@ fn detect_os_sandbox_backend() -> &'static str { "none" } } + +#[cfg(test)] +#[path = "sandbox_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/config/ops/sandbox_tests.rs b/crates/openhuman-core/src/config/ops/sandbox_tests.rs new file mode 100644 index 00000000000..24caf1cc5e1 --- /dev/null +++ b/crates/openhuman-core/src/config/ops/sandbox_tests.rs @@ -0,0 +1,29 @@ +use super::*; +use crate::config::SandboxBackend; + +#[test] +fn every_backend_name_parses_back_to_itself() { + for backend in [ + SandboxBackend::Auto, + SandboxBackend::Landlock, + SandboxBackend::Firejail, + SandboxBackend::Bubblewrap, + SandboxBackend::Docker, + SandboxBackend::OpenShell, + SandboxBackend::None, + ] { + let name = backend_name(&backend); + assert_eq!( + serde_json::to_value(&backend).unwrap(), + serde_json::json!(name) + ); + assert_eq!(backend_name(&parse_backend(name).unwrap()), name); + } +} + +#[test] +fn an_unknown_backend_names_the_valid_ones() { + let refused = parse_backend("vm").unwrap_err(); + assert!(refused.contains("unknown sandbox backend 'vm'")); + assert!(refused.contains("openshell")); +} diff --git a/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs index 9e523ed77d6..ce03d99bbb9 100644 --- a/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs @@ -185,3 +185,19 @@ async fn missing_tinybox_status_does_not_start_the_module_runtime() { crate::modules::types::ModuleState::Available ); } + +#[tokio::test] +async fn a_configured_openshell_backend_is_checked_when_its_first_box_is_created() { + let scratch = tempfile::tempdir().expect("create isolated config fixture"); + let check = SandboxBackendCheck::with_probe(Arc::new(DockerAvailability(false))); + let finding = check + .detect(&DoctorCtx::from_config(config( + scratch.path(), + SandboxBackend::OpenShell, + ))) + .await + .remove(0); + + assert_eq!(finding.severity, FindingSeverity::Skipped); + assert!(finding.message.contains("OpenShell")); +} From 7cc6c52dba78ee2755d6e0318c5905eb35e597c2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:18:38 +0000 Subject: [PATCH 13/29] feat(sandbox): expose openshell module Register the new openshell sandbox backend in the sandbox module tree so its bus driver, registry, and types are reachable from the rest of the crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/mod.rs | 1 + .../src/sandbox/openshell/bus_driver.rs | 4 + .../src/sandbox/openshell/mod.rs | 10 ++ .../src/sandbox/openshell/registry.rs | 4 + .../src/sandbox/openshell/types.rs | 140 ++++++++++++++++++ 5 files changed, 159 insertions(+) create mode 100644 crates/openhuman-core/src/sandbox/openshell/bus_driver.rs create mode 100644 crates/openhuman-core/src/sandbox/openshell/mod.rs create mode 100644 crates/openhuman-core/src/sandbox/openshell/registry.rs create mode 100644 crates/openhuman-core/src/sandbox/openshell/types.rs diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rs index 8e2139b9d1a..eba3b3eb46d 100644 --- a/crates/openhuman-core/src/sandbox/mod.rs +++ b/crates/openhuman-core/src/sandbox/mod.rs @@ -13,6 +13,7 @@ pub mod docker; pub(crate) mod local_grants; pub(crate) mod native_jail; +pub mod openshell; pub mod ops; pub mod schemas; pub(crate) mod shell_exec; diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs new file mode 100644 index 00000000000..db12a65333f --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs @@ -0,0 +1,4 @@ +//! bus driver +#[cfg(test)] +#[path = "bus_driver_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs new file mode 100644 index 00000000000..5fedb4d870b --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -0,0 +1,10 @@ +//! OpenShell boxes, one per tenant. +#[cfg(feature = "modules")] +mod bus_driver; +mod registry; +#[cfg(test)] +#[path = "scripted_driver_fixture.rs"] +pub(crate) mod scripted_driver; +#[cfg(test)] +#[path = "mod_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs new file mode 100644 index 00000000000..8ed42d31fde --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -0,0 +1,4 @@ +//! registry +#[cfg(test)] +#[path = "registry_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/sandbox/openshell/types.rs b/crates/openhuman-core/src/sandbox/openshell/types.rs new file mode 100644 index 00000000000..cc5dd9c3d60 --- /dev/null +++ b/crates/openhuman-core/src/sandbox/openshell/types.rs @@ -0,0 +1,140 @@ +//! The box registry's vocabulary: what a box is created with, the command it +//! runs, what comes back, how it fails, and the [`BoxDriver`] seam that +//! creates, runs and closes boxes. + +use std::collections::BTreeMap; +use std::time::Duration; + +use async_trait::async_trait; + +use crate::config::OpenShellRuntimeConfig; + +/// What a new box is created with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxSettings { + /// OCI image reference the box starts from. + pub image: String, + /// CPU allowance in thousandths of a core. + pub cpu_millis: u32, + /// Memory limit in bytes, always a whole number of mebibytes. + pub memory_bytes: u64, +} + +impl BoxSettings { + /// The settings `[runtime.openshell]` gives every new box. + /// + /// # Errors + /// + /// [`BoxError::InvalidMemory`] when `memory_mb` does not fit in bytes. + pub fn from_config(config: &OpenShellRuntimeConfig) -> Result { + let memory_bytes = config.memory_bytes().ok_or(BoxError::InvalidMemory { + memory_mb: config.memory_mb, + })?; + Ok(Self { + image: config.image.clone(), + cpu_millis: config.cpu_millis, + memory_bytes, + }) + } +} + +/// Registry-wide bounds, fixed when the registry is built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RegistryLimits { + /// How long a box may sit idle before it is closed. + pub idle_ttl: Duration, + /// The most boxes alive at once. + pub max_live: usize, +} + +impl RegistryLimits { + /// The bounds `[runtime.openshell]` sets. + pub fn from_config(config: &OpenShellRuntimeConfig) -> Self { + Self { + idle_ttl: Duration::from_secs(config.idle_ttl_secs), + max_live: config.max_live, + } + } +} + +/// One shell command for a tenant's box. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxRequest { + /// The command line, run with `sh -c`. + pub command: String, + /// The only variables set for the command; nothing from the host. + pub env: BTreeMap, + /// How long the command may run. + pub timeout: Duration, +} + +/// What a driver runs inside a box: the program, already wrapped in the +/// box-side deadline. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxExec { + /// Unshelled program and arguments. + pub argv: Vec, + /// Working directory inside the box. + pub cwd: String, + /// Variables set for the program. + pub env: BTreeMap, + /// When the registry gives up on the reply; a driver's own transport + /// deadline must not fire before it. + pub deadline: Duration, +} + +/// What a command left behind. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxOutput { + /// The program's exit status. + pub exit_code: i32, + /// Standard output, unmodified. + pub stdout: Vec, + /// Standard error, unmodified. + pub stderr: Vec, +} + +/// Why a command could not run in a box. The messages are written to read +/// well as a tool result. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BoxError { + /// Every box is in use and none has been idle long enough to reap. + #[error("the sandbox service is at capacity; try again shortly")] + AtCapacity, + /// The box is gone: closed, lost, or no longer able to run commands. + #[error("the sandbox box is no longer available")] + UnknownResource, + /// The box was released or shut down while the command was waiting on it. + #[error("the sandbox was released while the command was running")] + Released, + /// The call carries no tenant, so it has no box of its own. + #[error("no tenant scope; refusing to run a command in a shared sandbox")] + NoTenant, + /// `[runtime.openshell] memory_mb` is too large to express in bytes. + #[error("sandbox memory of {memory_mb} MiB is too large")] + InvalidMemory { + /// The configured value. + memory_mb: u64, + }, + /// A variable for the command is not UTF-8. + #[error("sandbox environment is not UTF-8")] + NonUtf8Env, + /// The driver failed for another reason. + #[error("the sandbox service failed: {0}")] + Driver(String), +} + +/// Creates, runs and closes boxes. The registry owns their lifecycle; a +/// driver only performs each step. +#[async_trait] +pub trait BoxDriver: Send + Sync + 'static { + /// Create a box and return its resource id. + async fn create(&self, settings: &BoxSettings) -> Result; + + /// Run one program in the box and collect its output. A box that is gone + /// fails with [`BoxError::UnknownResource`]. + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result; + + /// Close the box and release what it holds. + async fn close(&self, resource: &str) -> Result<(), BoxError>; +} From a769cf236677fb872eee1bceb81c6e463095dd18 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:19:20 +0000 Subject: [PATCH 14/29] feat(sandbox): add per-tenant box registry with single-flight creation Introduce a BoxRegistry that keeps one live box per tenant, creating it on first use and reusing it for later commands. Slots are retired when released or reaped so in-flight commands cannot resurrect untracked boxes, and a backstop closes boxes that stop answering past the command deadline. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/registry.rs | 409 +++++++++++++++++- 1 file changed, 408 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs index 8ed42d31fde..eb4995616ff 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -1,4 +1,411 @@ -//! registry +//! [`BoxRegistry`]: one live box per tenant, created on first use, reused, +//! and closed when idle, released, or no longer answering. +//! +//! State lives in one map behind a `std` mutex that is never held across an +//! `.await`. Each tenant's entry counts the commands in flight on it and when +//! it was last used; its [`Slot`] holds the box id and the gate that makes +//! creation single-flight. A slot taken out of the map (released, shut down, +//! reaped) is marked retired, so a command still running on it can never +//! create a box nobody tracks. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard, Once, PoisonError, Weak}; +use std::time::Duration; + +use tokio::time::Instant; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; +use crate::core::runtime::Tenant; +use crate::sandbox::types::SandboxExecResult; + +/// The working directory commands run in: the box's own workspace. +pub(crate) const BOX_WORKDIR: &str = "/sandbox"; + +/// Seconds `timeout` waits after its signal before it kills the command. +const KILL_AFTER_SECS: &str = "5"; + +/// How long past the command's deadline the host waits for the box to answer +/// before it gives the box up. Covers the kill grace above plus the reply. +pub(crate) const BACKSTOP_MARGIN: Duration = Duration::from_secs(10); + +/// The exit status `timeout` reports for a command it stopped. +const TIMED_OUT_EXIT: i32 = 124; + +/// The longest the background reaper waits between passes. +pub(crate) const REAP_EVERY_AT_MOST: Duration = Duration::from_secs(30); + +/// One live box per [`Tenant`], over a [`BoxDriver`]. +pub struct BoxRegistry { + driver: Arc, + limits: RegistryLimits, + entries: Mutex>, + reaper: Once, +} + +struct Entry { + slot: Arc, + in_flight: usize, + last_used: Instant, +} + +#[derive(Default)] +struct Slot { + /// Held while the box is created, so concurrent first commands make one. + create_gate: tokio::sync::Mutex<()>, + state: Mutex, +} + +#[derive(Default)] +struct SlotState { + resource: Option, + retired: bool, +} + +impl Slot { + fn state(&self) -> MutexGuard<'_, SlotState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn current(&self) -> Result, BoxError> { + let state = self.state(); + if state.retired { + return Err(BoxError::Released); + } + Ok(state.resource.clone()) + } + + /// Record a new box; `false` when the slot was retired meanwhile. + fn store(&self, resource: &str) -> bool { + let mut state = self.state(); + if state.retired { + return false; + } + state.resource = Some(resource.to_owned()); + true + } + + /// Drop `resource` if it is still the slot's box. + fn forget(&self, resource: &str) { + let mut state = self.state(); + if state.resource.as_deref() == Some(resource) { + state.resource = None; + } + } + + /// Retire the slot and hand back its box to close. + fn retire(&self) -> Option { + let mut state = self.state(); + state.retired = true; + state.resource.take() + } +} + +/// A command's hold on its tenant's entry; dropping it (finished or +/// abandoned) ends the hold and touches the entry. +struct Lease<'a, D: BoxDriver> { + registry: &'a BoxRegistry, + tenant: Tenant, + slot: Arc, +} + +impl Drop for Lease<'_, D> { + fn drop(&mut self) { + self.registry.check_in(&self.tenant, &self.slot); + } +} + +enum Run { + Finished(BoxOutput), + BackstopFired, +} + +impl BoxRegistry { + /// A registry with no boxes yet. Call [`Self::start_reaper`] to close + /// idle boxes in the background. + pub fn new(driver: Arc, limits: RegistryLimits) -> Arc { + Arc::new(Self { + driver, + limits, + entries: Mutex::new(HashMap::new()), + reaper: Once::new(), + }) + } + + /// How many tenants hold a box (or are creating one). + pub fn live(&self) -> usize { + self.entries().len() + } + + /// Run `request` in `tenant`'s box, creating the box first if it has none. + /// + /// A box the driver reports gone is replaced once and the command retried. + /// A box that does not answer by the command's deadline plus + /// [`BACKSTOP_MARGIN`] is closed, and the command reported as timed out. + /// + /// # Errors + /// + /// [`BoxError::AtCapacity`] when a new box would exceed `max_live`, and + /// any creation or execution failure from the driver. + pub async fn exec( + &self, + tenant: &Tenant, + settings: &BoxSettings, + request: &BoxRequest, + ) -> Result { + let lease = self.check_out(tenant).await?; + let mut replaced = false; + loop { + let resource = self.resource_for(&lease.slot, settings).await?; + match self.run(&resource, request).await { + Ok(Run::Finished(output)) => return Ok(finished(output)), + Ok(Run::BackstopFired) => { + tracing::warn!( + timeout_secs = whole_seconds(request.timeout), + "[sandbox:openshell] box did not answer by the deadline; closing it" + ); + lease.slot.forget(&resource); + self.close_quietly(&resource).await; + return Ok(backstop_timed_out(request.timeout)); + } + Err(BoxError::UnknownResource) => { + lease.slot.forget(&resource); + if replaced { + return Err(BoxError::UnknownResource); + } + tracing::warn!("[sandbox:openshell] box is gone; retrying in a new box"); + replaced = true; + } + Err(error) => return Err(error), + } + } + } + + /// Close every box idle since `now - idle_ttl` or earlier with no command + /// in flight; returns how many were closed. + pub async fn reap(&self, now: Instant) -> usize { + let idle = self.take_idle(&mut self.entries(), now); + let closed = idle.len(); + for resource in idle { + self.close_quietly(&resource).await; + } + if closed > 0 { + tracing::debug!(closed, "[sandbox:openshell] reaped idle boxes"); + } + closed + } + + /// Close `tenant`'s box, if it has one. A command still running in it + /// fails rather than starting another box. + pub async fn release(&self, tenant: &Tenant) { + let resource = self + .entries() + .remove(tenant) + .and_then(|entry| entry.slot.retire()); + if let Some(resource) = resource { + self.close_quietly(&resource).await; + } + } + + /// Close every box. + pub async fn shutdown(&self) { + let resources: Vec = self + .entries() + .drain() + .filter_map(|(_, entry)| entry.slot.retire()) + .collect(); + for resource in resources { + self.close_quietly(&resource).await; + } + } + + /// Start the background reaper, once; it stops when the registry drops. + pub fn start_reaper(self: &Arc) { + self.reaper.call_once(|| { + let registry: Weak = Arc::downgrade(self); + let every = reap_interval(self.limits.idle_ttl); + tokio::spawn(async move { + let mut ticks = tokio::time::interval(every); + ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + ticks.tick().await; + let Some(registry) = registry.upgrade() else { + return; + }; + registry.reap(Instant::now()).await; + } + }); + }); + } + + fn entries(&self) -> MutexGuard<'_, HashMap> { + self.entries.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Hold `tenant`'s entry, making one when it has none and there is room. + async fn check_out(&self, tenant: &Tenant) -> Result, BoxError> { + let now = Instant::now(); + let (slot, reaped) = { + let mut entries = self.entries(); + let mut reaped = Vec::new(); + if !entries.contains_key(tenant) && entries.len() >= self.limits.max_live { + reaped = self.take_idle(&mut entries, now); + if entries.len() >= self.limits.max_live { + drop(entries); + tracing::warn!( + max_live = self.limits.max_live, + "[sandbox:openshell] refusing a new box: at capacity" + ); + for resource in reaped { + self.close_quietly(&resource).await; + } + return Err(BoxError::AtCapacity); + } + } + let entry = entries.entry(tenant.clone()).or_insert_with(|| Entry { + slot: Arc::new(Slot::default()), + in_flight: 0, + last_used: now, + }); + entry.in_flight += 1; + entry.last_used = now; + (Arc::clone(&entry.slot), reaped) + }; + for resource in reaped { + self.close_quietly(&resource).await; + } + Ok(Lease { + registry: self, + tenant: tenant.clone(), + slot, + }) + } + + /// End a command's hold; an entry left with no box and no command goes. + fn check_in(&self, tenant: &Tenant, slot: &Arc) { + let mut entries = self.entries(); + let Some(entry) = entries.get_mut(tenant) else { + return; + }; + if !Arc::ptr_eq(&entry.slot, slot) { + return; + } + entry.in_flight = entry.in_flight.saturating_sub(1); + entry.last_used = Instant::now(); + if entry.in_flight == 0 && entry.slot.state().resource.is_none() { + entries.remove(tenant); + } + } + + /// Remove idle entries and return their boxes to close. + fn take_idle(&self, entries: &mut HashMap, now: Instant) -> Vec { + let ttl = self.limits.idle_ttl; + let mut resources = Vec::new(); + entries.retain(|_, entry| { + let idle = + entry.in_flight == 0 && now.saturating_duration_since(entry.last_used) >= ttl; + if idle { + resources.extend(entry.slot.retire()); + } + !idle + }); + resources + } + + /// The slot's box, created now if it has none. + async fn resource_for(&self, slot: &Slot, settings: &BoxSettings) -> Result { + if let Some(resource) = slot.current()? { + return Ok(resource); + } + let _creating = slot.create_gate.lock().await; + if let Some(resource) = slot.current()? { + return Ok(resource); + } + tracing::debug!(image = %settings.image, "[sandbox:openshell] creating a box"); + let resource = self.driver.create(settings).await?; + if !slot.store(&resource) { + self.close_quietly(&resource).await; + return Err(BoxError::Released); + } + tracing::debug!(resource = %resource, "[sandbox:openshell] box ready"); + Ok(resource) + } + + async fn run(&self, resource: &str, request: &BoxRequest) -> Result { + let secs = whole_seconds(request.timeout); + let deadline = Duration::from_secs(secs).saturating_add(BACKSTOP_MARGIN); + let exec = BoxExec { + argv: timeout_argv(secs, &request.command), + cwd: BOX_WORKDIR.to_owned(), + env: request.env.clone(), + deadline, + }; + match tokio::time::timeout(deadline, self.driver.exec(resource, &exec)).await { + Ok(output) => output.map(Run::Finished), + Err(_) => Ok(Run::BackstopFired), + } + } + + async fn close_quietly(&self, resource: &str) { + if let Err(error) = self.driver.close(resource).await { + tracing::warn!( + resource = %resource, + error = %error, + "[sandbox:openshell] closing a box failed" + ); + } + } +} + +/// `timeout -k 5 sh -c `: the box stops the command itself. +fn timeout_argv(secs: u64, command: &str) -> Vec { + [ + "timeout", + "-k", + KILL_AFTER_SECS, + &secs.to_string(), + "sh", + "-c", + command, + ] + .map(str::to_owned) + .to_vec() +} + +/// `timeout` counts whole seconds: round up, and never ask for none. +pub(crate) fn whole_seconds(timeout: Duration) -> u64 { + let secs = timeout.as_secs() + u64::from(timeout.subsec_nanos() > 0); + secs.max(1) +} + +/// Half the TTL, at most [`REAP_EVERY_AT_MOST`], at least a second. +pub(crate) fn reap_interval(idle_ttl: Duration) -> Duration { + (idle_ttl / 2) + .min(REAP_EVERY_AT_MOST) + .max(Duration::from_secs(1)) +} + +/// A command's output as a sandbox result; exit 124 is `timeout` stopping it. +pub(crate) fn finished(output: BoxOutput) -> SandboxExecResult { + SandboxExecResult { + exit_code: output.exit_code, + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + timed_out: output.exit_code == TIMED_OUT_EXIT, + } +} + +fn backstop_timed_out(timeout: Duration) -> SandboxExecResult { + SandboxExecResult { + exit_code: TIMED_OUT_EXIT, + stdout: String::new(), + stderr: format!( + "the command did not finish within {}s and its sandbox was discarded", + whole_seconds(timeout) + ), + timed_out: true, + } +} + #[cfg(test)] #[path = "registry_tests.rs"] mod tests; From 6a9d623299a2bf58cddd551a64e4616b9612f538 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:19:38 +0000 Subject: [PATCH 15/29] refactor(sandbox): extract box checkout bookkeeping into a hold helper Moved the entry lookup, idle reaping, and in-flight counting out of check_out into a dedicated hold method that returns the slot or a capacity signal along with the reaped boxes. This keeps the async checkout path focused on closing reaped boxes and building the lease while the synchronous bookkeeping stays in one place. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/registry.rs | 57 ++++++++++--------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs index eb4995616ff..f1ca868ba8a 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -243,36 +243,17 @@ impl BoxRegistry { /// Hold `tenant`'s entry, making one when it has none and there is room. async fn check_out(&self, tenant: &Tenant) -> Result, BoxError> { - let now = Instant::now(); - let (slot, reaped) = { - let mut entries = self.entries(); - let mut reaped = Vec::new(); - if !entries.contains_key(tenant) && entries.len() >= self.limits.max_live { - reaped = self.take_idle(&mut entries, now); - if entries.len() >= self.limits.max_live { - drop(entries); - tracing::warn!( - max_live = self.limits.max_live, - "[sandbox:openshell] refusing a new box: at capacity" - ); - for resource in reaped { - self.close_quietly(&resource).await; - } - return Err(BoxError::AtCapacity); - } - } - let entry = entries.entry(tenant.clone()).or_insert_with(|| Entry { - slot: Arc::new(Slot::default()), - in_flight: 0, - last_used: now, - }); - entry.in_flight += 1; - entry.last_used = now; - (Arc::clone(&entry.slot), reaped) - }; + let (held, reaped) = self.hold(tenant, Instant::now()); for resource in reaped { self.close_quietly(&resource).await; } + let Some(slot) = held else { + tracing::warn!( + max_live = self.limits.max_live, + "[sandbox:openshell] refusing a new box: at capacity" + ); + return Err(BoxError::AtCapacity); + }; Ok(Lease { registry: self, tenant: tenant.clone(), @@ -280,6 +261,28 @@ impl BoxRegistry { }) } + /// Count a command against `tenant`'s entry, making the entry when there + /// is room (after reaping idle boxes if there is not). Returns the slot, + /// or `None` at capacity, and the reaped boxes to close. + fn hold(&self, tenant: &Tenant, now: Instant) -> (Option>, Vec) { + let mut entries = self.entries(); + let mut reaped = Vec::new(); + if !entries.contains_key(tenant) && entries.len() >= self.limits.max_live { + reaped = self.take_idle(&mut entries, now); + if entries.len() >= self.limits.max_live { + return (None, reaped); + } + } + let entry = entries.entry(tenant.clone()).or_insert_with(|| Entry { + slot: Arc::new(Slot::default()), + in_flight: 0, + last_used: now, + }); + entry.in_flight += 1; + entry.last_used = now; + (Some(Arc::clone(&entry.slot)), reaped) + } + /// End a command's hold; an entry left with no box and no command goes. fn check_in(&self, tenant: &Tenant, slot: &Arc) { let mut entries = self.entries(); From 6a13eeaa79d29acb7bdc57fe1776aaa0cd780228 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:19:46 +0000 Subject: [PATCH 16/29] feat(tinybox): add exec_within with caller-supplied deadline Adds an exec variant that applies a caller-provided timeout to the module client, so long-running commands can be bounded by the caller's own deadline rather than the default module call timeout. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/modules/tinybox/operations.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/openhuman-core/src/modules/tinybox/operations.rs b/crates/openhuman-core/src/modules/tinybox/operations.rs index 5b452ce02ee..702e905b55c 100644 --- a/crates/openhuman-core/src/modules/tinybox/operations.rs +++ b/crates/openhuman-core/src/modules/tinybox/operations.rs @@ -124,6 +124,17 @@ pub async fn exec( call(config, EXEC, (request,), true).await } +/// [`exec`] that waits up to `deadline` for the reply instead of the module +/// call default, for a long command whose caller enforces its own deadline. +pub async fn exec_within( + config: &Config, + request: contract::ExecRequest, + deadline: Duration, +) -> Result { + let client = crate::modules::client(config.clone()).with_timeout(deadline); + call_with_client(&client, EXEC, (request,), true).await +} + /// Inspect a module-owned resource. pub async fn inspect( config: &Config, From ccce54c60a8fccc11ccfa4e81b20ab99fe30a849 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:20:02 +0000 Subject: [PATCH 17/29] feat(sandbox): add bus-backed box driver for openshell Implement BusBoxDriver so boxes are created, executed, and closed through the TinyBox module's openshell backend. A failed exec is followed by an Inspect probe so boxes the module no longer knows are reported as unknown resources, letting the registry replace them. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/bus_driver.rs | 139 +++++++++++++++++- 1 file changed, 138 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs index db12a65333f..c63a25178ac 100644 --- a/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs +++ b/crates/openhuman-core/src/sandbox/openshell/bus_driver.rs @@ -1,4 +1,141 @@ -//! bus driver +//! [`BusBoxDriver`]: boxes through the TinyBox module's `openshell` backend. +//! +//! Each step is one bus call (`Reserve` + `Create`, `Exec`, `Close`). The +//! module's error names do not cross the bus client (it reports only +//! sanitized categories), so a failed exec is followed by an `Inspect`: a box +//! the module no longer knows, or one that can no longer take commands, is +//! [`BoxError::UnknownResource`], which the registry answers with a new box. + +use std::time::Duration; + +use async_trait::async_trait; + +use super::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxSettings}; +use crate::config::Config; +use crate::modules::tinybox::{self, contract}; + +/// The TinyBox backend name for OpenShell boxes. +pub(crate) const BACKEND: &str = "openshell"; + +/// How long past the registry's own deadline the bus waits for an exec reply, +/// so the registry's backstop always decides first. +pub(crate) const BUS_REPLY_GRACE: Duration = Duration::from_secs(5); + +/// Box states that still take commands. +const LIVE_STATES: &[&str] = &["ready", "running"]; + +/// A [`BoxDriver`] over the TinyBox module, using the module configuration it +/// was built with. +pub struct BusBoxDriver { + config: Config, +} + +impl BusBoxDriver { + /// A driver that reaches the module with `config`'s module settings. + pub fn new(config: Config) -> Self { + Self { config } + } +} + +#[async_trait] +impl BoxDriver for BusBoxDriver { + async fn create(&self, settings: &BoxSettings) -> Result { + let resource = tinybox::reserve(&self.config, contract::ReserveRequest::Resource) + .await + .map_err(BoxError::Driver)?; + let info = tinybox::create(&self.config, create_request(resource, settings)) + .await + .map_err(BoxError::Driver)?; + Ok(info.resource.0) + } + + async fn exec(&self, resource: &str, exec: &BoxExec) -> Result { + match tinybox::exec_within( + &self.config, + exec_request(resource, exec), + bus_deadline(exec.deadline), + ) + .await + { + Ok(output) => Ok(box_output(output)), + Err(error) => { + let probe = + tinybox::inspect(&self.config, contract::ResourceId(resource.to_owned())).await; + Err(exec_failure(error, probe)) + } + } + } + + async fn close(&self, resource: &str) -> Result<(), BoxError> { + tinybox::close(&self.config, contract::ResourceId(resource.to_owned())) + .await + .map_err(BoxError::Driver) + } +} + +/// An OpenShell box: the image, no network, no published ports, and no +/// environment from the host. +pub(crate) fn create_request( + resource: contract::ResourceId, + settings: &BoxSettings, +) -> contract::CreateRequest { + contract::CreateRequest { + resource, + backend: BACKEND.to_owned(), + host: contract::HostConfig::Local, + workspace: contract::Workspace::Image(settings.image.clone()), + network: contract::NetworkPolicy::Denied, + resources: contract::ResourceLimits { + cpu_millis: settings.cpu_millis, + memory_bytes: settings.memory_bytes, + ..contract::ResourceLimits::default() + }, + ports: Vec::new(), + env: std::collections::BTreeMap::new(), + } +} + +pub(crate) fn exec_request(resource: &str, exec: &BoxExec) -> contract::ExecRequest { + contract::ExecRequest { + resource: contract::ResourceId(resource.to_owned()), + argv: exec.argv.clone(), + cwd: Some(exec.cwd.clone()), + env: exec.env.clone(), + stdin: None, + } +} + +pub(crate) fn bus_deadline(registry_deadline: Duration) -> Duration { + registry_deadline.saturating_add(BUS_REPLY_GRACE) +} + +/// Classify a failed exec by what `Inspect` says about its box afterwards. +pub(crate) fn exec_failure( + exec_error: String, + probe: Result, +) -> BoxError { + let gone = match probe { + Ok(info) => !LIVE_STATES.contains(&info.state.as_str()), + // The module answered and refused: it holds no such box. + Err(probe_error) => { + probe_error == tinybus::module::ModuleCallError::ModuleFault.to_string() + } + }; + if gone { + BoxError::UnknownResource + } else { + BoxError::Driver(exec_error) + } +} + +pub(crate) fn box_output(output: contract::ExecOutput) -> BoxOutput { + BoxOutput { + exit_code: output.exit_code, + stdout: output.stdout, + stderr: output.stderr, + } +} + #[cfg(test)] #[path = "bus_driver_tests.rs"] mod tests; From eb1968b599da78ddcc7cfd431a6202956dba717c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:20:28 +0000 Subject: [PATCH 18/29] feat(sandbox): add openshell backend with per-tenant box registry Wire up the OpenShell sandbox backend so sandboxed shell commands run in a long-lived box per tenant instead of a fresh container per command, letting files persist across invocations. The registry creates one box per tenant, reaps idle boxes, caps live boxes, and refuses commands with no tenant scope. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/mod.rs | 168 +++++++++++++++++- 1 file changed, 167 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index 5fedb4d870b..190727922e5 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -1,10 +1,176 @@ -//! OpenShell boxes, one per tenant. +//! The OpenShell sandbox backend: one long-lived box per tenant. +//! +//! With `[security.sandbox] backend = "openshell"`, a sandboxed shell command +//! runs in a box the TinyBox module creates on an NVIDIA OpenShell gateway +//! (`[runtime.openshell]`). Unlike the Docker backend, which starts a +//! container per command, a box outlives the command: [`BoxRegistry`] keeps +//! one per [`Tenant`], so files a command writes are there for the next one. +//! +//! - **Keyed on the whole tenant.** An embedded host runs one agent per end +//! user with no profile, so keying on the profile alone would put every user +//! in one box. A call with no tenant ([`NoTenant`]) is refused, never sent +//! to a shared box. +//! - **Created once, reused, reaped.** Concurrent first commands make one box. +//! A box idle for `idle_ttl_secs` is closed by a background reaper, and +//! `max_live` caps the boxes alive at once. +//! - **The box enforces the deadline.** Commands run as +//! `timeout -k 5 sh -c ` in `/sandbox`, with only the +//! variables the request carries. A box that does not answer shortly after +//! the deadline is closed and the command reported as timed out. +//! +//! [`BoxDriver`] is the seam: [`BusBoxDriver`] reaches the TinyBox module +//! (behind the `modules` feature); tests use a scripted stand-in. The process +//! holds one registry, built from the config of the first command that needs +//! it, so `idle_ttl_secs` and `max_live` changes take effect on restart. + #[cfg(feature = "modules")] mod bus_driver; mod registry; +mod types; + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::OsString; +use std::sync::Arc; +use std::time::Duration; + +#[cfg(feature = "modules")] +pub use bus_driver::BusBoxDriver; +pub use registry::BoxRegistry; +pub use types::{ + BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits, +}; + +use super::types::SandboxExecResult; +use crate::config::{Config, OpenShellRuntimeConfig}; +use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; + +/// The tenant a box is kept for: the call's whole tenant, or a refusal. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] when the call carries no tenant. +pub fn tenant_for_box(tenant: Result) -> Result { + tenant.map_err(|NoTenant| { + tracing::warn!("[sandbox:openshell] refusing a command with no tenant scope"); + BoxError::NoTenant + }) +} + +/// The command's variables as UTF-8, refusing any that are not. +/// +/// # Errors +/// +/// [`BoxError::NonUtf8Env`] when a name or value is not UTF-8. +pub fn box_env(extra_env: &HashMap) -> Result, BoxError> { + extra_env + .iter() + .map(|(name, value)| match (name.to_str(), value.to_str()) { + (Some(name), Some(value)) => Ok((name.to_owned(), value.to_owned())), + _ => Err(BoxError::NonUtf8Env), + }) + .collect() +} + +/// Run `command` in the box of the tenant `tenant` resolves to. +/// +/// # Errors +/// +/// [`BoxError::NoTenant`] before any box is touched when there is no tenant; +/// otherwise the settings, environment and registry errors. +pub async fn run_command( + registry: &BoxRegistry, + tenant: Result, + openshell: &OpenShellRuntimeConfig, + command: &str, + extra_env: &HashMap, + timeout: Duration, +) -> Result { + let tenant = tenant_for_box(tenant)?; + let settings = BoxSettings::from_config(openshell)?; + let request = BoxRequest { + command: command.to_owned(), + env: box_env(extra_env)?, + timeout, + }; + registry.exec(&tenant, &settings, &request).await +} + +#[cfg(feature = "modules")] +static REGISTRY: std::sync::OnceLock>> = std::sync::OnceLock::new(); + +/// The process's registry, built (and its reaper started) on first use. +#[cfg(feature = "modules")] +fn registry(config: &Config) -> &'static Arc> { + let registry = REGISTRY.get_or_init(|| { + BoxRegistry::new( + Arc::new(BusBoxDriver::new(config.clone())), + RegistryLimits::from_config(&config.runtime.openshell), + ) + }); + registry.start_reaper(); + registry +} + +/// Run a sandboxed shell command in the calling tenant's OpenShell box. +/// +/// # Errors +/// +/// Every [`BoxError`], and a refusal when this build has no module support. +pub(crate) async fn execute( + ctx: &DispatchCtx, + config: &Config, + command: &str, + extra_env: &HashMap, + timeout: Duration, +) -> anyhow::Result { + #[cfg(feature = "modules")] + { + tracing::debug!( + timeout_secs = timeout.as_secs(), + "[sandbox:openshell] running a command" + ); + run_command( + registry(config), + ctx.tenant(), + &config.runtime.openshell, + command, + extra_env, + timeout, + ) + .await + .map_err(anyhow::Error::from) + } + #[cfg(not(feature = "modules"))] + { + let _ = (ctx, config, command, extra_env, timeout); + anyhow::bail!( + "TinyBox module support is disabled; OpenShell sandbox execution is unavailable" + ) + } +} + +/// Close `tenant`'s box, if the process has one. +pub async fn release(tenant: &Tenant) { + #[cfg(feature = "modules")] + if let Some(registry) = REGISTRY.get() { + registry.release(tenant).await; + } + #[cfg(not(feature = "modules"))] + let _ = tenant; +} + +/// Close every box the process holds. +pub async fn shutdown() { + #[cfg(feature = "modules")] + if let Some(registry) = REGISTRY.get() { + registry.shutdown().await; + } +} + #[cfg(test)] #[path = "scripted_driver_fixture.rs"] pub(crate) mod scripted_driver; + #[cfg(test)] #[path = "mod_tests.rs"] mod tests; From 4ab3c3ebb759f822b1faa1a07a1e3491d0e787c5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:22:31 +0000 Subject: [PATCH 19/29] feat(sandbox): add openshell backend support Add an OpenShell variant to the sandbox backend enum and wire it through settings parsing, doctor checks, and backend selection. Backend name mapping is now shared between reading and applying settings so the new variant is accepted consistently, and OpenShell counts as an explicit isolation requirement when deciding whether a command needs sandboxing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/config/ops/sandbox.rs | 58 ++++++++++++------- .../src/doctor/checks/sandbox.rs | 5 ++ crates/openhuman-core/src/sandbox/ops.rs | 45 +++++++++++++- crates/openhuman-core/src/sandbox/types.rs | 3 + 4 files changed, 86 insertions(+), 25 deletions(-) diff --git a/crates/openhuman-core/src/config/ops/sandbox.rs b/crates/openhuman-core/src/config/ops/sandbox.rs index d122fa3bdb5..0923685069c 100644 --- a/crates/openhuman-core/src/config/ops/sandbox.rs +++ b/crates/openhuman-core/src/config/ops/sandbox.rs @@ -31,14 +31,7 @@ pub async fn get_sandbox_settings(ctx: &DispatchCtx) -> Result "auto", - crate::config::SandboxBackend::Landlock => "landlock", - crate::config::SandboxBackend::Firejail => "firejail", - crate::config::SandboxBackend::Bubblewrap => "bubblewrap", - crate::config::SandboxBackend::Docker => "docker", - crate::config::SandboxBackend::None => "none", - }; + let backend_str = backend_name(&sandbox.backend); let detected_backend = detect_os_sandbox_backend(); @@ -59,25 +52,46 @@ pub async fn get_sandbox_settings(ctx: &DispatchCtx) -> Result &'static str { + use crate::config::SandboxBackend; + match backend { + SandboxBackend::Auto => "auto", + SandboxBackend::Landlock => "landlock", + SandboxBackend::Firejail => "firejail", + SandboxBackend::Bubblewrap => "bubblewrap", + SandboxBackend::Docker => "docker", + SandboxBackend::OpenShell => "openshell", + SandboxBackend::None => "none", + } +} + +/// The backend a settings name selects. +fn parse_backend(name: &str) -> Result { + use crate::config::SandboxBackend; + Ok(match name { + "auto" => SandboxBackend::Auto, + "landlock" => SandboxBackend::Landlock, + "firejail" => SandboxBackend::Firejail, + "bubblewrap" => SandboxBackend::Bubblewrap, + "docker" => SandboxBackend::Docker, + "openshell" => SandboxBackend::OpenShell, + "none" => SandboxBackend::None, + other => { + log::warn!("[config][sandbox] rejected unknown backend: {other}"); + return Err(format!( + "unknown sandbox backend '{other}'; valid: auto, landlock, firejail, bubblewrap, docker, openshell, none" + )); + } + }) +} + pub async fn apply_sandbox_settings( config: &mut Config, update: SandboxSettingsPatch, ) -> Result, String> { if let Some(ref backend) = update.backend { - config.sandbox.backend = match backend.as_str() { - "auto" => crate::config::SandboxBackend::Auto, - "landlock" => crate::config::SandboxBackend::Landlock, - "firejail" => crate::config::SandboxBackend::Firejail, - "bubblewrap" => crate::config::SandboxBackend::Bubblewrap, - "docker" => crate::config::SandboxBackend::Docker, - "none" => crate::config::SandboxBackend::None, - other => { - log::warn!("[config][sandbox] rejected unknown backend: {other}"); - return Err(format!( - "unknown sandbox backend '{other}'; valid: auto, landlock, firejail, bubblewrap, docker, none" - )); - } - }; + config.sandbox.backend = parse_backend(backend)?; } if let Some(enabled) = update.enabled { config.sandbox.enabled = Some(enabled); diff --git a/crates/openhuman-core/src/doctor/checks/sandbox.rs b/crates/openhuman-core/src/doctor/checks/sandbox.rs index 68fcb258940..6c6da9484f2 100644 --- a/crates/openhuman-core/src/doctor/checks/sandbox.rs +++ b/crates/openhuman-core/src/doctor/checks/sandbox.rs @@ -149,6 +149,11 @@ impl SandboxBackendCheck { "Review the sandbox runtime and rerun doctor.", ), }, + SandboxBackend::OpenShell => Finding::skipped( + "sandbox/backend", + "The OpenShell backend is configured; its gateway is reached when a tenant's first box is created.", + "Run a sandboxed command to confirm the OpenShell gateway accepts new boxes.", + ), SandboxBackend::Firejail | SandboxBackend::Bubblewrap => Finding::error( "sandbox/backend", "The configured sandbox backend is not supported by this build.", diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs index 0f0fb17ce55..6cc07bd0f8c 100644 --- a/crates/openhuman-core/src/sandbox/ops.rs +++ b/crates/openhuman-core/src/sandbox/ops.rs @@ -66,13 +66,20 @@ pub async fn command_requires_sandbox( if config_disables_sandbox(&config) { return Ok(false); } - Ok(matches!( - config.sandbox.backend, + Ok(backend_requires_sandbox(&config.sandbox.backend)) +} + +/// Whether the operator's backend selection is an explicit isolation +/// requirement, rather than leaving the choice to the agent's mode. +pub(crate) fn backend_requires_sandbox(backend: &SandboxBackend) -> bool { + matches!( + backend, SandboxBackend::Landlock | SandboxBackend::Firejail | SandboxBackend::Bubblewrap | SandboxBackend::Docker - )) + | SandboxBackend::OpenShell + ) } /// Resolve the policy for a command tool before building its command line. @@ -283,6 +290,14 @@ pub async fn create_sandbox_backend_with_config( }) } SandboxBackendKind::Docker => docker::docker_backend_handle(config).await, + // A box is created on a tenant's first command, so there is nothing + // to probe or name yet; the gateway's availability shows on that call. + SandboxBackendKind::OpenShell => Ok(SandboxBackendHandle { + kind: SandboxBackendKind::OpenShell, + status: SandboxStatus::Ready, + backend_id: None, + isolation: None, + }), } } @@ -460,6 +475,23 @@ pub(crate) async fn execute_in_sandbox_yielding( .await .map(ShellRunOutcome::Finished) } + // The box has its own workspace (`/sandbox`); no host path or host + // variable is sent, only the request's own environment. A box cannot + // hand back a running command, so the come-back time is a deadline. + SandboxBackendKind::OpenShell => { + let timeout = come_back + .deadline_instead + .map_or(timeout, |deadline| timeout.min(deadline)); + let config = match module_config { + Some(config) => config, + None => ctx.load_config().await.map_err(|error| { + anyhow::anyhow!("Cannot read module configuration: {error}") + })?, + }; + super::openshell::execute(ctx, &config, command, &extra_env, timeout) + .await + .map(ShellRunOutcome::Finished) + } } } @@ -491,6 +523,13 @@ pub(crate) async fn apply_requested_backend( }); Ok(true) } + SandboxBackend::OpenShell => { + policy.backend = SandboxBackendKind::OpenShell; + policy.docker_overrides = None; + policy.read_only_mounts.clear(); + policy.read_write_mounts.clear(); + Ok(true) + } SandboxBackend::Landlock => { super::native_jail::require_backend(config, "landlock").await?; policy.backend = SandboxBackendKind::Local; diff --git a/crates/openhuman-core/src/sandbox/types.rs b/crates/openhuman-core/src/sandbox/types.rs index 4c8d167a5c0..f13be548cd5 100644 --- a/crates/openhuman-core/src/sandbox/types.rs +++ b/crates/openhuman-core/src/sandbox/types.rs @@ -15,6 +15,9 @@ pub enum SandboxBackendKind { Local, /// Docker container isolation. Docker, + /// The tenant's long-lived OpenShell box (`sandbox::openshell`). + #[serde(rename = "openshell")] + OpenShell, } /// Per-session sandbox policy resolved from agent definition, session From 7b51ad9f0c7ff7d231fba12b80fe9d8e852a3be3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:23:07 +0000 Subject: [PATCH 20/29] style: apply rustfmt formatting to openshell sandbox and config modules Reformatted import lists, long function signatures, and test assertions to satisfy rustfmt line-width rules. No behaviour changed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/config/mod.rs | 5 ++--- .../openhuman-core/src/config/schema/runtime_openshell.rs | 3 ++- crates/openhuman-core/src/sandbox/openshell/mod.rs | 8 ++++---- crates/openhuman-core/src/sandbox/openshell/mod_tests.rs | 7 ++++++- .../src/sandbox/openshell/registry_tests.rs | 5 ++++- 5 files changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs index 6ce414ed2fe..7ec696eb474 100644 --- a/crates/openhuman-core/src/config/mod.rs +++ b/crates/openhuman-core/src/config/mod.rs @@ -53,11 +53,10 @@ pub use schema::{ DockerRuntimeConfig, EmailConfig, EmbeddingRouteConfig, GitbooksConfig, HttpHeader, HttpRequestConfig, IMessageConfig, IntegrationToggle, IntegrationsConfig, LarkConfig, LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, McpAuthConfig, McpClientConfig, - OpenShellRuntimeConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, ObservabilityConfig, - OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, ProviderRoute, - ProxyConfig, ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, + OpenShellRuntimeConfig, OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, + ProviderRoute, ProxyConfig, ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, SandboxBackend, SandboxConfig, SchedulerConfig, SchedulerGateConfig, SchedulerGateMode, SearchConfig, SearchEngineCredentials, SearchHostCredential, SearchProviderSettings, SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StreamMode, SttEngine, diff --git a/crates/openhuman-core/src/config/schema/runtime_openshell.rs b/crates/openhuman-core/src/config/schema/runtime_openshell.rs index 40b693ed07f..16ff7a8412d 100644 --- a/crates/openhuman-core/src/config/schema/runtime_openshell.rs +++ b/crates/openhuman-core/src/config/schema/runtime_openshell.rs @@ -15,7 +15,8 @@ use serde::{Deserialize, Serialize}; /// The image a box starts from when none is configured: the OpenShell /// community base sandbox, which carries the `/sandbox` workspace, `sh` and /// `timeout` the backend relies on. -pub const DEFAULT_OPENSHELL_IMAGE: &str = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest"; +pub const DEFAULT_OPENSHELL_IMAGE: &str = + "ghcr.io/nvidia/openshell-community/sandboxes/base:latest"; const MEBIBYTE: u64 = 1024 * 1024; diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index 190727922e5..fb191dcb370 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -36,9 +36,7 @@ use std::time::Duration; #[cfg(feature = "modules")] pub use bus_driver::BusBoxDriver; pub use registry::BoxRegistry; -pub use types::{ - BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits, -}; +pub use types::{BoxDriver, BoxError, BoxExec, BoxOutput, BoxRequest, BoxSettings, RegistryLimits}; use super::types::SandboxExecResult; use crate::config::{Config, OpenShellRuntimeConfig}; @@ -61,7 +59,9 @@ pub fn tenant_for_box(tenant: Result) -> Result) -> Result, BoxError> { +pub fn box_env( + extra_env: &HashMap, +) -> Result, BoxError> { extra_env .iter() .map(|(name, value)| match (name.to_str(), value.to_str()) { diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs index da9e7342c33..a0cfd448a4c 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -61,7 +61,12 @@ fn memory_too_large_for_bytes_is_refused() { ..OpenShellRuntimeConfig::default() }; let refused = BoxSettings::from_config(&config).unwrap_err(); - assert_eq!(refused, BoxError::InvalidMemory { memory_mb: u64::MAX }); + assert_eq!( + refused, + BoxError::InvalidMemory { + memory_mb: u64::MAX + } + ); assert!(refused.to_string().contains("too large")); } diff --git a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs index a7dda048b93..530aa940b39 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs @@ -69,7 +69,10 @@ async fn the_box_enforces_the_deadline_from_its_own_workspace() { let mut request = request("ls | wc -l"); request.env.insert("LANG".into(), "C.UTF-8".into()); - boxes.exec(&user("u1"), &settings(), &request).await.unwrap(); + boxes + .exec(&user("u1"), &settings(), &request) + .await + .unwrap(); let exec = driver.last_exec().unwrap(); assert_eq!( From 9fb55cd7cd499af1eb170ffd225b8fab3ed0e393 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:24:54 +0000 Subject: [PATCH 21/29] test(openshell): cover release and shutdown before any box exists Add a test asserting that releasing a box and shutting down the sandbox are no-ops when no box has been created yet, guarding against panics on early teardown paths. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/mod_tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs index a0cfd448a4c..d13590d47c5 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -155,3 +155,9 @@ async fn without_module_support_execution_is_refused() { .unwrap_err(); assert!(error.to_string().contains("module support is disabled")); } + +#[tokio::test] +async fn release_and_shutdown_before_any_box_exists_are_no_ops() { + release(&embedded("u1")).await; + shutdown().await; +} From c40622ac9d61c745ee3a6e2b82f1958a0805d184 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:25:09 +0000 Subject: [PATCH 22/29] chore(ci): register openshell box registry in process statics Adds the OpenShell box registry to the process statics inventory, documenting that it is keyed on the full authenticated tenant and that unscoped calls are refused before the registry is touched, with the tests that verify tenant isolation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- scripts/ci/process-statics.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index f223f01b7ac..d8bf05b6803 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -668,5 +668,15 @@ "category": "A", "reason": "One-shot guard that subscribes the proactive web subscriber to the process-wide bus once; it stores no tenant identifiers, and per-event tenant scope arrives on each event.", "verification": "web_chat/event_bus_tests.rs: egress_surface_bridges_pending_with_chat_context" + }, + { + "file": "crates/openhuman-core/src/sandbox/openshell/mod.rs", + "scope": "", + "name": "REGISTRY", + "type": "std::sync::OnceLock>>", + "count": 1, + "category": "B", + "reason": "The process's OpenShell box registry holds one box per tenant, keyed on the whole authenticated Tenant (profile and agent), never the profile alone; a call with no tenant is refused before the registry is touched, so no two tenants can share a box.", + "verification": "sandbox/openshell/registry_tests.rs: embedded_users_of_one_host_get_separate_boxes; sandbox/openshell/mod_tests.rs: an_unscoped_command_creates_no_box" } ] From 5febc853c23e825f9bba3f96803cac12351b125f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:25:54 +0000 Subject: [PATCH 23/29] docs(sandbox): document the openshell sandbox backend Adds a section describing the OpenShell backend, covering per-tenant box lifecycle, single-flight creation, command execution and timeouts, lost-box recovery, and idle reaping with the max_live cap. Also lists the new [runtime.openshell] config table in the schema README so the settings are discoverable alongside the other runtime options. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/schema/README.md | 1 + crates/openhuman-core/src/sandbox/README.md | 45 ++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/README.md b/crates/openhuman-core/src/config/schema/README.md index d17e9fa7d39..ae3a4c89f6d 100644 --- a/crates/openhuman-core/src/config/schema/README.md +++ b/crates/openhuman-core/src/config/schema/README.md @@ -41,6 +41,7 @@ is mounted as a submodule of [`load/dirs.rs`](./load/dirs.rs) via `#[path]`. | `[[model_routes]]`, `[[embedding_routes]]` | [`routes.rs`](./routes.rs) | `ModelRouteConfig`, `EmbeddingRouteConfig` | | `[runtime]` (+ `[runtime.docker]`), `[shell]`, `[reliability]`, `[scheduler]` | [`runtime.rs`](./runtime.rs) | `RuntimeConfig`, `DockerRuntimeConfig`, `ShellConfig`, `ReliabilityConfig`, `SchedulerConfig` | | `[runtime.local_jail]` | [`runtime_local_jail.rs`](./runtime_local_jail.rs) | `LocalJailConfig`: filesystem grants for the local OS jail | +| `[runtime.openshell]` | [`runtime_openshell.rs`](./runtime_openshell.rs) | `OpenShellRuntimeConfig`: image, CPU, memory (whole MiB), idle TTL and `max_live` for the OpenShell sandbox backend | | `[scheduler_gate]` | [`scheduler_gate.rs`](./scheduler_gate.rs) | `SchedulerGateConfig`, `SchedulerGateMode` | | `[memory]` (engine, `engines.`, `conversations`, `context`, `sources`, embedding settings) | [`memory.rs`](./memory.rs) | `MemoryConfig`, `MemoryEngineSettings`, `MemoryConversationsConfig`, `MemoryContextConfig`, `MemorySourceConfig` (see [`docs/specs/memory-v2.md`](../../../../../docs/specs/memory-v2.md)) | | `[task_sources]` | [`task_sources.rs`](./task_sources.rs) | `TaskSourcesConfig` | diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index 493af22cc68..a6feff29928 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -1,7 +1,8 @@ # sandbox Decides where an agent's command runs: directly on the host, inside an OS jail -confined to the action dir, or in a throwaway Docker container. The tools that +confined to the action dir, in a throwaway Docker container, or in the +tenant's own long-lived OpenShell box. The tools that spawn processes (`shell`) and the flows code-runner capability call into it when the agent runs in sandboxed mode. The core process itself always runs on the host; only the spawned @@ -162,12 +163,50 @@ probe and label-scoped orphan cleanup. `validate_docker_policy` asks TinyBox's reports host networking and a mount or workspace root of `/`, `/etc`, `/proc`, `/sys` or the Docker socket; with no module there is no verdict, never a clean one. +### The OpenShell backend + +Selected only by `[security.sandbox] backend = "openshell"`: +`apply_requested_backend` sets `SandboxBackendKind::OpenShell` and drops the +Docker overrides and host mounts, since nothing on the host is mounted. +[`openshell/`](./openshell/mod.rs) keeps one box per tenant on an NVIDIA +OpenShell gateway, through the TinyBox module's `openshell` backend +(`Reserve` + `Create`, `Exec`, `Close`); the box outlives the command, so a +tenant's files persist between commands until the box is closed. + +- **One box per whole `Tenant`.** `BoxRegistry` keys on profile *and* agent: + an embedded host runs one agent per end user with no profile, so the profile + alone would put every user in one box. `ctx.tenant()` returning `NoTenant` + refuses the command; there is no shared fallback box. +- **Single-flight creation.** Concurrent first commands for a tenant create + one box. Each box comes from `[runtime.openshell]` (`image`, `cpu_millis`, + `memory_mb` sent as whole MiB bytes), with network `Denied`, no ports and no + host environment. +- **Commands.** `timeout -k 5 sh -c ` in `/sandbox`, with only + the request's own environment. Exit 124 is reported as timed out. The + shell tool's come-back time bounds the deadline (no yielding, like Docker). + If the box does not answer within the deadline plus 10 s, the host closes it + and reports the command timed out. +- **Lost boxes.** The bus client does not pass TinyBox's error names through, + so after a failed `Exec` the driver asks `Inspect`: a box the module refuses + to describe, or one no longer `ready`/`running`, is replaced once and the + command retried. +- **Lifetime.** A background reaper (every `min(30 s, idle_ttl / 2)`) closes + boxes idle for `idle_ttl_secs` (default 900) with nothing in flight. + `max_live` (default 50) caps live boxes: a new tenant first reaps idle + boxes, then fails with "the sandbox service is at capacity; try again + shortly". `openshell::release(tenant)` and `openshell::shutdown()` close + boxes; a failed close is logged, never raised. +- **One registry per process**, built from the first command's config, so + `idle_ttl_secs` and `max_live` changes apply after a restart. + ### Backend status `create_sandbox_backend` returns a `SandboxBackendHandle`. None is always `Ready`. Docker is `Ready` when the TinyBox status operation reports the daemon available and `Error` otherwise. A module or transport failure is surfaced by the status RPC rather than probed with a host-local Docker CLI. +OpenShell is `Ready` with no `backend_id`: boxes are created per tenant on +first use, so the gateway's availability shows on that call. Local reports `Ready` when `jail_isolation` accepts the module's native jail, and its handle's `isolation` says which posture (`isolated` or `folder_confined`); the field is omitted for every other handle. Missing modules and transport errors are @@ -184,13 +223,14 @@ execution refuses to run without the required provider. | [`native_jail.rs`](./native_jail.rs) | TinyBox native-jail and cron passthrough request mapping, process/output lifecycle, and fail-closed status checks. | | [`local_grants.rs`](./local_grants.rs) | Host adapter for `ResolveLocalGrants`: sends the credential floor as input and re-applies it to the module's reply. | | [`docker.rs`](./docker.rs) | Policy-to-`RunDocker` mapping, module status/cleanup calls, Docker policy validation. | +| [`openshell/`](./openshell/mod.rs) | Per-tenant OpenShell boxes: `BoxRegistry` (lifecycle, reaper, capacity, backstop), the `BoxDriver` seam and its TinyBox bus implementation. | | [`schemas.rs`](./schemas.rs) | The `sandbox.*` controllers. | ## Key types and entry points - `SandboxPolicy` ([`types.rs`](./types.rs)): the resolved per-call policy. It is serializable so `sandbox.resolve_policy` can return it. -- `SandboxBackendKind` (`types.rs`): `None`, `Local`, `Docker`. +- `SandboxBackendKind` (`types.rs`): `None`, `Local`, `Docker`, `OpenShell`. - `resolve_sandbox_policy(mode, action_dir, state_dir, runtime_config, is_remote_session)` (`ops.rs`). - `execute_in_sandbox(policy, command, working_dir, extra_env, timeout)` @@ -259,6 +299,7 @@ The settings surface (`get_sandbox_settings`, `[security.sandbox]` and ## Tests Sibling suites: [`types_tests.rs`](./types_tests.rs), [`ops_tests.rs`](./ops_tests.rs), [`local_grants_tests.rs`](./local_grants_tests.rs), +`openshell/{registry,bus_driver,mod}_tests.rs` (over a scripted `BoxDriver`, under a paused clock), [`schemas_tests.rs`](./schemas_tests.rs), [`docker_tests.rs`](./docker_tests.rs) and [`docker_exec_tests.rs`](./docker_exec_tests.rs). `native_jail_tests.rs` pins the status floor, grant/environment mapping, module-unavailable refusal, and an ignored pinned-artifact Linux execution From 249d272dbd57da593c2c5778d0287da9c845f75f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:26:12 +0000 Subject: [PATCH 24/29] chore(ci): refresh saas ambient baseline for shifted lines Updated the ambient-config baseline to track line shifts in existing files and registered the sandbox registry's process-wide reaper spawn as a known bare-spawn, with a comment explaining that the sweeper intentionally carries no tenant context. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/registry.rs | 2 ++ scripts/ci/saas-ambient-baseline.json | 15 +++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs index f1ca868ba8a..a5fb4738635 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -223,6 +223,8 @@ impl BoxRegistry { self.reaper.call_once(|| { let registry: Weak = Arc::downgrade(self); let every = reap_interval(self.limits.idle_ttl); + // A process-wide sweeper: it closes boxes by id and acts under no + // tenant's context, so it carries none. tokio::spawn(async move { let mut ticks = tokio::time::interval(every); ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json index 01bdfb961ad..a1e2c2f66bd 100644 --- a/scripts/ci/saas-ambient-baseline.json +++ b/scripts/ci/saas-ambient-baseline.json @@ -9,21 +9,21 @@ { "rule": "ambient-config", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 231, + "line": 247, "text": "let config = crate::config::Config::load_or_init().await?;", "occurrence": 1 }, { "rule": "ambient-context", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 322, + "line": 338, "text": "crate::core::runtime::CoreContext::current()", "occurrence": 1 }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs", - "line": 661, + "line": 672, "text": "tokio::spawn(async move { while rx.recv().await.is_some() {} });", "occurrence": 1 }, @@ -636,6 +636,13 @@ "text": "tokio::spawn(async move {", "occurrence": 1 }, + { + "rule": "bare-spawn", + "path": "crates/openhuman-core/src/sandbox/openshell/registry.rs", + "line": 228, + "text": "tokio::spawn(async move {", + "occurrence": 1 + }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/security/credentials/ops/gated_services.rs", @@ -821,7 +828,7 @@ { "rule": "bare-spawn", "path": "crates/openhuman-core/src/storage/import_state.rs", - "line": 455, + "line": 457, "text": "std::thread::spawn(move || {", "occurrence": 1 }, From 34f905a1d7a91c7c72cb06babce8d77c87833851 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:26:21 +0000 Subject: [PATCH 25/29] chore(ci): update saas ambient baseline line numbers Shift the recorded line numbers for existing ambient-config, ambient-context, and bare-spawn entries to match their current positions after unrelated code moved in the affected files. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- scripts/ci/saas-ambient-baseline.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json index a1e2c2f66bd..c1df35c8026 100644 --- a/scripts/ci/saas-ambient-baseline.json +++ b/scripts/ci/saas-ambient-baseline.json @@ -9,21 +9,21 @@ { "rule": "ambient-config", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 247, + "line": 231, "text": "let config = crate::config::Config::load_or_init().await?;", "occurrence": 1 }, { "rule": "ambient-context", "path": "crates/openhuman-core/src/agent_registry/host_definition.rs", - "line": 338, + "line": 322, "text": "crate::core::runtime::CoreContext::current()", "occurrence": 1 }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs", - "line": 672, + "line": 661, "text": "tokio::spawn(async move { while rx.recv().await.is_some() {} });", "occurrence": 1 }, @@ -828,7 +828,7 @@ { "rule": "bare-spawn", "path": "crates/openhuman-core/src/storage/import_state.rs", - "line": 457, + "line": 455, "text": "std::thread::spawn(move || {", "occurrence": 1 }, From bc465510db1dbb90ff3170aa913ebca3b9c5bfbf Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:29:28 +0000 Subject: [PATCH 26/29] refactor(sandbox): use fully qualified std::sync::Arc paths Replaced the imported Arc with fully qualified std::sync::Arc in the OpenShell registry static and its accessor, and updated the process-statics manifest to match. The test module now imports Arc directly since it no longer inherits the parent's use. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/mod.rs | 8 ++++---- crates/openhuman-core/src/sandbox/openshell/mod_tests.rs | 1 + scripts/ci/process-statics.json | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/mod.rs b/crates/openhuman-core/src/sandbox/openshell/mod.rs index fb191dcb370..c3f4d382a47 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod.rs @@ -30,7 +30,6 @@ mod types; use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; -use std::sync::Arc; use std::time::Duration; #[cfg(feature = "modules")] @@ -96,14 +95,15 @@ pub async fn run_command( } #[cfg(feature = "modules")] -static REGISTRY: std::sync::OnceLock>> = std::sync::OnceLock::new(); +static REGISTRY: std::sync::OnceLock>> = + std::sync::OnceLock::new(); /// The process's registry, built (and its reaper started) on first use. #[cfg(feature = "modules")] -fn registry(config: &Config) -> &'static Arc> { +fn registry(config: &Config) -> &'static std::sync::Arc> { let registry = REGISTRY.get_or_init(|| { BoxRegistry::new( - Arc::new(BusBoxDriver::new(config.clone())), + std::sync::Arc::new(BusBoxDriver::new(config.clone())), RegistryLimits::from_config(&config.runtime.openshell), ) }); diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs index d13590d47c5..9655a23d2de 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -4,6 +4,7 @@ use crate::core::runtime::NoTenant; use scripted_driver::ScriptedDriver; use std::collections::HashMap; use std::ffi::OsString; +use std::sync::Arc; fn embedded(id: &str) -> Tenant { Tenant { diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index d8bf05b6803..d322f219db1 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -673,7 +673,7 @@ "file": "crates/openhuman-core/src/sandbox/openshell/mod.rs", "scope": "", "name": "REGISTRY", - "type": "std::sync::OnceLock>>", + "type": "std::sync::OnceLock>>", "count": 1, "category": "B", "reason": "The process's OpenShell box registry holds one box per tenant, keyed on the whole authenticated Tenant (profile and agent), never the profile alone; a call with no tenant is refused before the registry is touched, so no two tenants can share a box.", From 051dec50b45679a76f0bd80e4ac653ff31bc602e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:51:53 +0000 Subject: [PATCH 27/29] test(openshell): cover closing a box reported gone before replacement Add a regression test asserting that a box inferred as gone after a failed exec is still closed before being replaced, since the probe can be wrong and skipping the close would leak the box on the gateway. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/registry_tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs index 530aa940b39..d29923c880d 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry_tests.rs @@ -294,6 +294,22 @@ async fn an_unknown_box_is_replaced_once_and_the_command_retried() { assert_eq!(driver.exec_resources(), vec!["box-0", "box-1"]); } +#[tokio::test(start_paused = true)] +async fn a_box_reported_gone_is_still_closed_before_it_is_replaced() { + // "Gone" is inferred from a probe after a failed exec, so the box may + // still exist; dropping it without a close would leak it on the gateway. + let driver = ScriptedDriver::new(); + driver.then(ExecStep::Fail(BoxError::UnknownResource)); + let boxes = registry(&driver, 10); + + boxes + .exec(&user("u1"), &settings(), &request("true")) + .await + .unwrap(); + + assert_eq!(driver.closed(), vec!["box-0"]); +} + #[tokio::test(start_paused = true)] async fn a_second_unknown_box_fails_the_command() { let driver = ScriptedDriver::new(); From 76b64890e09111bf691290de4806bd310fe36fd8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 10:51:59 +0000 Subject: [PATCH 28/29] fix(sandbox): close box on gateway after unknown resource error When an exec fails with UnknownResource, the box may still exist on the gateway since "gone" is only inferred from the failed exec. Close it quietly before forgetting the slot so the resource is not leaked. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/sandbox/openshell/registry.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/openhuman-core/src/sandbox/openshell/registry.rs b/crates/openhuman-core/src/sandbox/openshell/registry.rs index a5fb4738635..6b87824c465 100644 --- a/crates/openhuman-core/src/sandbox/openshell/registry.rs +++ b/crates/openhuman-core/src/sandbox/openshell/registry.rs @@ -168,7 +168,10 @@ impl BoxRegistry { return Ok(backstop_timed_out(request.timeout)); } Err(BoxError::UnknownResource) => { + // "Gone" is inferred after a failed exec, so the box may + // still exist on the gateway: close it rather than leak it. lease.slot.forget(&resource); + self.close_quietly(&resource).await; if replaced { return Err(BoxError::UnknownResource); } From 59b57d98c760368ca52155eda3889c10f5dd9229 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Fri, 30 Oct 2026 11:13:34 +0000 Subject: [PATCH 29/29] fix(sandbox): reject unusable openshell box settings and clamp registry limits BoxSettings::from_config now returns an InvalidConfig error when the image is blank or cpu_millis or memory_mb is zero, instead of letting a broken box be created. RegistryLimits::from_config raises zero idle_ttl_secs and max_live to 1 so a zero value cannot reap every box immediately or refuse every command. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/sandbox/openshell/mod_tests.rs | 39 +++++++++++++++++++ .../src/sandbox/openshell/types.rs | 23 +++++++++-- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs index 9655a23d2de..c5475ca0e7c 100644 --- a/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs +++ b/crates/openhuman-core/src/sandbox/openshell/mod_tests.rs @@ -71,6 +71,45 @@ fn memory_too_large_for_bytes_is_refused() { assert!(refused.to_string().contains("too large")); } +#[test] +fn unusable_box_settings_are_refused_with_a_config_error() { + let defaults = OpenShellRuntimeConfig::default(); + for config in [ + OpenShellRuntimeConfig { + image: " ".into(), + ..defaults.clone() + }, + OpenShellRuntimeConfig { + cpu_millis: 0, + ..defaults.clone() + }, + OpenShellRuntimeConfig { + memory_mb: 0, + ..defaults.clone() + }, + ] { + let refused = BoxSettings::from_config(&config).unwrap_err(); + assert!(matches!(refused, BoxError::InvalidConfig(_)), "{refused:?}"); + assert!(refused.to_string().contains("[runtime.openshell]")); + } +} + +#[test] +fn zero_registry_limits_are_raised_to_one() { + let config = OpenShellRuntimeConfig { + idle_ttl_secs: 0, + max_live: 0, + ..OpenShellRuntimeConfig::default() + }; + assert_eq!( + RegistryLimits::from_config(&config), + RegistryLimits { + idle_ttl: Duration::from_secs(1), + max_live: 1, + } + ); +} + #[test] fn the_command_env_is_only_what_the_request_carries() { let mut extra = HashMap::new(); diff --git a/crates/openhuman-core/src/sandbox/openshell/types.rs b/crates/openhuman-core/src/sandbox/openshell/types.rs index cc5dd9c3d60..1908a514e9d 100644 --- a/crates/openhuman-core/src/sandbox/openshell/types.rs +++ b/crates/openhuman-core/src/sandbox/openshell/types.rs @@ -25,8 +25,18 @@ impl BoxSettings { /// /// # Errors /// - /// [`BoxError::InvalidMemory`] when `memory_mb` does not fit in bytes. + /// [`BoxError::InvalidConfig`] when `image` is blank or `cpu_millis` or + /// `memory_mb` is zero; [`BoxError::InvalidMemory`] when `memory_mb` does + /// not fit in bytes. pub fn from_config(config: &OpenShellRuntimeConfig) -> Result { + if config.image.trim().is_empty() { + return Err(BoxError::InvalidConfig("image must not be blank")); + } + if config.cpu_millis == 0 || config.memory_mb == 0 { + return Err(BoxError::InvalidConfig( + "cpu_millis and memory_mb must be positive", + )); + } let memory_bytes = config.memory_bytes().ok_or(BoxError::InvalidMemory { memory_mb: config.memory_mb, })?; @@ -48,11 +58,13 @@ pub struct RegistryLimits { } impl RegistryLimits { - /// The bounds `[runtime.openshell]` sets. + /// The bounds `[runtime.openshell]` sets. A zero `max_live` would refuse + /// every command and a zero `idle_ttl_secs` would reap every box at once, + /// so each is raised to 1. pub fn from_config(config: &OpenShellRuntimeConfig) -> Self { Self { - idle_ttl: Duration::from_secs(config.idle_ttl_secs), - max_live: config.max_live, + idle_ttl: Duration::from_secs(config.idle_ttl_secs.max(1)), + max_live: config.max_live.max(1), } } } @@ -116,6 +128,9 @@ pub enum BoxError { /// The configured value. memory_mb: u64, }, + /// A `[runtime.openshell]` value is out of range. + #[error("invalid [runtime.openshell] setting: {0}")] + InvalidConfig(&'static str), /// A variable for the command is not UTF-8. #[error("sandbox environment is not UTF-8")] NonUtf8Env,