Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat: route desktop gateway provisioning through TinyBox

Steven Enamakel6fe7115f0ba5
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock
index b6fc13ed8e..f26cf2295d 100644
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@ -4439,6 +4439,7 @@ dependencies = [
"tinyagents-runtime",
"tinyagents-session",
"tinyagents-tasks",
+ "tinybox-bus",
"tinybox-core",
"tinybox-docker",
"tinybox-jail",
@@ -4536,10 +4537,6 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tempfile",
- "tinybox-core",
- "tinybox-docker",
- "tinybox-host",
- "tinybox-ssh",
"tokio",
"tokio-util",
"toml 0.8.2",
@@ -7423,35 +7420,36 @@ dependencies = [
]
[[package]]
-name = "tinybox-core"
-version = "0.1.16"
+name = "tinybox-bus"
+version = "0.1.18"
dependencies = [
- "async-trait",
"serde",
- "thiserror 2.0.20",
]
[[package]]
-name = "tinybox-docker"
-version = "0.1.16"
+name = "tinybox-core"
+version = "0.1.18"
dependencies = [
"async-trait",
- "tinybox-core",
- "tokio",
+ "serde",
+ "thiserror 2.0.20",
+ "tinybox-bus",
]
[[package]]
-name = "tinybox-host"
-version = "0.1.16"
+name = "tinybox-docker"
+version = "0.1.18"
dependencies = [
"async-trait",
+ "serde_json",
"tinybox-core",
"tokio",
+ "uuid",
]
[[package]]
name = "tinybox-jail"
-version = "0.1.16"
+version = "0.1.18"
dependencies = [
"landlock",
"log",
@@ -7461,15 +7459,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "tinybox-ssh"
-version = "0.1.16"
-dependencies = [
- "async-trait",
- "tinybox-core",
- "tokio",
-]
-
[[package]]
name = "tinybus"
version = "0.1.3"
diff --git a/crates/openhuman-app/Cargo.toml b/crates/openhuman-app/Cargo.toml
index 7e89463b77..5bac3f34f8 100644
--- a/crates/openhuman-app/Cargo.toml
+++ b/crates/openhuman-app/Cargo.toml
@@ -130,14 +130,6 @@ url = "2"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
rand = "0.9"
-# tinybox: reach (local/ssh) and confinement (passthrough/docker) as
-# independent axes, which is what lets one `GatewaySpec::Box` variant cover a
-# container here, a machine over there, and a container over there. Vendored as
-# a submodule and taken by path, the same shape as the other tiny* crates.
-tinybox-core = { path = "../../vendor/tinybox/crates/tinybox-core", optional = true }
-tinybox-host = { path = "../../vendor/tinybox/crates/tinybox-host", optional = true }
-tinybox-ssh = { path = "../../vendor/tinybox/crates/tinybox-ssh", optional = true }
-tinybox-docker = { path = "../../vendor/tinybox/crates/tinybox-docker", optional = true }
hex = "0.4"
# Tauri's vendored dev-server proxy (see `vendor/tauri-cef/.../protocol/tauri.rs`)
# builds a reqwest 0.13 client that requires a process-wide rustls
@@ -272,19 +264,14 @@ windows-sys = { version = "0.59", features = [
[features]
default = ["gateways"]
# Routing the frontend to a core somewhere other than this process: a
-# container, a machine over SSH, or a container on a machine over SSH. Pulls in
-# the tinybox crates that provision and reach those boxes.
+# container, a machine over SSH, or a container on a machine over SSH. Calls
+# the TinyBox module through openhuman-rpc's curated embed facade.
#
# This is a **shell-local** gate, unrelated to the feature-forwarding rules in
# AGENTS.md: those govern which product gates the shell forwards on its
# `openhuman-rpc` dependency, and `scripts/ci/check-feature-forwarding.mjs`
# reads that dependency's feature list, not this table. Nothing here belongs in `scripts/ci/product-features.txt`.
-gateways = [
- "dep:tinybox-core",
- "dep:tinybox-docker",
- "dep:tinybox-host",
- "dep:tinybox-ssh",
-]
+gateways = []
# `custom-protocol` switches Tauri from `devUrl` (vite dev server) to the
# bundled `frontendDist` served via `tauri://localhost`. `cargo tauri build`
# turns this on automatically for release; do not put it in `default` or
diff --git a/crates/openhuman-app/src/gateway/README.md b/crates/openhuman-app/src/gateway/README.md
index 13ad2e52a4..3230f0f4c8 100644
--- a/crates/openhuman-app/src/gateway/README.md
+++ b/crates/openhuman-app/src/gateway/README.md
@@ -62,34 +62,26 @@ core_rpc_endpoint ----------------> registry::current -> (rpc_url, token)
### Provisioning a box
-`provision::provision` runs four tinybox steps and reports each through a
-progress callback, which the registry turns into `GatewayStatus::Activating
-{ step }`:
-
-1. Create the box (`create_box`). The spec from `box_spec` maps reach to a
- tinybox `HostRef` (`local` or `ssh`) and confinement to a `SandboxRef`
- (`passthrough` or `docker`). Docker boxes get `NetworkPolicy::Egress` and
- publish the in-box core port `CORE_PORT_IN_BOX` (7788) to a host port.
- That host port is chosen by the shell (a free local port, or a random
- ephemeral port on a remote machine) because tinybox cannot report a port
- Docker picked. Creation retries up to `PORT_ATTEMPTS` (8) times when
- Docker says the port is taken. A passthrough box publishes nothing; the
- core listens on 7788 on the target machine directly.
-2. Start the core detached (`start_core`). `core_command` runs
- `<binary> serve` (or `openhuman-core serve` from the image's `PATH`) with
- `OPENHUMAN_CORE_TOKEN` set to a freshly minted bearer,
- `OPENHUMAN_CORE_HOST=0.0.0.0` and `OPENHUMAN_CORE_PORT=7788`.
-3. Forward the published port back to `127.0.0.1` on this machine
- (`Host::forward`). For an SSH box the published port lives on the far
- machine, so without this step nothing is reachable.
-4. Poll the unauthenticated `/health` every 250 ms for up to 120 s
- (`wait_until_healthy`). An open tunnel does not prove the core is up.
-
-A failure at any step stops the core and destroys the box before returning,
-so a failed activation leaves nothing behind. The resulting `Provisioned`
-value owns the tunnel (`Forward`), the sandbox, the box id and the process id.
-Dropping the `Forward` closes the tunnel, which is why the registry holds the
-value for as long as the gateway is active.
+`provision::provision` loads the persisted runtime config through the curated
+embed facade and calls the pinned TinyBox module before the core RPC server is
+started. The host reserves opaque resource, process, and forward ids before
+native work, then sends typed requests through `openhuman_rpc::embed::modules::tinybox`.
+
+The gateway chooses the host (`Local` or configured `Ssh`), workspace
+(directory or OCI image), egress policy, and process environment. TinyBox owns
+creation, the detached core process, and its forward. Docker requests a dynamic
+host port; TinyBox returns the effective mapping and owns the forward rather
+than relying on shell-side Docker probing or port-conflict parsing. The core
+runs as `<binary> serve` (or `openhuman-core serve` from the image's `PATH`) with
+a freshly minted `OPENHUMAN_CORE_TOKEN`, `OPENHUMAN_CORE_HOST=0.0.0.0`, and
+`OPENHUMAN_CORE_PORT=7788`.
+
+After opening the module-owned forward, the gateway polls the unauthenticated
+`/health` endpoint every 250 ms for up to 120 seconds. A failure closes the
+caller-known resource reservation, which lets the module clean up even if a
+Create/Spawn/Forward reply was lost after native startup. The resulting
+`Provisioned` value retains the explicit config and resource handle; teardown
+uses TinyBox `Close` and logs a sanitized error if native cleanup remains pending.
### Activation and switching
@@ -100,8 +92,8 @@ terminal `Connected` or `Failed` status.
The previous gateway is torn down only after the new one is up. A failed
activation records `GatewayStatus::Failed { reason }` and leaves the working
-gateway active. `Provisioned::tear_down` stops the core and destroys the box,
-logging and continuing past each failure.
+gateway active. `Provisioned::tear_down` asks TinyBox to close the resource and waits for its
+cleanup acknowledgement; the module retains unacknowledged native ownership.
At launch, and whenever nothing has been activated, `registry::current` falls
back to the embedded core. Active state is in memory only; after a restart
diff --git a/crates/openhuman-app/src/gateway/ops.rs b/crates/openhuman-app/src/gateway/ops.rs
index c4df26cdd6..d414f2721d 100644
--- a/crates/openhuman-app/src/gateway/ops.rs
+++ b/crates/openhuman-app/src/gateway/ops.rs
@@ -18,18 +18,17 @@
//! Getting a core into a box and making it reachable is [`provision`]'s job;
//! this module decides *which* of those a gateway needs and holds the result.
-use std::sync::Arc;
-
-use tinybox_core::{BoxId, Forward, ProcessId, Sandbox};
+use openhuman_rpc::embed::config::RuntimeConfig;
+use openhuman_rpc::embed::modules::tinybox::{self, contract};
use super::provision;
use super::types::{ActiveGateway, Gateway, GatewaySpec};
/// A provisioned gateway, and everything that has to stay alive for it.
///
-/// Holding this *is* the gateway existing: dropping it closes the tunnel and
-/// the box stops being reachable. That is why the active one is kept in a
-/// long-lived registry rather than returned to the caller.
+/// The module-owned resource remains active while this handle is stored. The
+/// registry calls [`Self::tear_down`] to await acknowledged cleanup before
+/// releasing it.
pub struct Provisioned {
/// Where the frontend should send RPC.
pub active: ActiveGateway,
@@ -39,13 +38,11 @@ pub struct Provisioned {
/// it is the sibling that creates all of this, and moving it back in here
/// would put four hundred lines of box mechanics in the module whose job is
/// deciding which gateway needs them.
- pub(super) _forward: Option<Forward>,
- /// The sandbox the box lives in, for tearing it down.
- pub(super) sandbox: Arc<dyn Sandbox>,
- /// The box.
- pub(super) box_id: BoxId,
- /// The core process inside it.
- pub(super) process: ProcessId,
+ pub(super) config: RuntimeConfig,
+ /// Caller-known module resource handle used for acknowledged cleanup.
+ pub(super) resource: contract::ResourceId,
+ /// Opaque process id used only in safe diagnostics; TinyBox owns the process.
+ pub(super) process: contract::ProcessRef,
}
impl std::fmt::Debug for Provisioned {
@@ -55,32 +52,26 @@ impl std::fmt::Debug for Provisioned {
formatter
.debug_struct("Provisioned")
.field("id", &self.active.id)
- .field("box", &self.box_id.as_str())
- .field("process", &self.process.as_str())
+ .field("resource", &self.resource.0)
+ .field("process", &self.process.process.0)
.finish_non_exhaustive()
}
}
impl Provisioned {
- /// Stop the core and destroy the box.
+ /// Close the TinyBox resource and wait for native cleanup acknowledgement.
///
- /// Best-effort throughout: this runs when the user is switching away, and
- /// a box that cannot be cleaned up must not block them from reaching a
- /// gateway that works. Every failure is logged and the next step is still
- /// attempted.
+ /// Best-effort at the gateway-switch boundary: cleanup failures are logged
+ /// without blocking the user from reaching another gateway. TinyBox keeps
+ /// any unacknowledged native ownership for module shutdown or retry.
pub async fn tear_down(self) {
log::debug!(
- "[gateway][teardown] stopping {} in box {}",
- self.process,
- self.box_id
+ "[gateway][teardown] closing TinyBox resource {}",
+ self.resource.0
);
- if let Err(error) = self.sandbox.stop(&self.box_id, &self.process).await {
- log::warn!("[gateway][teardown] stop failed: {error}");
- }
- if let Err(error) = self.sandbox.destroy(&self.box_id).await {
- log::warn!("[gateway][teardown] destroy failed: {error}");
+ if let Err(error) = tinybox::close(&self.config, self.resource).await {
+ log::warn!("[gateway][teardown] cleanup remains pending: {error}");
}
- // The forward's own `Drop` closes the tunnel as this returns.
}
}
diff --git a/crates/openhuman-app/src/gateway/ops_tests.rs b/crates/openhuman-app/src/gateway/ops_tests.rs
index a6106198f0..9094b05902 100644
--- a/crates/openhuman-app/src/gateway/ops_tests.rs
+++ b/crates/openhuman-app/src/gateway/ops_tests.rs
@@ -1,17 +1,11 @@
-//! Tests for gateway provisioning.
-//!
-//! The decisions worth pinning are the ones made *before* anything runs: which
-//! placement a spec names, whether the network policy actually permits the
-//! publish it asks for, and what the core is started with. Those are pure, so
-//! they are asserted as values rather than observed by creating a container.
-//!
-//! Provisioning end to end spawns a local box and a netcat stand-in core and is `#[ignore]`d below.
+//! Tests for the host-owned TinyBox module request mapping.
use std::collections::BTreeMap;
use super::ops::endpoint_of;
-use super::provision::{box_spec, core_command, is_port_conflict};
+use super::provision::{core_command, create_request, host_config};
use super::types::{Confinement, Reach, SshReach, CORE_PORT_IN_BOX};
+use openhuman_rpc::embed::modules::tinybox::contract;
fn docker() -> Confinement {
Confinement::Docker {
@@ -30,145 +24,113 @@ fn ssh() -> Reach {
Reach::Ssh(SshReach {
destination: "[email protected]".to_owned(),
port: Some(2222),
- identity: None,
+ identity: Some("/home/operator/.ssh/build_key".into()),
accept_new_host_key: true,
})
}
#[test]
-fn a_docker_box_permits_the_network_its_published_port_needs() {
- // tinybox drops the `--publish` flags entirely on a box whose network is
- // denied — a container with no network has nowhere for a published port to
- // lead. Denied here would produce a box that looks configured, publishes
- // nothing, and is unreachable with no error anywhere.
- let spec = box_spec(&Reach::Local, &docker(), &BTreeMap::new(), 54321).expect("a spec");
-
- assert!(spec.network.allows_egress());
- let published = spec
- .ports
- .iter()
- .find(|mapping| mapping.guest == CORE_PORT_IN_BOX);
- assert_eq!(published.and_then(|mapping| mapping.host), Some(54321));
-}
-
-#[test]
-fn the_host_port_is_named_rather_than_left_to_docker() {
- // `PortMapping::dynamic` would let Docker choose, and the number it chose
- // would live only in Docker's own state — tinybox has no call that reports
- // it back, and a forward needs that number.
- let spec = box_spec(&Reach::Local, &docker(), &BTreeMap::new(), 54321).expect("a spec");
-
- assert!(spec.ports.iter().all(|mapping| mapping.host.is_some()));
-}
-
-#[test]
-fn a_passthrough_box_publishes_nothing_because_there_is_no_boundary() {
- // The core listens on the machine's own port; there is nothing to publish
- // across and nothing that could collide beyond the core itself.
- let spec = box_spec(&Reach::Local, &passthrough(), &BTreeMap::new(), 54321).expect("a spec");
+fn docker_request_uses_module_owned_dynamic_port_and_required_egress() {
+ let request = create_request(
+ contract::ResourceId("resource-1".to_owned()),
+ &Reach::Local,
+ &docker(),
+ &BTreeMap::new(),
+ );
- assert!(spec.ports.is_empty());
+ assert_eq!(request.backend, "docker");
+ assert_eq!(request.host, contract::HostConfig::Local);
+ assert_eq!(
+ request.workspace,
+ contract::Workspace::Image("openhuman-core:latest".to_owned())
+ );
+ assert_eq!(request.network, contract::NetworkPolicy::Egress);
+ assert_eq!(
+ request.ports,
+ [contract::PortMapping {
+ guest: CORE_PORT_IN_BOX,
+ host: None
+ }]
+ );
}
#[test]
-fn the_placement_records_both_axes_independently() {
- // Which is what makes "a container on the build server" need no code of
- // its own: it is these two fields, chosen separately.
- let spec = box_spec(&ssh(), &docker(), &BTreeMap::new(), 54321).expect("a spec");
+fn passthrough_request_uses_the_configured_workspace_without_publishing() {
+ let request = create_request(
+ contract::ResourceId("resource-1".to_owned()),
+ &Reach::Local,
+ &passthrough(),
+ &BTreeMap::new(),
+ );
- assert_eq!(spec.workspace.host.as_str(), "ssh");
- assert_eq!(spec.workspace.sandbox.as_str(), "docker");
+ assert_eq!(request.backend, "passthrough");
+ assert_eq!(
+ request.workspace,
+ contract::Workspace::Directory("/srv/openhuman".to_owned())
+ );
+ assert!(request.ports.is_empty());
}
#[test]
-fn a_passthrough_box_runs_in_the_configured_workspace() {
- let spec = box_spec(&Reach::Local, &passthrough(), &BTreeMap::new(), 1).expect("a spec");
-
+fn ssh_placement_and_identity_path_are_transferred_as_host_configuration() {
assert_eq!(
- spec.source,
- tinybox_core::WorkspaceSource::LocalDir("/srv/openhuman".into())
+ host_config(&ssh()),
+ contract::HostConfig::Ssh(contract::SshHostConfig {
+ destination: "[email protected]".to_owned(),
+ port: Some(2222),
+ identity: Some("/home/operator/.ssh/build_key".to_owned()),
+ known_hosts: None,
+ accept_new_host_key: true,
+ })
);
}
#[test]
-fn configured_environment_reaches_the_box() {
- let mut env = BTreeMap::new();
- env.insert(
+fn configured_environment_is_passed_to_module_creation() {
+ let env = BTreeMap::from([(
"BACKEND_URL".to_owned(),
"https://api.example.com".to_owned(),
+ )]);
+ let request = create_request(
+ contract::ResourceId("resource-1".to_owned()),
+ &Reach::Local,
+ &docker(),
+ &env,
);
-
- let spec = box_spec(&Reach::Local, &docker(), &env, 1).expect("a spec");
-
- assert_eq!(
- spec.env.get("BACKEND_URL").map(String::as_str),
- Some("https://api.example.com")
- );
+ assert_eq!(request.env, env);
}
#[test]
-fn the_core_is_started_bound_to_every_interface_inside_the_box() {
- // Loopback inside a container is reachable only from inside it, which is
- // the one place nothing is asking. The published port would lead nowhere.
- let request = core_command(&docker(), "deadbeef");
-
+fn core_command_carries_ephemeral_bearer_and_explicit_bind_address() {
+ let request = core_command(
+ &contract::ResourceId("resource-1".to_owned()),
+ &docker(),
+ "deadbeef",
+ );
+ assert_eq!(request.argv, ["openhuman-core", "serve"]);
+ assert_eq!(
+ request.env.get("OPENHUMAN_CORE_TOKEN").map(String::as_str),
+ Some("deadbeef")
+ );
assert_eq!(
request.env.get("OPENHUMAN_CORE_HOST").map(String::as_str),
Some("0.0.0.0")
);
assert_eq!(
request.env.get("OPENHUMAN_CORE_PORT").map(String::as_str),
- Some(CORE_PORT_IN_BOX.to_string().as_str())
+ Some("7788")
);
}
#[test]
-fn the_bearer_is_handed_over_as_environment_rather_than_written_down() {
- // It is minted per activation and never persisted, so a stored gateway
- // record cannot leak a credential for a core that is still running.
- let request = core_command(&docker(), "deadbeef");
-
- assert_eq!(
- request.env.get("OPENHUMAN_CORE_TOKEN").map(String::as_str),
- Some("deadbeef")
+fn passthrough_core_command_uses_named_binary_and_workspace() {
+ let request = core_command(
+ &contract::ResourceId("resource-1".to_owned()),
+ &passthrough(),
+ "t",
);
-}
-
-#[test]
-fn a_docker_box_runs_the_image_s_own_core_rather_than_a_named_path() {
- // Naming a path would tie the gateway to one image's layout.
- let request = core_command(&docker(), "t");
-
- assert_eq!(request.program(), Some("openhuman-core"));
- assert_eq!(request.argv.get(1).map(String::as_str), Some("serve"));
-}
-
-#[test]
-fn a_passthrough_box_runs_the_binary_the_user_named() {
- let request = core_command(&passthrough(), "t");
-
- assert_eq!(request.program(), Some("/usr/local/bin/openhuman-core"));
-}
-
-#[test]
-fn a_taken_port_is_recognised_from_the_backend_s_own_words() {
- // tinybox passes Docker's diagnostic through verbatim, so this is what a
- // collision actually looks like coming back.
- assert!(is_port_conflict(
- "driver failed programming external connectivity on endpoint: \
- Bind for 0.0.0.0:54321 failed: port is already allocated"
- ));
- assert!(is_port_conflict("address already in use"));
-}
-
-#[test]
-fn an_unrelated_failure_is_not_mistaken_for_a_taken_port() {
- // Retrying a missing image seven more times would turn one clear error
- // into a slow, confusing one.
- assert!(!is_port_conflict(
- "Unable to find image 'openhuman-core:latest' locally"
- ));
- assert!(!is_port_conflict("Cannot connect to the Docker daemon"));
+ assert_eq!(request.argv[0], "/usr/local/bin/openhuman-core");
+ assert_eq!(request.cwd.as_deref(), Some("/srv/openhuman"));
}
#[test]
@@ -183,13 +145,8 @@ fn a_remote_gateway_resolves_to_its_url_without_provisioning() {
token: Some("bearer".to_owned()),
},
};
-
- // The handle is irrelevant for a remote gateway and is never consulted;
- // it is required only because the desktop arm of the same function needs
- // one.
let unused = crate::core_process::CoreProcessHandle::new(7788);
let resolved = endpoint_of(&gateway, &unused).expect("an endpoint");
-
assert_eq!(resolved.rpc_url, "https://core.example.com/rpc");
assert_eq!(resolved.token.as_deref(), Some("bearer"));
}
@@ -240,7 +197,7 @@ mod provisioning {
}
#[tokio::test]
- #[ignore = "spawns a tinybox local box plus a netcat-served stand-in core on a real port (needs `nc` with -l -p); run: cargo test --manifest-path crates/openhuman-app/Cargo.toml --lib gateway::ops_tests::provisioning -- --ignored --nocapture"]
+ #[ignore = "spawns the pinned TinyBox module plus a netcat-served stand-in core on a real port (needs `nc` with -l -p); run: cargo test --manifest-path crates/openhuman-app/Cargo.toml --lib gateway::ops_tests::provisioning -- --ignored --nocapture"]
async fn a_local_box_is_provisioned_and_answers_through_its_endpoint() {
let dir = tempfile::TempDir::new().expect("a temporary directory");
let gateway = Gateway {
@@ -270,14 +227,12 @@ mod provisioning {
provisioned.active.token.is_some(),
"a provisioned core is behind a bearer"
);
- assert!(
- provisioned
- .active
- .rpc_url
- .contains(&CORE_PORT_IN_BOX.to_string()),
- "a passthrough box publishes nothing, so the core's own port is the endpoint: {}",
- provisioned.active.rpc_url
- );
+ let endpoint: url::Url = provisioned
+ .active
+ .rpc_url
+ .parse()
+ .expect("TinyBox returns a parseable local forwarding address");
+ assert!(endpoint.port().is_some(), "forwarded address has an assigned port");
provisioned.tear_down().await;
}
diff --git a/crates/openhuman-app/src/gateway/provision.rs b/crates/openhuman-app/src/gateway/provision.rs
index 13e44925fe..8a78d8f0bd 100644
--- a/crates/openhuman-app/src/gateway/provision.rs
+++ b/crates/openhuman-app/src/gateway/provision.rs
@@ -1,43 +1,20 @@
-//! Making a box run a core, and making that core reachable from here.
+//! Provision a core through OpenHuman's typed TinyBox module facade.
//!
-//! Four steps, each one tinybox call:
-//!
-//! 1. `create` a box, publishing the core's port to whichever machine it runs on
-//! 2. `spawn` the core in it, detached, with a freshly minted bearer
-//! 3. `forward` that published port back to this machine
-//! 4. poll the core's unauthenticated `/health` until it answers
-//!
-//! Step 3 is the one that is easy to leave out and impossible to notice
-//! missing: publishing puts the port on the *box's* host, which for an SSH
-//! placement is the far machine. Everything looks configured and nothing is
-//! reachable.
-//!
-//! Step 4 is not a courtesy either. A tunnel's local listener exists before the
-//! far side is proven, so "the forward opened" is not "the core is up".
+//! The host chooses the placement, workspace, network policy, and core
+//! credentials. TinyBox owns every native sandbox, process, and forward handle.
use std::collections::BTreeMap;
-use std::sync::Arc;
+use std::net::SocketAddr;
use std::time::Duration;
-use tinybox_core::{
- BoxId, BoxInfo, BoxSpec, ExecRequest, Host, NetworkPolicy, PassthroughSandbox, Placement,
- PortMapping, ProcessId, Sandbox, WorkspaceSource,
-};
-use tinybox_docker::DockerSandbox;
-use tinybox_host::LocalHost;
-use tinybox_ssh::{SshHost, SshTarget};
+use openhuman_rpc::embed::config::RuntimeConfig;
+use openhuman_rpc::embed::modules::tinybox::{self, contract};
use super::ops::{ProgressSink, Provisioned};
use super::types::{ActiveGateway, Confinement, Gateway, Reach, SshReach, CORE_PORT_IN_BOX};
/// How long to wait for a provisioned core to answer `/health`.
-///
-/// Generous because this covers a container start, the core's own boot, and
-/// possibly an image pull - and because polling returns the moment it answers,
-/// so a high ceiling costs nothing when things are fast. Mirrors the embedded
-/// core's own ceiling in `core_process`.
const HEALTH_TIMEOUT: Duration = Duration::from_secs(120);
-
/// How often to re-ask while waiting.
const HEALTH_POLL: Duration = Duration::from_millis(250);
@@ -49,54 +26,115 @@ pub(super) async fn provision(
env: &BTreeMap<String, String>,
progress: &ProgressSink,
) -> Result<Provisioned, String> {
- let host = build_host(reach)?;
- let sandbox = build_sandbox(confinement, &host);
-
- // Minted here and handed to the core as an environment variable, so it is
- // never written to disk and never reused across activations. The core
- // reads `OPENHUMAN_CORE_TOKEN` and gates `/rpc` on it; `/health` stays
- // unauthenticated, which is what makes the readiness poll below possible
- // before any credential is established.
+ // This is intentionally loaded through the curated facade: gateway
+ // activation happens before the embedded RPC server may exist.
+ let config = openhuman_rpc::embed::config::load_config_with_timeout().await?;
let token = crate::core_process::generate_rpc_token();
+ progress("reserving the box");
+ let resource = tinybox::reserve(&config, contract::ReserveRequest::Resource)
+ .await
+ .map_err(|error| format!("could not reserve the box: {error}"))?;
+
progress("creating the box");
- let (info, host_port) = create_box(sandbox.as_ref(), reach, confinement, env).await?;
+ let request = create_request(resource.clone(), reach, confinement, env);
+ let info = match tinybox::create(&config, request).await {
+ Ok(info) if info.resource == resource => info,
+ Ok(_) => {
+ close_quietly(&config, resource).await;
+ return Err("TinyBox returned a mismatched resource reservation".to_owned());
+ }
+ Err(error) => {
+ // The reply may have been lost after native creation. The
+ // reservation is caller-known, so Close can still clean it up.
+ close_quietly(&config, resource).await;
+ return Err(format!("could not create the box: {error}"));
+ }
+ };
log::info!(
- "[gateway][provision] box {} created ({}) publishing {host_port}",
- info.id,
- sandbox.name()
+ "[gateway][provision] TinyBox resource created for {}",
+ gateway.id
);
progress("starting the core");
- let started = start_core(sandbox.as_ref(), &info.id, confinement, &token).await;
- let process = match started {
+ let process_reservation = match tinybox::reserve(
+ &config,
+ contract::ReserveRequest::Process(info.resource.clone()),
+ )
+ .await
+ {
Ok(process) => process,
Err(error) => {
- // Do not leave a box behind for a core that never started.
- destroy_quietly(sandbox.as_ref(), &info.id).await;
- return Err(error);
+ close_quietly(&config, resource).await;
+ return Err(format!("could not reserve the core process: {error}"));
+ }
+ };
+ let command = core_command(&info.resource, confinement, &token);
+ let process = match tinybox::spawn(
+ &config,
+ contract::SpawnRequest {
+ process: process_reservation,
+ command,
+ },
+ )
+ .await
+ {
+ Ok(process) if process.resource == info.resource => process,
+ Ok(_) => {
+ close_quietly(&config, resource).await;
+ return Err("TinyBox returned a mismatched process resource".to_owned());
+ }
+ Err(error) => {
+ close_quietly(&config, resource).await;
+ return Err(format!("could not start the core in the box: {error}"));
}
};
progress("opening the connection");
- let forwarded = host
- .forward(([127, 0, 0, 1], host_port).into())
- .await
- .map_err(|error| format!("could not reach the box: {error}"));
- let forwarded = match forwarded {
- Ok(forwarded) => forwarded,
+ let forward_reservation = match tinybox::reserve(
+ &config,
+ contract::ReserveRequest::Forward(info.resource.clone()),
+ )
+ .await
+ {
+ Ok(forward) => forward,
Err(error) => {
- stop_quietly(sandbox.as_ref(), &info.id, &process).await;
- destroy_quietly(sandbox.as_ref(), &info.id).await;
- return Err(error);
+ close_quietly(&config, resource).await;
+ return Err(format!("could not reserve the gateway connection: {error}"));
}
};
+ let forward = match tinybox::forward(
+ &config,
+ contract::ForwardRequest {
+ resource: info.resource.clone(),
+ forward: forward_reservation,
+ guest_port: CORE_PORT_IN_BOX,
+ },
+ )
+ .await
+ {
+ Ok(forward) if forward.resource == info.resource => forward,
+ Ok(_) => {
+ close_quietly(&config, resource).await;
+ return Err("TinyBox returned a mismatched forward resource".to_owned());
+ }
+ Err(error) => {
+ close_quietly(&config, resource).await;
+ return Err(format!("could not reach the box: {error}"));
+ }
+ };
+ let address: SocketAddr = match forward.local_address.parse() {
+ Ok(address) => address,
+ Err(_) => {
+ close_quietly(&config, resource).await;
+ return Err("TinyBox returned an invalid gateway address".to_owned());
+ }
+ };
+ let rpc_base = format!("http://{address}");
- let rpc_base = format!("http://{}", forwarded.local_addr());
progress("waiting for the core");
if let Err(error) = wait_until_healthy(&rpc_base).await {
- stop_quietly(sandbox.as_ref(), &info.id, &process).await;
- destroy_quietly(sandbox.as_ref(), &info.id).await;
+ close_quietly(&config, resource).await;
return Err(error);
}
@@ -110,301 +148,118 @@ pub(super) async fn provision(
rpc_url: format!("{rpc_base}/rpc"),
token: Some(token),
},
- _forward: Some(forwarded),
- sandbox,
- box_id: info.id,
+ config,
+ resource,
process,
})
}
-/// The host a box's commands run on.
-fn build_host(reach: &Reach) -> Result<Arc<dyn Host>, String> {
- match reach {
- Reach::Local => Ok(Arc::new(LocalHost::new())),
- Reach::Ssh(ssh) => Ok(Arc::new(SshHost::new(
- // Always local: `SshHost` opens its tunnel from its inner host, and
- // a chained one would open it on the wrong machine. tinybox refuses
- // that case rather than reporting an address leading nowhere.
- Arc::new(LocalHost::new()),
- ssh_target(ssh)?,
- ))),
- }
-}
-
-fn ssh_target(ssh: &SshReach) -> Result<SshTarget, String> {
- let mut target = SshTarget::new(ssh.destination.clone())
- .map_err(|error| format!("that SSH destination is not usable: {error}"))?;
- if let Some(port) = ssh.port {
- target = target.with_port(port);
- }
- if let Some(identity) = &ssh.identity {
- target = target.with_identity(identity.clone());
- }
- if ssh.accept_new_host_key {
- target = target.accepting_new_host_key();
- }
- Ok(target)
-}
-
-/// The sandbox a box is created in.
-fn build_sandbox(confinement: &Confinement, host: &Arc<dyn Host>) -> Arc<dyn Sandbox> {
- // An in-memory store: these boxes exist for as long as this process holds
- // the gateway open, and a file store would outlive that — leaving records
- // for containers a later run has no tunnel to and no reason to trust.
- let store = Arc::new(tinybox_core::MemoryStore::new());
- match confinement {
- Confinement::Passthrough { .. } => {
- Arc::new(PassthroughSandbox::new(host.clone(), store)) as Arc<dyn Sandbox>
- }
- Confinement::Docker { .. } => {
- Arc::new(DockerSandbox::new(host.clone(), store)) as Arc<dyn Sandbox>
- }
- }
-}
-
-/// The spec the box is created from.
-pub(super) fn box_spec(
+/// Construct the module request without exposing TinyBox implementation types.
+fn create_request(
+ resource: contract::ResourceId,
reach: &Reach,
confinement: &Confinement,
env: &BTreeMap<String, String>,
- host_port: u16,
-) -> Result<BoxSpec, String> {
- let host_ref = match reach {
- Reach::Local => "local",
- Reach::Ssh(_) => "ssh",
- };
- let (sandbox_ref, source) = match confinement {
+) -> contract::CreateRequest {
+ let (backend, workspace, network, ports) = match confinement {
Confinement::Passthrough { workspace, .. } => (
"passthrough",
- WorkspaceSource::LocalDir(
+ contract::Workspace::Directory(
workspace
.clone()
- .unwrap_or_else(|| std::path::PathBuf::from("/tmp")),
+ .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
+ .display()
+ .to_string(),
),
+ contract::NetworkPolicy::Open,
+ Vec::new(),
+ ),
+ Confinement::Docker { image } => (
+ "docker",
+ contract::Workspace::Image(image.clone()),
+ contract::NetworkPolicy::Egress,
+ vec![contract::PortMapping {
+ guest: CORE_PORT_IN_BOX,
+ host: None,
+ }],
),
- Confinement::Docker { image } => ("docker", WorkspaceSource::OciImage(image.clone())),
};
- let placement = Placement::new(
- tinybox_core::HostRef::new(host_ref)
- .map_err(|error| format!("invalid host reference: {error}"))?,
- tinybox_core::SandboxRef::new(sandbox_ref)
- .map_err(|error| format!("invalid sandbox reference: {error}"))?,
- );
-
- let mut spec = BoxSpec::new(placement, source);
- for (key, value) in env {
- spec = spec.with_env(key, value);
+ contract::CreateRequest {
+ resource,
+ backend: backend.to_owned(),
+ host: host_config(reach),
+ workspace,
+ network,
+ resources: contract::ResourceLimits::default(),
+ ports,
+ env: env.clone(),
}
+}
- if matches!(confinement, Confinement::Docker { .. }) {
- // Publishing is how the core is reached at all, and tinybox drops the
- // `--publish` flags entirely on a box whose network is denied — a
- // container with no network has nowhere for a published port to lead.
- // `Egress` is the weakest policy that still publishes; the core needs
- // outbound anyway to reach the TinyHumans backend.
- spec = spec.with_network(NetworkPolicy::Egress);
- // `fixed(guest, host)`, in that order: the core listens on
- // CORE_PORT_IN_BOX *inside* the box, and that is what gets published
- // at `host_port` on the machine the box runs on. Reversed, the box
- // would publish a port nothing is listening on.
- spec = spec.with_port(PortMapping::fixed(CORE_PORT_IN_BOX, host_port));
+fn host_config(reach: &Reach) -> contract::HostConfig {
+ match reach {
+ Reach::Local => contract::HostConfig::Local,
+ Reach::Ssh(ssh) => contract::HostConfig::Ssh(contract::SshHostConfig {
+ destination: ssh.destination.clone(),
+ port: ssh.port,
+ identity: ssh.identity.as_ref().map(|path| path.display().to_string()),
+ known_hosts: None,
+ accept_new_host_key: ssh.accept_new_host_key,
+ }),
}
- Ok(spec)
}
-/// The command that starts `openhuman-core` in a box.
-///
-/// Pure and separate from running it, for the reason tinybox's own backends
-/// keep command construction in an `args` module: which binary is named and
-/// what environment it is handed are the decisions worth asserting, and they
-/// should be values rather than something only observable by starting a
-/// container.
-pub(super) fn core_command(confinement: &Confinement, token: &str) -> ExecRequest {
+/// Build the explicit core command passed to TinyBox.
+fn core_command(
+ resource: &contract::ResourceId,
+ confinement: &Confinement,
+ token: &str,
+) -> contract::ExecRequest {
let binary = match confinement {
Confinement::Passthrough { binary, .. } => binary.display().to_string(),
- // The image's own core, on `PATH`. Naming a path here would tie the
- // gateway to one image's layout.
Confinement::Docker { .. } => "openhuman-core".to_owned(),
};
-
- ExecRequest::new([binary.as_str(), "serve"])
- // Handed over as environment and never written down: minted per
- // activation, so a stored gateway record cannot leak a credential for
- // a core that is still running.
- .with_env("OPENHUMAN_CORE_TOKEN", token)
- // Bind every interface *inside the box*, so the published port has
- // something to reach. Loopback there would be reachable only from
- // inside the container, which is the one place nothing is asking.
- .with_env("OPENHUMAN_CORE_HOST", "0.0.0.0")
- .with_env("OPENHUMAN_CORE_PORT", CORE_PORT_IN_BOX.to_string())
-}
-
-/// Start `openhuman-core` in the box, detached, and return its handle.
-async fn start_core(
- sandbox: &dyn Sandbox,
- box_id: &BoxId,
- confinement: &Confinement,
- token: &str,
-) -> Result<ProcessId, String> {
- sandbox
- .spawn(box_id, &core_command(confinement, token))
- .await
- .map_err(|error| format!("could not start the core in the box: {error}"))
-}
-
-/// How many times to retry creation when the chosen host port is taken.
-const PORT_ATTEMPTS: usize = 8;
-
-/// Create the box, choosing a port on its machine that is actually free.
-///
-/// # Why the port is named rather than left to Docker
-///
-/// `PortMapping::dynamic` lets Docker pick, which is the better choice in
-/// general — and unusable here, because the number it picks is recorded only in
-/// Docker's own state and tinybox has no call that reports it back. A forward
-/// needs that number.
-///
-/// So the port is named, which means it can collide. On the local machine that
-/// is checkable; on a remote one it is not — asking would mean running a probe
-/// over there, and there is no command every host is guaranteed to have. Both
-/// cases are therefore handled the same way: pick, try, and pick again if the
-/// backend says the port is taken. A wrong guess is a fast, specific failure
-/// from Docker rather than something silent.
-async fn create_box(
- sandbox: &dyn Sandbox,
- reach: &Reach,
- confinement: &Confinement,
- env: &BTreeMap<String, String>,
-) -> Result<(BoxInfo, u16), String> {
- // A passthrough box has no boundary to publish across: the core listens on
- // the machine's own port, so there is nothing to choose and nothing that
- // could collide beyond the core itself.
- if matches!(confinement, Confinement::Passthrough { .. }) {
- let spec = box_spec(reach, confinement, env, CORE_PORT_IN_BOX)?;
- let info = sandbox
- .create(&spec)
- .await
- .map_err(|error| format!("could not create the box: {error}"))?;
- return Ok((info, CORE_PORT_IN_BOX));
- }
-
- let mut last = String::new();
- for attempt in 1..=PORT_ATTEMPTS {
- let host_port = candidate_port(reach);
- let spec = box_spec(reach, confinement, env, host_port)?;
- match sandbox.create(&spec).await {
- Ok(info) => return Ok((info, host_port)),
- Err(error) => {
- last = error.to_string();
- if !is_port_conflict(&last) {
- return Err(format!("could not create the box: {last}"));
- }
- log::debug!(
- "[gateway][provision] port {host_port} is taken (attempt {attempt}/{PORT_ATTEMPTS})"
- );
- }
+ let mut env = BTreeMap::new();
+ env.insert("OPENHUMAN_CORE_TOKEN".to_owned(), token.to_owned());
+ env.insert("OPENHUMAN_CORE_HOST".to_owned(), "0.0.0.0".to_owned());
+ env.insert(
+ "OPENHUMAN_CORE_PORT".to_owned(),
+ CORE_PORT_IN_BOX.to_string(),
+ );
+ let cwd = match confinement {
+ Confinement::Passthrough { workspace, .. } => {
+ workspace.as_ref().map(|path| path.display().to_string())
}
+ Confinement::Docker { .. } => None,
+ };
+ contract::ExecRequest {
+ resource: resource.clone(),
+ argv: vec![binary, "serve".to_owned()],
+ cwd,
+ env,
+ stdin: None,
}
- Err(format!(
- "could not find a free port on the box's machine after {PORT_ATTEMPTS} attempts ({last})"
- ))
}
-/// A port to try publishing on.
-///
-/// Locally the operating system is asked, which makes a collision very
-/// unlikely. Remotely there is nothing to ask, so a port is drawn from the
-/// ephemeral range and [`create_box`] retries if it was taken.
-fn candidate_port(reach: &Reach) -> u16 {
- if matches!(reach, Reach::Local) {
- if let Some(port) = free_local_port() {
- return port;
- }
+async fn close_quietly(config: &RuntimeConfig, resource: contract::ResourceId) {
+ if let Err(error) = tinybox::close(config, resource).await {
+ log::warn!("[gateway][teardown] TinyBox cleanup remains pending: {error}");
}
- // Draw from the ephemeral range rather than counting up from a fixed base:
- // two OpenHuman instances against the same remote machine would otherwise
- // collide on their first attempt every time, and again on their second.
- use rand::Rng as _;
- rand::rng().random_range(49_152..=65_535)
-}
-
-/// A free port on this machine, or `None` if one cannot be reserved.
-fn free_local_port() -> Option<u16> {
- std::net::TcpListener::bind(("127.0.0.1", 0))
- .and_then(|listener| listener.local_addr())
- .map(|address| address.port())
- .ok()
-}
-
-/// Whether a backend's refusal was about the port rather than anything else.
-///
-/// Matched on text because that is what the backend gives us: tinybox passes
-/// Docker's own diagnostic through verbatim, deliberately, since it is more
-/// specific than anything tinybox could reconstruct. A miss here costs a retry
-/// that fails the same way, not a wrong outcome — the next attempt surfaces
-/// whatever the real error was.
-pub(super) fn is_port_conflict(message: &str) -> bool {
- let lowered = message.to_ascii_lowercase();
- lowered.contains("port is already allocated")
- || lowered.contains("address already in use")
- || (lowered.contains("bind") && lowered.contains("already"))
}
/// Poll `/health` until the core answers, or give up.
-///
-/// `/health` is unauthenticated by design, which is what makes this possible
-/// before the bearer matters — and it is a genuinely necessary step rather than
-/// a courtesy: a tunnel's local listener exists before the far side is proven,
-/// so "the forward opened" is not "the core is up".
async fn wait_until_healthy(base_url: &str) -> Result<(), String> {
- let client = reqwest::Client::builder()
- .timeout(Duration::from_secs(5))
- .build()
- .map_err(|error| format!("could not build an HTTP client: {error}"))?;
- let url = format!("{base_url}/health");
let deadline = tokio::time::Instant::now() + HEALTH_TIMEOUT;
-
+ let client = reqwest::Client::new();
loop {
- // Kept so the timeout message can name why it never answered.
- // "did not become reachable" alone sends an operator looking at the
- // network when the core was answering 503 the whole time.
- let detail = match client.get(&url).send().await {
- Ok(response) if response.status().is_success() => {
- log::debug!("[gateway][health] {base_url} is up");
- return Ok(());
- }
- Ok(response) => format!("HTTP {}", response.status()),
- Err(error) => error.to_string(),
- };
-
+ match client.get(format!("{base_url}/health")).send().await {
+ Ok(response) if response.status().is_success() => return Ok(()),
+ Ok(_) | Err(_) => {}
+ }
if tokio::time::Instant::now() >= deadline {
- return Err(format!(
- "the core did not become reachable within {}s ({detail})",
- HEALTH_TIMEOUT.as_secs()
- ));
+ return Err("the core did not become healthy within two minutes".to_owned());
}
tokio::time::sleep(HEALTH_POLL).await;
}
}
-
-/// Destroy a box, logging rather than propagating a failure.
-///
-/// Used on the failure paths, where the error the caller is about to see is the
-/// one that matters — a cleanup failure on top of it would bury the cause.
-async fn destroy_quietly(sandbox: &dyn Sandbox, box_id: &BoxId) {
- if let Err(error) = sandbox.destroy(box_id).await {
- log::warn!("[gateway][provision] could not clean up box {box_id}: {error}");
- }
-}
-
-/// Stop a started core process, logging rather than propagating a failure.
-///
-/// `Sandbox::destroy` on a passthrough box only removes the box record — it
-/// does not stop the detached `ProcessId` — so on the forward and health-error
-/// paths the core must be stopped explicitly or it keeps running headless.
-async fn stop_quietly(sandbox: &dyn Sandbox, box_id: &BoxId, process: &ProcessId) {
- if let Err(error) = sandbox.stop(box_id, process).await {
- log::warn!("[gateway][provision] could not stop core {process} in box {box_id}: {error}");
- }
-}
diff --git a/crates/openhuman-app/src/gateway/registry.rs b/crates/openhuman-app/src/gateway/registry.rs
index fff4f46dbf..851b2b759d 100644
--- a/crates/openhuman-app/src/gateway/registry.rs
+++ b/crates/openhuman-app/src/gateway/registry.rs
@@ -1,9 +1,7 @@
//! Which gateway is active, and what is being held open for it.
//!
-//! A provisioned gateway is only as alive as the values holding it open: drop
-//! the [`Forward`](tinybox_core::Forward) and the tunnel closes. So the process
-//! needs somewhere to keep them for as long as the gateway is selected, and
-//! that is here.
+//! A provisioned gateway is only as alive as its module-owned TinyBox resource.
+//! The selected resource handle stays here until `tear_down` awaits its cleanup.
//!
//! Everything is behind one lock and every write goes through
//! [`activate`], so two screens racing to switch gateways cannot leave the
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index fae3ef7afb..81c3fbbe06 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -144,6 +144,7 @@ tinybox-docker = { path = "../../vendor/tinybox/crates/tinybox-docker" }
# Quote-aware shell command-string scanners (`tinybox_core::shell::scan`); the
# classification policy built on them stays in `security::policy`.
tinybox-core = { path = "../../vendor/tinybox/crates/tinybox-core" }
+tinybox-bus = { path = "../../vendor/tinybox/crates/tinybox-bus", optional = true }
tinyagents-definition = { path = "../../vendor/tinyagents/crates/tinyagents-definition" }
# Live (realtime voice) agent sessions: `tinyagents-live` runs a
# `tinyliveagents` provider session (Gemini Live direct/relayed, ElevenLabs
@@ -765,7 +766,7 @@ tinymemes = ["dep:tinymemes"]
# A loaded module is trusted in-process code with this process's privileges, and
# tinybus never unloads one. See `crates/openhuman-core/src/modules/` before adding an entry
# to the registry.
-modules = ["tinybus/modules"]
+modules = ["tinybus/modules", "dep:tinybox-bus"]
# Voice + audio_toolkit domains: STT/TTS providers, the standalone dictation
# server, always-on listening, and podcast audio generation/email delivery.
# Default-ON — the desktop app always ships with voice. Slim / headless builds
diff --git a/crates/openhuman-core/src/modules/client.rs b/crates/openhuman-core/src/modules/client.rs
index d28b822129..14e9811212 100644
--- a/crates/openhuman-core/src/modules/client.rs
+++ b/crates/openhuman-core/src/modules/client.rs
@@ -135,6 +135,13 @@ impl ModuleClient {
}
}
+ /// Report a registered module that advertises an older wire contract.
+ pub(crate) fn report_incompatible_contract(module: &str) {
+ if let Some(record) = registry::find(module) {
+ failure::report(record, failure::Reason::IncompatibleContract);
+ }
+ }
+
/// Report a known module that does not provide the requested capability.
pub(crate) fn report_unavailable(module: &str) {
if let Some(record) = registry::find(module) {
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index f917046aba..f95597fe1b 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -71,6 +71,8 @@ pub mod schemas;
#[cfg(feature = "modules")]
pub mod search;
#[cfg(feature = "modules")]
+pub mod tinybox;
+#[cfg(feature = "modules")]
mod tokenjuice_host;
pub mod types;
#[cfg(feature = "voice")]
diff --git a/crates/openhuman-core/src/modules/registry/records_extra.rs b/crates/openhuman-core/src/modules/registry/records_extra.rs
index 69bc7b739a..851d2f9df1 100644
--- a/crates/openhuman-core/src/modules/registry/records_extra.rs
+++ b/crates/openhuman-core/src/modules/registry/records_extra.rs
@@ -8,63 +8,63 @@ pub(crate) const TINYBOX: ModuleRecord = ModuleRecord {
description: "Sandbox capability discovery through TinyBox",
bus_name: "ai.tinyhumans.tinybox.Box",
object_path: "/ai/tinyhumans/tinybox/Box",
- version: "0.1.16",
- release_url: "https://github.com/tinyhumansai/tinybox/releases/tag/v0.1.16",
+ version: "0.1.18",
+ release_url: "https://github.com/tinyhumansai/tinybox/releases/tag/v0.1.18",
assets: &[
PlatformAsset {
host_key: "ubuntu-24.04-x86_64",
- archive: "tinybox-0.1.16-ubuntu-24.04-x86_64.tar.gz",
- sha256: "3163f7cf621beaf71d99b978555085e6bb933a0810153970dd16b2c531e1a030",
+ archive: "tinybox-0.1.18-ubuntu-24.04-x86_64.tar.gz",
+ sha256: "232934349cb0ece8f049c00e5d15e38e30248a100cd9b66b203e69aee23145da",
},
PlatformAsset {
host_key: "ubuntu-24.04-arm64",
- archive: "tinybox-0.1.16-ubuntu-24.04-arm64.tar.gz",
- sha256: "fad323bf74ce075f758a31c7cb93f393d84ac4c9a6a22f31fb7fc7e2ec4743c4",
+ archive: "tinybox-0.1.18-ubuntu-24.04-arm64.tar.gz",
+ sha256: "994a37f95e128cd1b54999a9d4eebf012eaeb17b6a3006c9985a83b10e4ee6e1",
},
PlatformAsset {
host_key: "ubuntu-22.04-x86_64",
- archive: "tinybox-0.1.16-ubuntu-22.04-x86_64.tar.gz",
- sha256: "9abddc0e8ad14ac9f34e479714baa7f1720ed029d199272214450f356b7d51da",
+ archive: "tinybox-0.1.18-ubuntu-22.04-x86_64.tar.gz",
+ sha256: "f8210816dfacd7ee58dcfb4482845f40ee4dbb435f706c2e154e9542a15f8329",
},
PlatformAsset {
host_key: "ubuntu-22.04-arm64",
- archive: "tinybox-0.1.16-ubuntu-22.04-arm64.tar.gz",
- sha256: "fb164eeec76789035de8c621176630b6ea6aea0a5021778fbd97fafe163b6dac",
+ archive: "tinybox-0.1.18-ubuntu-22.04-arm64.tar.gz",
+ sha256: "b192c1ce4333b8668ec9f38a0197aeb443c5a9afd63d5f9b617a6de97f080f4b",
},
PlatformAsset {
host_key: "macos-26-arm64",
- archive: "tinybox-0.1.16-macos-26-arm64.tar.gz",
- sha256: "34cb87457a3b21ec5ee8b8b6817f6a78a854b12e4d40fa43221aeed508d7c40a",
+ archive: "tinybox-0.1.18-macos-26-arm64.tar.gz",
+ sha256: "6d7c9120f6f773861ed0901360142ad0c131fe9597d937a21788891a6cae9663",
},
PlatformAsset {
host_key: "macos-26-x86_64",
- archive: "tinybox-0.1.16-macos-26-x86_64.tar.gz",
- sha256: "5f7a4886fb191a58dc33bb5f43a7034c0f6b31c1e85161e13228aa0deb6ae5b9",
+ archive: "tinybox-0.1.18-macos-26-x86_64.tar.gz",
+ sha256: "7e61a78a8ea82aec31692d84979169ba72202ac7698ecac7cf515445f911473d",
},
PlatformAsset {
host_key: "macos-15-arm64",
- archive: "tinybox-0.1.16-macos-15-arm64.tar.gz",
- sha256: "ae427b7962b0607051595c9c12f9cb630c87672bc3c92c7becdac87283aaefd4",
+ archive: "tinybox-0.1.18-macos-15-arm64.tar.gz",
+ sha256: "b827b00712d8ea5eaf081be9bb8d9e5283dd29fbf34c1dc8d26d15a64224483b",
},
PlatformAsset {
host_key: "macos-15-x86_64",
- archive: "tinybox-0.1.16-macos-15-x86_64.tar.gz",
- sha256: "417d4c182c3882cd90b5ff323dc81c62c2d98b3e0bb8ac0a237cac51c34828fe",
+ archive: "tinybox-0.1.18-macos-15-x86_64.tar.gz",
+ sha256: "c4526cc2f05137d1d82d8a41681403c3c74d0c585a7ff51c4dd49ff3f2eb9694",
},
PlatformAsset {
host_key: "windows-2025-x86_64",
- archive: "tinybox-0.1.16-windows-2025-x86_64.zip",
- sha256: "ada7ddb1edf16887ef20d84241f0453b2ce8ee29aa670c1505758c1f7913b4fc",
+ archive: "tinybox-0.1.18-windows-2025-x86_64.zip",
+ sha256: "c320392f979d3298c4bcecb4b54f18db40d49bb546634a441219eef9f5fbf592",
},
PlatformAsset {
host_key: "windows-2022-x86_64",
- archive: "tinybox-0.1.16-windows-2022-x86_64.zip",
- sha256: "044666f53b10c8db6626262de45806d1a2a34147ce2de196e8549987f32c1cd8",
+ archive: "tinybox-0.1.18-windows-2022-x86_64.zip",
+ sha256: "d06c300eb7651147e9c7672e1377f25cc88e824be6afadfdafd4ec7eb6f5f8d1",
},
PlatformAsset {
host_key: "windows-11-arm64",
- archive: "tinybox-0.1.16-windows-11-arm64.zip",
- sha256: "bc3da524fc3e702e77cc1e85c064dccaece633f896503737c71ce7127ba26440",
+ archive: "tinybox-0.1.18-windows-11-arm64.zip",
+ sha256: "b3a26410b6a7adda83ae9ce23e0716367e06c3561e8a2f9ffbe30b6820ccae89",
},
],
load: LoadPolicy::Lazy,
diff --git a/crates/openhuman-core/src/modules/registry_tests.rs b/crates/openhuman-core/src/modules/registry_tests.rs
index 244e02d355..162c72980a 100644
--- a/crates/openhuman-core/src/modules/registry_tests.rs
+++ b/crates/openhuman-core/src/modules/registry_tests.rs
@@ -15,12 +15,12 @@ fn tinycomputer_registry_matches_bus_contract_and_published_release() {
}
#[test]
-fn tinybox_registry_matches_the_published_v0116_release_manifest() {
+fn tinybox_registry_matches_the_published_v0118_release_manifest() {
let record = find("tinybox").expect("compiled TinyBox module");
- assert_eq!(record.version, "0.1.16");
+ assert_eq!(record.version, "0.1.18");
assert_eq!(
record.release_url,
- "https://github.com/tinyhumansai/tinybox/releases/tag/v0.1.16"
+ "https://github.com/tinyhumansai/tinybox/releases/tag/v0.1.18"
);
let actual = record
@@ -31,58 +31,58 @@ fn tinybox_registry_matches_the_published_v0116_release_manifest() {
let published = [
(
"ubuntu-24.04-x86_64",
- "tinybox-0.1.16-ubuntu-24.04-x86_64.tar.gz",
- "3163f7cf621beaf71d99b978555085e6bb933a0810153970dd16b2c531e1a030",
+ "tinybox-0.1.18-ubuntu-24.04-x86_64.tar.gz",
+ "232934349cb0ece8f049c00e5d15e38e30248a100cd9b66b203e69aee23145da",
),
(
"ubuntu-24.04-arm64",
- "tinybox-0.1.16-ubuntu-24.04-arm64.tar.gz",
- "fad323bf74ce075f758a31c7cb93f393d84ac4c9a6a22f31fb7fc7e2ec4743c4",
+ "tinybox-0.1.18-ubuntu-24.04-arm64.tar.gz",
+ "994a37f95e128cd1b54999a9d4eebf012eaeb17b6a3006c9985a83b10e4ee6e1",
),
(
"ubuntu-22.04-x86_64",
- "tinybox-0.1.16-ubuntu-22.04-x86_64.tar.gz",
- "9abddc0e8ad14ac9f34e479714baa7f1720ed029d199272214450f356b7d51da",
+ "tinybox-0.1.18-ubuntu-22.04-x86_64.tar.gz",
+ "f8210816dfacd7ee58dcfb4482845f40ee4dbb435f706c2e154e9542a15f8329",
),
(
"ubuntu-22.04-arm64",
- "tinybox-0.1.16-ubuntu-22.04-arm64.tar.gz",
- "fb164eeec76789035de8c621176630b6ea6aea0a5021778fbd97fafe163b6dac",
+ "tinybox-0.1.18-ubuntu-22.04-arm64.tar.gz",
+ "b192c1ce4333b8668ec9f38a0197aeb443c5a9afd63d5f9b617a6de97f080f4b",
),
(
"macos-26-arm64",
- "tinybox-0.1.16-macos-26-arm64.tar.gz",
- "34cb87457a3b21ec5ee8b8b6817f6a78a854b12e4d40fa43221aeed508d7c40a",
+ "tinybox-0.1.18-macos-26-arm64.tar.gz",
+ "6d7c9120f6f773861ed0901360142ad0c131fe9597d937a21788891a6cae9663",
),
(
"macos-26-x86_64",
- "tinybox-0.1.16-macos-26-x86_64.tar.gz",
- "5f7a4886fb191a58dc33bb5f43a7034c0f6b31c1e85161e13228aa0deb6ae5b9",
+ "tinybox-0.1.18-macos-26-x86_64.tar.gz",
+ "7e61a78a8ea82aec31692d84979169ba72202ac7698ecac7cf515445f911473d",
),
(
"macos-15-arm64",
- "tinybox-0.1.16-macos-15-arm64.tar.gz",
- "ae427b7962b0607051595c9c12f9cb630c87672bc3c92c7becdac87283aaefd4",
+ "tinybox-0.1.18-macos-15-arm64.tar.gz",
+ "b827b00712d8ea5eaf081be9bb8d9e5283dd29fbf34c1dc8d26d15a64224483b",
),
(
"macos-15-x86_64",
- "tinybox-0.1.16-macos-15-x86_64.tar.gz",
- "417d4c182c3882cd90b5ff323dc81c62c2d98b3e0bb8ac0a237cac51c34828fe",
+ "tinybox-0.1.18-macos-15-x86_64.tar.gz",
+ "c4526cc2f05137d1d82d8a41681403c3c74d0c585a7ff51c4dd49ff3f2eb9694",
),
(
"windows-2025-x86_64",
- "tinybox-0.1.16-windows-2025-x86_64.zip",
- "ada7ddb1edf16887ef20d84241f0453b2ce8ee29aa670c1505758c1f7913b4fc",
+ "tinybox-0.1.18-windows-2025-x86_64.zip",
+ "c320392f979d3298c4bcecb4b54f18db40d49bb546634a441219eef9f5fbf592",
),
(
"windows-2022-x86_64",
- "tinybox-0.1.16-windows-2022-x86_64.zip",
- "044666f53b10c8db6626262de45806d1a2a34147ce2de196e8549987f32c1cd8",
+ "tinybox-0.1.18-windows-2022-x86_64.zip",
+ "d06c300eb7651147e9c7672e1377f25cc88e824be6afadfdafd4ec7eb6f5f8d1",
),
(
"windows-11-arm64",
- "tinybox-0.1.16-windows-11-arm64.zip",
- "bc3da524fc3e702e77cc1e85c064dccaece633f896503737c71ce7127ba26440",
+ "tinybox-0.1.18-windows-11-arm64.zip",
+ "b3a26410b6a7adda83ae9ce23e0716367e06c3561e8a2f9ffbe30b6820ccae89",
),
];
diff --git a/crates/openhuman-core/src/modules/tinybox.rs b/crates/openhuman-core/src/modules/tinybox.rs
new file mode 100644
index 0000000000..bfd5cfdeb7
--- /dev/null
+++ b/crates/openhuman-core/src/modules/tinybox.rs
@@ -0,0 +1,322 @@
+//! Host calls to the TinyBox sandbox module.
+//!
+//! This adapter owns only OpenHuman's module loading and bus boundary. Request
+//! and response types come from `tinybox-bus`; isolation, process ownership,
+//! file access, forwarding, and output collection stay in TinyBox.
+
+use std::time::Duration;
+
+use serde::{de::DeserializeOwned, Serialize};
+pub use tinybox_bus as contract;
+
+use crate::config::Config;
+
+use super::client::{ModuleCallError, ModuleClient};
+
+/// Registry id for the TinyBox module.
+pub const MODULE_ID: &str = "tinybox";
+
+const MODULE_CALL_TIMEOUT: Duration = Duration::from_secs(300);
+
+// `tinybox_bus::METHODS` is the canonical method catalogue. Its original
+// members retain their positions and additions are append-only; indexing here
+// avoids maintaining a second set of wire strings in the host.
+const DESCRIBE: &str = contract::METHODS[0];
+const CREATE: &str = contract::METHODS[1];
+const EXEC: &str = contract::METHODS[2];
+const INSPECT: &str = contract::METHODS[3];
+const CLOSE: &str = contract::METHODS[4];
+const SPAWN: &str = contract::METHODS[5];
+const IS_RUNNING: &str = contract::METHODS[6];
+const CANCEL: &str = contract::METHODS[7];
+const ANALYZE_SHELL: &str = contract::METHODS[8];
+const RESERVE: &str = contract::METHODS[9];
+const CAPABILITIES: &str = contract::METHODS[10];
+const SHUTDOWN: &str = contract::METHODS[11];
+const FORWARD: &str = contract::METHODS[12];
+const CLOSE_FORWARD: &str = contract::METHODS[13];
+const JAIL_STATUS: &str = contract::METHODS[14];
+const ANALYZE_COMMAND: &str = contract::METHODS[15];
+const BEGIN_FILE_READ: &str = contract::METHODS[16];
+const READ_FILE_CHUNK: &str = contract::METHODS[17];
+const FINISH_FILE_READ: &str = contract::METHODS[18];
+const BEGIN_FILE_WRITE: &str = contract::METHODS[19];
+const WRITE_FILE_CHUNK: &str = contract::METHODS[20];
+const FINISH_FILE_WRITE: &str = contract::METHODS[21];
+const ABORT_FILE_WRITE: &str = contract::METHODS[22];
+const START_EXEC: &str = contract::METHODS[23];
+const READ_OUTPUT: &str = contract::METHODS[24];
+const RELEASE_OUTPUT: &str = contract::METHODS[25];
+const START_JAILED_EXEC: &str = contract::METHODS[26];
+
+#[cfg(test)]
+#[path = "tinybox_tests.rs"]
+mod tests;
+
+/// Resolve TinyBox, require the bus contract supported by this host, and
+/// return its proxy.
+///
+/// The capability check is deliberate: the registry artifact may be older
+/// than this compiled host while a release is being rolled out. A package
+/// version alone does not prove which additive bus members it serves.
+///
+/// # Errors
+///
+/// Returns a safe loading, transport, or contract-version error. It does not
+/// include request arguments or filesystem paths.
+fn require_compatible(version: (u32, u32)) -> Result<(), ModuleCallError> {
+ if contract::is_compatible(version) {
+ return Ok(());
+ }
+ ModuleClient::report_incompatible_contract(MODULE_ID);
+ Err(ModuleCallError::IncompatibleContract)
+}
+
+/// Describe the loaded TinyBox module.
+pub async fn describe(config: &Config) -> Result<String, String> {
+ call(config, DESCRIBE, (), false).await
+}
+
+/// Read module capabilities after enforcing contract compatibility.
+pub async fn capabilities(config: &Config) -> Result<contract::ModuleCapabilities, String> {
+ let client = module_client(config);
+ let capabilities: contract::ModuleCapabilities = client
+ .call(MODULE_ID, CAPABILITIES, ())
+ .await
+ .map_err(message)?;
+ require_compatible(capabilities.contract_version).map_err(message)?;
+ Ok(capabilities)
+}
+
+/// Read the native jail facts; the caller applies its own policy to them.
+pub async fn jail_status(config: &Config) -> Result<contract::JailStatus, String> {
+ call(config, JAIL_STATUS, (), false).await
+}
+
+/// Reserve an opaque identifier before native startup.
+pub async fn reserve(
+ config: &Config,
+ request: contract::ReserveRequest,
+) -> Result<contract::ResourceId, String> {
+ call(config, RESERVE, (request,), false).await
+}
+
+/// Create a sandbox using its caller-known reservation.
+pub async fn create(
+ config: &Config,
+ request: contract::CreateRequest,
+) -> Result<contract::ResourceInfo, String> {
+ call(config, CREATE, (request,), true).await
+}
+
+/// Execute a collected command in a resource.
+pub async fn exec(
+ config: &Config,
+ request: contract::ExecRequest,
+) -> Result<contract::ExecOutput, String> {
+ call(config, EXEC, (request,), true).await
+}
+
+/// Inspect a module-owned resource.
+pub async fn inspect(
+ config: &Config,
+ resource: contract::ResourceId,
+) -> Result<contract::ResourceInfo, String> {
+ call(config, INSPECT, (resource,), false).await
+}
+
+/// Close a resource and wait for the module's native cleanup acknowledgement.
+pub async fn close(config: &Config, resource: contract::ResourceId) -> Result<(), String> {
+ call(config, CLOSE, (resource,), false).await
+}
+
+/// Shut down the module-owned resources.
+pub async fn shutdown(config: &Config) -> Result<(), String> {
+ call(config, SHUTDOWN, (), false).await
+}
+
+/// Start a detached process using a pre-reserved process id.
+pub async fn spawn(
+ config: &Config,
+ request: contract::SpawnRequest,
+) -> Result<contract::ProcessRef, String> {
+ call(config, SPAWN, (request,), true).await
+}
+
+/// Start a supervised process with live output collection.
+pub async fn start_exec(
+ config: &Config,
+ request: contract::SpawnRequest,
+) -> Result<contract::ProcessRef, String> {
+ call(config, START_EXEC, (request,), true).await
+}
+
+/// Start a process in the explicitly requested native directory jail.
+pub async fn start_jailed_exec(
+ config: &Config,
+ request: contract::SpawnRequest,
+ jail: contract::NativeJailConfig,
+) -> Result<contract::ProcessRef, String> {
+ call(config, START_JAILED_EXEC, (request, jail), true).await
+}
+
+/// Read a bounded output batch from a live or completed process.
+pub async fn read_output(
+ config: &Config,
+ process: contract::ProcessRef,
+ cursor: u64,
+) -> Result<contract::OutputBatch, String> {
+ call(config, READ_OUTPUT, (process, cursor), false).await
+}
+
+/// Release retained output and process ownership after terminal observation.
+pub async fn release_output(config: &Config, process: contract::ProcessRef) -> Result<(), String> {
+ call(config, RELEASE_OUTPUT, (process,), false).await
+}
+
+/// Check whether a detached process remains active.
+pub async fn is_running(config: &Config, process: contract::ProcessRef) -> Result<bool, String> {
+ call(config, IS_RUNNING, (process,), false).await
+}
+
+/// Cancel a detached process and wait for acknowledged cleanup.
+pub async fn cancel(config: &Config, process: contract::ProcessRef) -> Result<(), String> {
+ call(config, CANCEL, (process,), false).await
+}
+
+/// Open a module-owned port forward.
+pub async fn forward(
+ config: &Config,
+ request: contract::ForwardRequest,
+) -> Result<contract::ForwardInfo, String> {
+ call(config, FORWARD, (request,), false).await
+}
+
+/// Close a module-owned port forward.
+pub async fn close_forward(
+ config: &Config,
+ request: contract::CloseForwardRequest,
+) -> Result<(), String> {
+ call(config, CLOSE_FORWARD, (request,), false).await
+}
+
+/// Ask TinyBox for structural shell facts; this is not an authorization check.
+pub async fn analyze_shell(
+ config: &Config,
+ command: String,
+) -> Result<contract::ShellAnalysis, String> {
+ call(config, ANALYZE_SHELL, (command,), false).await
+}
+
+/// Ask TinyBox for generic command facts; the caller still decides policy.
+pub async fn analyze_command(
+ config: &Config,
+ command: String,
+) -> Result<contract::CommandAnalysis, String> {
+ call(config, ANALYZE_COMMAND, (command,), false).await
+}
+
+/// Open a bounded workspace file reader.
+pub async fn begin_file_read(
+ config: &Config,
+ request: contract::BeginFileReadRequest,
+) -> Result<contract::FileReadInfo, String> {
+ call(config, BEGIN_FILE_READ, (request,), false).await
+}
+
+/// Read one bounded range from an open file reader.
+pub async fn read_file_chunk(
+ config: &Config,
+ request: contract::ReadFileChunkRequest,
+) -> Result<contract::FileChunk, String> {
+ call(config, READ_FILE_CHUNK, (request,), false).await
+}
+
+/// Close a workspace file reader.
+pub async fn finish_file_read(
+ config: &Config,
+ request: contract::FinishFileReadRequest,
+) -> Result<(), String> {
+ call(config, FINISH_FILE_READ, (request,), false).await
+}
+
+/// Open an atomic staged workspace file writer.
+pub async fn begin_file_write(
+ config: &Config,
+ request: contract::BeginFileWriteRequest,
+) -> Result<contract::FileWriteInfo, String> {
+ call(config, BEGIN_FILE_WRITE, (request,), false).await
+}
+
+/// Write one bounded sequential chunk.
+pub async fn write_file_chunk(
+ config: &Config,
+ request: contract::WriteFileChunkRequest,
+) -> Result<contract::FileWriteProgress, String> {
+ call(config, WRITE_FILE_CHUNK, (request,), true).await
+}
+
+/// Atomically publish the staged workspace file.
+pub async fn finish_file_write(
+ config: &Config,
+ request: contract::FinishFileWriteRequest,
+) -> Result<contract::FileWriteProgress, String> {
+ call(config, FINISH_FILE_WRITE, (request,), false).await
+}
+
+/// Abort a staged workspace write without publishing it.
+pub async fn abort_file_write(
+ config: &Config,
+ request: contract::AbortFileWriteRequest,
+) -> Result<(), String> {
+ call(config, ABORT_FILE_WRITE, (request,), false).await
+}
+
+async fn call<Request, Reply>(
+ config: &Config,
+ member: &'static str,
+ request: Request,
+ confidential: bool,
+) -> Result<Reply, String>
+where
+ Request: Serialize + Send,
+ Reply: DeserializeOwned,
+{
+ call_with_client(&module_client(config), member, request, confidential).await
+}
+
+fn module_client(config: &Config) -> ModuleClient {
+ ModuleClient::new(config.clone()).with_timeout(MODULE_CALL_TIMEOUT)
+}
+
+fn message(error: ModuleCallError) -> String {
+ error.to_string()
+}
+
+async fn call_with_client<Request, Reply>(
+ client: &ModuleClient,
+ member: &'static str,
+ request: Request,
+ confidential: bool,
+) -> Result<Reply, String>
+where
+ Request: Serialize + Send,
+ Reply: DeserializeOwned,
+{
+ let capabilities: contract::ModuleCapabilities = client
+ .call(MODULE_ID, CAPABILITIES, ())
+ .await
+ .map_err(message)?;
+ require_compatible(capabilities.contract_version).map_err(message)?;
+ if confidential {
+ client
+ .call_confidential(MODULE_ID, member, request)
+ .await
+ .map_err(message)
+ } else {
+ client
+ .call(MODULE_ID, member, request)
+ .await
+ .map_err(message)
+ }
+}
diff --git a/crates/openhuman-core/src/modules/tinybox_tests.rs b/crates/openhuman-core/src/modules/tinybox_tests.rs
new file mode 100644
index 0000000000..ac5bec8f1e
--- /dev/null
+++ b/crates/openhuman-core/src/modules/tinybox_tests.rs
@@ -0,0 +1,225 @@
+//! MemoryBus tests for the TinyBox host adapter.
+
+use std::sync::{Arc, Mutex};
+
+use serde_json::{json, Value};
+use tinybus::broker::Broker;
+use tinybus::service::Interface;
+use tinybus::transport::memory::MemoryBus;
+use tinybus::{Connection, InterfaceName, MemberName, ObjectPath};
+
+use super::*;
+
+struct MockTinyBox {
+ calls: Arc<Mutex<Vec<(String, Value)>>>,
+}
+
+#[async_trait::async_trait]
+impl Interface for MockTinyBox {
+ fn name(&self) -> InterfaceName {
+ InterfaceName::new(contract::INTERFACE).expect("TinyBox interface")
+ }
+
+ fn members(&self) -> Vec<MemberName> {
+ contract::METHODS
+ .iter()
+ .map(|member| MemberName::new(*member).expect("TinyBox contract member"))
+ .collect()
+ }
+
+ async fn call(&self, member: &MemberName, args: Value) -> tinybus::Result<Value> {
+ self.calls
+ .lock()
+ .expect("call log lock")
+ .push((member.as_str().to_owned(), args));
+ match member.as_str() {
+ CAPABILITIES => serde_json::to_value(contract::ModuleCapabilities {
+ contract_version: contract::CONTRACT_VERSION,
+ create_backends: vec!["docker".to_owned()],
+ exec_backends: vec!["docker".to_owned()],
+ spawn_backends: vec!["docker".to_owned()],
+ })
+ .map_err(tinybus::Error::from),
+ ANALYZE_COMMAND => serde_json::to_value(contract::CommandAnalysis {
+ segments: Vec::new(),
+ hidden_execution: false,
+ redirection: false,
+ expansion: false,
+ tee: false,
+ background: false,
+ literal_words: vec!["printf".to_owned(), "hello".to_owned()],
+ })
+ .map_err(tinybus::Error::from),
+ EXEC => Err(tinybus::Error::MethodFailed {
+ name: "ai.tinyhumans.tinybox.Error.Backend".to_owned(),
+ message: "private argument /home/user/token leaked by provider".to_owned(),
+ }),
+ _ => serde_json::to_value(()).map_err(tinybus::Error::from),
+ }
+ }
+}
+
+async fn mock_client() -> (Connection, ModuleClient, Arc<Mutex<Vec<(String, Value)>>>) {
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+ let service = Connection::connect(bus.connect().await.expect("service transport"))
+ .await
+ .expect("service connection");
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ service
+ .serve_at(
+ ObjectPath::new(contract::OBJECT_PATH).expect("TinyBox path"),
+ MockTinyBox {
+ calls: Arc::clone(&calls),
+ },
+ )
+ .await
+ .expect("serve mock TinyBox");
+ service
+ .request_name(contract::INTERFACE)
+ .await
+ .expect("TinyBox bus name");
+ let client = Connection::connect(bus.connect().await.expect("client transport"))
+ .await
+ .expect("client connection");
+ let proxy = client
+ .proxy(
+ contract::INTERFACE,
+ contract::OBJECT_PATH,
+ contract::INTERFACE,
+ )
+ .expect("TinyBox proxy");
+ (service, ModuleClient::fixture(proxy), calls)
+}
+
+#[test]
+fn host_and_module_contract_versions_must_cover_the_full_host_surface() {
+ assert_eq!(require_compatible(contract::CONTRACT_VERSION), Ok(()));
+ assert_eq!(
+ require_compatible((1, contract::CONTRACT_VERSION.1 + 1)),
+ Ok(())
+ );
+ assert_eq!(
+ require_compatible((1, contract::CONTRACT_VERSION.1 - 1))
+ .expect_err("older member set is refused"),
+ ModuleCallError::IncompatibleContract
+ );
+ assert_eq!(
+ require_compatible((2, contract::CONTRACT_VERSION.1))
+ .expect_err("different major is refused"),
+ ModuleCallError::IncompatibleContract
+ );
+}
+
+#[tokio::test]
+async fn command_facts_use_contract_member_and_positional_arguments() {
+ let (_service, client, calls) = mock_client().await;
+ let command = "printf 'hello'".to_owned();
+ let facts: contract::CommandAnalysis =
+ call_with_client(&client, ANALYZE_COMMAND, (command.clone(),), false)
+ .await
+ .expect("typed command facts");
+
+ assert_eq!(facts.literal_words, ["printf", "hello"]);
+ assert_eq!(
+ calls.lock().expect("call log lock").as_slice(),
+ [
+ (CAPABILITIES.to_owned(), json!([])),
+ (ANALYZE_COMMAND.to_owned(), json!([command]))
+ ]
+ );
+}
+
+#[tokio::test]
+async fn provider_failure_does_not_echo_paths_or_request_values() {
+ let (_service, client, calls) = mock_client().await;
+ let secret_path = "/home/user/token";
+ let error = call_with_client::<_, contract::ExecOutput>(
+ &client,
+ EXEC,
+ (json!({"argv": ["cat", secret_path]}),),
+ false,
+ )
+ .await
+ .expect_err("provider refusal");
+
+ assert!(error.contains("MODULE_CALL_REPORTED"), "{error}");
+ assert!(!error.contains(secret_path));
+ let calls = calls.lock().expect("call log lock");
+ assert_eq!(calls.len(), 2);
+ assert_eq!(calls[1].0, EXEC);
+ assert!(calls[1].1.to_string().contains(secret_path));
+}
+
+#[tokio::test]
+async fn confidential_execution_refusal_is_not_retried_as_an_ordinary_call() {
+ let (_service, client, calls) = mock_client().await;
+ let error = call_with_client::<_, contract::ProcessRef>(
+ &client,
+ START_EXEC,
+ (json!({"process": "private"}),),
+ true,
+ )
+ .await
+ .expect_err("an unattested fixture cannot receive confidential execution");
+
+ assert!(error.contains("MODULE_CALL_REPORTED"), "{error}");
+ let calls = calls.lock().expect("call log lock");
+ assert_eq!(calls.len(), 1, "only the public capabilities probe ran");
+ assert_eq!(calls[0].0, CAPABILITIES);
+}
+
+#[tokio::test]
+#[ignore = "requires OPENHUMAN_BUNDLED_MODULES containing the pinned TinyBox release archive"]
+async fn pinned_loader_serves_the_published_tinybox_release() {
+ assert!(
+ std::env::var_os(crate::modules::ops::BUNDLED_MODULES_ENV).is_some(),
+ "set OPENHUMAN_BUNDLED_MODULES to the directory containing the pinned release archive"
+ );
+
+ let install = tempfile::tempdir().expect("temporary verified module cache");
+ let mut config = Config::default();
+ config.modules.allow_download = false;
+ config.modules.install_dir = Some(install.path().display().to_string());
+
+ let capabilities = super::capabilities(&config)
+ .await
+ .expect("the OpenHuman release registry and TinyBus loader admit v0.1.18");
+ assert_eq!(capabilities.contract_version, contract::CONTRACT_VERSION);
+ assert!(capabilities.create_backends.contains(&"docker".to_owned()));
+ assert!(capabilities.exec_backends.contains(&"docker".to_owned()));
+}
+
+#[test]
+fn every_host_operation_is_a_member_of_the_canonical_contract() {
+ let methods = [
+ DESCRIBE,
+ CREATE,
+ EXEC,
+ INSPECT,
+ CLOSE,
+ SPAWN,
+ IS_RUNNING,
+ CANCEL,
+ ANALYZE_SHELL,
+ RESERVE,
+ CAPABILITIES,
+ SHUTDOWN,
+ FORWARD,
+ CLOSE_FORWARD,
+ JAIL_STATUS,
+ ANALYZE_COMMAND,
+ BEGIN_FILE_READ,
+ READ_FILE_CHUNK,
+ FINISH_FILE_READ,
+ BEGIN_FILE_WRITE,
+ WRITE_FILE_CHUNK,
+ FINISH_FILE_WRITE,
+ ABORT_FILE_WRITE,
+ START_EXEC,
+ READ_OUTPUT,
+ RELEASE_OUTPUT,
+ START_JAILED_EXEC,
+ ];
+ assert_eq!(methods, contract::METHODS);
+}
diff --git a/crates/openhuman-embed/src/modules.rs b/crates/openhuman-embed/src/modules.rs
index 89443dcdea..b10a14a00b 100644
--- a/crates/openhuman-embed/src/modules.rs
+++ b/crates/openhuman-embed/src/modules.rs
@@ -13,9 +13,40 @@ pub mod browser {
pub use openhuman_core::modules::browser::MODULE_ID;
}
+/// TinyBox sandbox operations, with request types from its released bus contract.
+#[cfg(feature = "modules")]
+pub mod tinybox {
+ pub use openhuman_core::modules::tinybox::{
+ abort_file_write, analyze_command, analyze_shell, begin_file_read, begin_file_write,
+ cancel, capabilities, close, close_forward, create, describe, exec, finish_file_read,
+ finish_file_write, forward, inspect, is_running, jail_status, read_file_chunk, read_output,
+ release_output, reserve, shutdown, spawn, start_exec, start_jailed_exec, write_file_chunk,
+ MODULE_ID,
+ };
+}
+
/// Pre-core calls through the process-wide loader, with explicit runtime configuration.
pub use openhuman_core::modules::client::{ModuleCallError, ModuleClient};
#[cfg(all(test, not(feature = "modules"), not(feature = "default")))]
#[path = "modules_tests.rs"]
mod tests;
+
+/// The TinyBox sandbox module, available to hosts that compose sandbox and
+/// gateway operations before the core RPC server starts.
+#[cfg(feature = "modules")]
+pub mod tinybox {
+ /// The registry id used by the process module loader.
+ pub use openhuman_core::modules::tinybox::MODULE_ID;
+
+ /// TinyBox's versioned serialized bus contract.
+ pub use openhuman_core::modules::tinybox::contract;
+
+ pub use openhuman_core::modules::tinybox::{
+ abort_file_write, analyze_command, analyze_shell, begin_file_read, begin_file_write,
+ cancel, capabilities, close, close_forward, create, describe, exec, finish_file_read,
+ finish_file_write, forward, inspect, is_running, jail_status, read_file_chunk, read_output,
+ release_output, reserve, run_docker, shutdown, spawn, start_exec, start_jailed_exec,
+ write_file_chunk, MODULE_ID,
+ };
+}
diff --git a/vendor/tinybox b/vendor/tinybox
index b61c6bcebf..d493d1ccae 160000
--- a/vendor/tinybox
+++ b/vendor/tinybox
@@ -1 +1 @@
-Subproject commit b61c6bcebf3c0dbaf6ce3e36fae8131ebd6d78ae
+Subproject commit d493d1ccaef3cb2891ca387b30214b30b6f7df1e