Skip to content

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

Merge upstream/main into tinybox-followup

Steven Enamakel8561ec04b5da
diff --cc crates/openhuman-core/src/hooks/shell.rs
index cc8bf7390f,0000000000..60c84d63ef
mode 100644,000000..100644
--- a/crates/openhuman-core/src/hooks/shell.rs
+++ b/crates/openhuman-core/src/hooks/shell.rs
@@@ -1,119 -1,0 +1,119 @@@
+//! The shell that runs `command` hooks, as selected by TinyBox.
+//!
+//! The hook engine (`tinyagents_runtime::command_hooks`) spawns the hook process
+//! itself and asks its host for a synchronous `fn(&str) -> Command`. The host
+//! does not choose the shell: it asks TinyBox's `SelectShell` once, at the async
+//! boundary where hooks are (re)loaded, and the factory only fills the hook's
+//! command into that selection. A selection that never resolved yields a command
+//! that fails to spawn, so a hook never silently runs under a different shell.
+
+use std::sync::{OnceLock, RwLock};
+
+use tinybox_bus::ShellInvocation;
+
+/// Stands in for the hook command while asking the module for a selection. It is
+/// substituted back in verbatim wherever the module embedded it.
+const PLACEHOLDER: &str = "__OPENHUMAN_HOOK_COMMAND__";
+
+/// A program that does not exist, so an unresolved selection fails the spawn.
+const UNAVAILABLE: &str = "openhuman-hook-shell-unavailable";
+
+fn slot() -> &'static RwLock<Option<ShellInvocation>> {
+ static SLOT: OnceLock<RwLock<Option<ShellInvocation>>> = OnceLock::new();
+ SLOT.get_or_init(|| RwLock::new(None))
+}
+
+/// Ask TinyBox which shell it selects and remember it for [`command`].
+///
+/// A failure is logged and leaves any earlier selection in place.
+pub(super) async fn resolve() {
+ #[cfg(feature = "modules")]
+ {
+ let config = match crate::config::ops::load_config_with_timeout().await {
+ Ok(config) => config,
+ Err(error) => {
+ log::warn!("[hooks] cannot read config to select the hook shell: {error}");
+ return;
+ }
+ };
+ let request = tinybox_bus::SelectShellRequest {
+ command: PLACEHOLDER.to_owned(),
+ preserve_pipeline_status: false,
+ runtime_path: None,
+ python_utf8: false,
+ };
+ match crate::modules::tinybox::select_shell(&config, request).await {
+ Ok(selection) if embeds_placeholder_once(&selection) => install(selection),
+ Ok(_) => log::warn!("[hooks] TinyBox shell selection did not embed the hook command"),
+ Err(error) => log::warn!("[hooks] TinyBox shell selection failed: {error}"),
+ }
+ }
+ #[cfg(not(feature = "modules"))]
+ log::warn!("[hooks] built without `modules`; hook commands cannot select a shell");
+}
+
+fn install(selection: ShellInvocation) {
+ log::debug!(
+ "[hooks] hook shell selected flavor={:?} program_set={}",
+ selection.flavor,
+ !selection.program.is_empty()
+ );
+ *slot()
+ .write()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(selection);
+}
+
+fn embeds_placeholder_once(selection: &ShellInvocation) -> bool {
+ let count = selection
+ .arguments
+ .iter()
+ .map(String::as_str)
+ .chain(selection.raw_arguments.as_deref())
+ .map(|text| text.matches(PLACEHOLDER).count())
+ .sum::<usize>();
+ count == 1
+}
+
+/// Build the process for one hook `command` from the remembered selection.
+pub(super) fn command(command: &str) -> tokio::process::Command {
+ let selection = slot()
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ let process = match selection {
+ Some(selection) => from_selection(&selection, command),
+ None => {
+ log::warn!("[hooks] no TinyBox shell selection; the hook command will not start");
+ std::process::Command::new(UNAVAILABLE)
+ }
+ };
+ let mut process = tokio::process::Command::from(process);
+ // A hook leads its own process group and dies with the handle that owns it,
+ // so a deadline cannot leave its pipeline running.
+ process.kill_on_drop(true);
- crate::tools::timeout::own_process_group(process.as_std_mut());
++ tinytools_std::timeout::own_process_group(process.as_std_mut());
+ process
+}
+
+fn from_selection(selection: &ShellInvocation, command: &str) -> std::process::Command {
+ let mut process = std::process::Command::new(&selection.program);
+ process.args(
+ selection
+ .arguments
+ .iter()
+ .map(|argument| argument.replace(PLACEHOLDER, command)),
+ );
+ for name in &selection.remove_environment {
+ process.env_remove(name);
+ }
+ #[cfg(windows)]
+ if let Some(raw) = &selection.raw_arguments {
+ use std::os::windows::process::CommandExt;
+ process.raw_arg(raw.replace(PLACEHOLDER, command));
+ }
+ process
+}
+
+#[cfg(test)]
+#[path = "shell_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
index c5c9775654,0000000000..37d2706925
mode 100644,000000..100644
--- a/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
+++ b/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
@@@ -1,78 -1,0 +1,78 @@@
+//! Test-only stand-in for the module's native shell: unit tests do not load a
+//! native TinyBox artifact, so unjailed runs execute here. The module's own
+//! behaviour (shell selection, environment, scratch) is covered by its crate and
+//! by the released-artifact test; this fixture only has to run a command.
+
+use std::process::Stdio;
+
+use super::{NativeShellRun, SandboxExecResult};
+
+/// Variables the module's safe environment snapshot carries.
+const SNAPSHOT: &[&str] = &[
+ "PATH", "HOME", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "USER", "SHELL", "TMPDIR",
+];
+
+pub(crate) async fn run(run: NativeShellRun) -> anyhow::Result<SandboxExecResult> {
+ let bash = ["/usr/bin/bash", "/bin/bash"]
+ .into_iter()
+ .find(|path| std::path::Path::new(path).exists());
+ let mut command = tokio::process::Command::new(if cfg!(windows) {
+ "cmd"
+ } else {
+ bash.unwrap_or("sh")
+ });
+ if cfg!(windows) {
+ command.arg("/C").arg(&run.command);
+ } else if bash.is_some() && !run.preserve_pipeline_status {
+ command
+ .arg("-c")
+ .arg(format!("set -o pipefail\n{}", run.command));
+ } else {
+ command.arg("-c").arg(&run.command);
+ }
+ command.env_clear();
+ for name in SNAPSHOT {
+ if let Some(value) = std::env::var_os(name) {
+ command.env(name, value);
+ }
+ }
+ if cfg!(windows) {
+ for name in ["SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "TEMP", "TMP"] {
+ if let Some(value) = std::env::var_os(name) {
+ command.env(name, value);
+ }
+ }
+ }
+ if run.python_utf8 {
+ // The module defaults these unless the parent environment sets them.
+ for (name, default) in [("PYTHONUTF8", "1"), ("PYTHONIOENCODING", "utf-8")] {
+ command.env(
+ name,
+ std::env::var_os(name).unwrap_or_else(|| default.into()),
+ );
+ }
+ }
+ command.envs(&run.env);
+ command
+ .current_dir(&run.cwd)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
- crate::tools::timeout::own_process_group(command.as_std_mut());
- match crate::tools::timeout::output_or_kill(&mut command, run.timeout).await {
++ tinytools_std::timeout::own_process_group(command.as_std_mut());
++ match tinytools_std::timeout::output_or_kill(&mut command, run.timeout).await {
+ Ok(Ok(output)) => Ok(SandboxExecResult {
+ exit_code: output.status.code().unwrap_or(-1),
+ stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
+ stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
+ timed_out: false,
+ }),
+ Ok(Err(error)) => anyhow::bail!("Failed to execute command: {error}"),
+ Err(_) => Ok(SandboxExecResult {
+ exit_code: -1,
+ stdout: String::new(),
+ stderr: format!("Command timed out after {}s", run.timeout.as_secs()),
+ timed_out: true,
+ }),
+ }
+}
diff --cc crates/openhuman-core/src/tools/impl/system/shell.rs
index b833c8d77b,2ffb3f9a45..5897f0765a
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@@ -517,32 -544,19 +517,32 @@@ impl ShellTool
return (true, result);
}
- let mut cmd = match self.runtime.build_shell_command(command, &action_dir) {
- Ok(cmd) => cmd,
- Err(e) => {
- return (
- true,
- ToolResult::error(format!("Failed to build shell command: {e}")),
- );
+ // The module spawns the shell: it selects cmd or bash, starts from its
+ // own safe environment (no API keys or other secrets, CWE-200) and owns
+ // the per-call scratch directory. The host adds only what it approves.
+ if let Err(e) = crate::config::ensure_usable_cwd(&action_dir) {
+ return (
+ true,
+ ToolResult::error(format!("Failed to build shell command: {e}")),
+ );
+ }
+ let mut env = std::collections::BTreeMap::new();
+
+ // A turn that owns its child environment (library agents) keeps it: the
+ // module starts from the process snapshot, so the turn's own values for
+ // the functional variables are passed as approved overrides.
- if crate::tools::timeout::CommandEnvironment::is_active() {
++ if tinytools_std::timeout::CommandEnvironment::is_active() {
+ for name in crate::sandbox::ops::SANDBOX_ENV_PASSTHROUGH {
- if let Some(value) = crate::tools::timeout::CommandEnvironment::var_os(name) {
++ if let Some(value) = tinytools_std::timeout::CommandEnvironment::var_os(name) {
+ let Ok(value) = value.into_string() else {
+ return (
+ false,
+ ToolResult::error("Shell environment contains a non-UTF-8 value."),
+ );
+ };
+ env.insert((*name).to_owned(), value);
+ }
}
- };
- cmd.env_clear();
-
- for (var, val) in shell_child_env(tinytools_std::timeout::CommandEnvironment::var_os) {
- cmd.env(var, val);
}
// Keep command-valued repository Git settings from executing host
@@@ -578,41 -586,56 +578,41 @@@
}
// No default deadline — only a caller-supplied `timeout_secs` bounds the
- // run. `None` ⇒ run to completion (issue #4023).
+ // run (issue #4023). TinyBox needs a finite budget, so an unbounded call
+ // gets the module's ceiling.
let explicit_timeout = self.explicit_timeout(requested_timeout);
+ let effective = explicit_timeout.unwrap_or_else(|| {
- Duration::from_secs(crate::tools::timeout::SANDBOX_UNBOUNDED_CAP_SECS)
++ Duration::from_secs(tinytools_std::timeout::SANDBOX_UNBOUNDED_CAP_SECS)
+ });
tracing::debug!(
- timeout_secs = ?explicit_timeout.map(|d| d.as_secs()),
+ timeout_secs = effective.as_secs(),
requested_timeout_secs = ?requested_timeout,
- "[shell] starting command ({} timeout)",
- if explicit_timeout.is_some() { "explicit" } else { "no" }
+ unbounded = explicit_timeout.is_none(),
+ "[shell] starting command through TinyBox"
);
- let result = match explicit_timeout {
- Some(timeout) => tinytools_std::timeout::output_or_kill(&mut cmd, timeout).await,
- None => Ok(tinytools_std::timeout::output_unbounded(&mut cmd).await),
- };
-
- let tool_result = match result {
- Ok(Ok(output)) => {
- let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
- let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();
-
- // Truncate output to prevent OOM
- if stdout.len() > MAX_OUTPUT_BYTES {
- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));
- stdout.push_str("\n... [output truncated at 1MB]");
- }
- if stderr.len() > MAX_OUTPUT_BYTES {
- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));
- stderr.push_str("\n... [stderr truncated at 1MB]");
- }
-
- if output.status.success() {
- if stderr.is_empty() {
- ToolResult::success(stdout)
- } else {
- // Successful exit but stderr present — attach stderr as output suffix
- ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}"))
- }
- } else {
- // Surface the exit code AND both streams so the agent can
- // diagnose the failure (e.g. 127 missing dependency, 126
- // sandbox/permission wall) instead of looping on it (#4095).
- command_failure(output.status.code(), &stdout, &stderr)
+ let config = match self.analysis_config.as_deref() {
+ Some(config) => config.clone(),
+ None => match crate::config::ops::load_config_with_timeout().await {
+ Ok(config) => config,
+ Err(e) => {
+ return (
+ true,
+ ToolResult::error(format!("Cannot read module configuration: {e}")),
+ )
}
- }
- Ok(Err(e)) => ToolResult::error(format!("Failed to execute command: {e}")),
- Err(_) => {
- let secs = explicit_timeout.map(|d| d.as_secs()).unwrap_or(0);
- tracing::debug!(timeout_secs = secs, "[shell] tool timeout_secs fired");
- ToolResult::error(tool_timeout_message(secs))
- }
+ },
};
- (true, tool_result)
+ let mut run = crate::sandbox::shell_exec::NativeShellRun::new(
+ command,
+ &action_dir,
+ &self.security.workspace_dir,
+ effective,
+ );
+ run.env = env;
+ run.python_utf8 = true;
+ run.hide_window = self.runtime.hide_window();
+ let result = crate::sandbox::shell_exec::run(&config, run).await;
+ (true, exec_result(result, effective))
}
/// Execute a command through the sandbox backend. Called when the
diff --cc crates/openhuman-core/src/tools/impl/system/shell_support.rs
index cbc134026a,0000000000..83514e73ff
mode 100644,000000..100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_support.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_support.rs
@@@ -1,95 -1,0 +1,95 @@@
+//! Result mapping and child-environment helpers for the `shell` tool.
+
+use std::time::Duration;
+use tinytools::ToolResult;
+
+/// Exit status coreutils `timeout` returns when its own limit expires.
+pub(super) const COMMAND_TIMEOUT_EXIT_CODE: i32 = 124;
+/// Appended to an exit-124 failure: the command's own `timeout` fired, not the
+/// tool's (#6953). Without it, `exit code 124 [stdout] ok` reads like a bug.
+pub(super) const COMMAND_TIMEOUT_NOTE: &str = "[exit 124: the command's own `timeout` limit expired; the shell tool's timeout_secs did not fire]";
+
+/// The result when the tool's own `timeout_secs` deadline killed the command.
+pub(super) fn tool_timeout_message(secs: u64) -> String {
+ format!("Command timed out after {secs}s and was killed: the shell tool's timeout_secs limit fired.")
+}
+
+/// [`tinytools::command_failure`], plus [`COMMAND_TIMEOUT_NOTE`] on exit 124.
+pub(super) fn command_failure(code: Option<i32>, stdout: &str, stderr: &str) -> ToolResult {
+ let mut failure = tinytools::command_failure(code, stdout, stderr);
+ if code == Some(COMMAND_TIMEOUT_EXIT_CODE) {
+ tracing::debug!("[shell] exit 124: attributing it to the command's own timeout");
+ failure.content.push(tinytools::ToolContent::Text {
+ text: COMMAND_TIMEOUT_NOTE.to_string(),
+ });
+ }
+ failure
+}
+
+/// Map a finished sandbox or module execution to the tool result.
+///
+/// The same exit-code and both-streams surfacing everywhere (#4095); the `-1`
+/// sentinel renders as a signal.
+pub(super) fn exec_result(
+ result: anyhow::Result<crate::sandbox::SandboxExecResult>,
+ effective: Duration,
+) -> ToolResult {
+ match result {
+ Ok(result) if result.timed_out => {
+ ToolResult::error(tool_timeout_message(effective.as_secs()))
+ }
+ Ok(result) if result.success() => {
+ if result.stderr.is_empty() {
+ ToolResult::success(result.stdout)
+ } else {
+ ToolResult::success(format!("{}\n[stderr]\n{}", result.stdout, result.stderr))
+ }
+ }
+ Ok(result) => command_failure(
+ tinytools::sandbox_exit_code(result.exit_code),
+ &result.stdout,
+ &result.stderr,
+ ),
+ Err(e) => ToolResult::error(format!("Sandbox execution failed: {e}")),
+ }
+}
+
+/// Python's text-encoding defaults for a child, unless the parent sets its own.
+/// Under `cmd.exe` the console code page is a legacy one (cp1252, cp437), so a
+/// script printing anything outside it dies with `UnicodeEncodeError`. Both are
+/// no-ops for a non-Python command. Native runs get the same from TinyBox's
+/// `python_utf8` request flag; this serves the Docker and sandbox-policy paths,
+/// which forward their environment as plain variables.
+pub(super) const PYTHON_UTF8_DEFAULTS: &[(&str, &str)] =
+ &[("PYTHONUTF8", "1"), ("PYTHONIOENCODING", "utf-8")];
+
+pub(super) fn python_utf8_env(
+ lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
+) -> Vec<(&'static str, std::ffi::OsString)> {
+ PYTHON_UTF8_DEFAULTS
+ .iter()
+ .map(|(name, default)| {
+ let value = lookup(name).unwrap_or_else(|| (*default).into());
+ (*name, value)
+ })
+ .collect()
+}
+
+/// The host environment a Docker container receives: the sandbox allowlist from
+/// the parent plus the Python encoding defaults. `None` when a value is not UTF-8.
+#[cfg(feature = "modules")]
+pub(super) fn container_environment() -> Option<std::collections::BTreeMap<String, String>> {
+ let mut env = std::collections::BTreeMap::new();
+ let inherited = crate::sandbox::ops::SANDBOX_ENV_PASSTHROUGH
+ .iter()
+ .filter_map(|name| {
- crate::tools::timeout::CommandEnvironment::var_os(name).map(|value| (*name, value))
++ tinytools_std::timeout::CommandEnvironment::var_os(name).map(|value| (*name, value))
+ })
+ .chain(python_utf8_env(
- crate::tools::timeout::CommandEnvironment::var_os,
++ tinytools_std::timeout::CommandEnvironment::var_os,
+ ));
+ for (name, value) in inherited {
+ env.insert(name.to_owned(), value.into_string().ok()?);
+ }
+ Some(env)
+}
diff --cc crates/openhuman-core/src/tools/impl/system/shell_tests_platform_tests.rs
index 918e5e4396,a5a55e7d58..503a4a6a14
--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_platform_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_platform_tests.rs
@@@ -89,22 -106,18 +89,22 @@@ fn a_users_own_python_encoding_settings
);
}
-#[test]
-fn the_child_env_forwards_only_the_allow_list_plus_python_defaults() {
- let env = as_map(shell_child_env(parent(&[
- ("PATH", "/bin"),
- ("USERPROFILE", "C:\\Users\\me"),
- ("OPENAI_API_KEY", "sk-secret"),
- ("AWS_SECRET_ACCESS_KEY", "secret"),
- ])));
- assert_eq!(
- env.get("USERPROFILE").map(String::as_str),
- Some("C:\\Users\\me")
- );
+/// A Docker container gets the sandbox allowlist from the turn's environment
+/// plus the Python defaults, and never the rest of it.
+#[cfg(feature = "modules")]
+#[tokio::test]
+async fn the_container_environment_forwards_only_the_allowlist_plus_python_defaults() {
- let scoped = crate::tools::timeout::CommandEnvironment::new([
++ let scoped = tinytools_std::timeout::CommandEnvironment::new([
+ ("PATH".to_owned(), "/bin".to_owned()),
+ ("OPENAI_API_KEY".to_owned(), "sk-secret".to_owned()),
+ ("AWS_SECRET_ACCESS_KEY".to_owned(), "secret".to_owned()),
+ ]);
+ let env = scoped
+ .scope(async { container_environment() })
+ .await
+ .unwrap();
+ assert_eq!(env.get("PATH").map(String::as_str), Some("/bin"));
+ assert_eq!(env.get("PYTHONUTF8").map(String::as_str), Some("1"));
assert!(!env.contains_key("OPENAI_API_KEY"));
assert!(!env.contains_key("AWS_SECRET_ACCESS_KEY"));
for key in env.keys() {
diff --cc crates/openhuman-embed/tests/process_cancellation.rs
index e0590b6558,8146fd150f..da6a3884d7
--- a/crates/openhuman-embed/tests/process_cancellation.rs
+++ b/crates/openhuman-embed/tests/process_cancellation.rs
@@@ -2,18 -2,9 +2,18 @@@
#![cfg(target_os = "linux")]
- use openhuman_core::tools::timeout::{output_or_kill, output_unbounded, ProcessCleanup};
use std::time::Duration;
+ use tinytools_std::timeout::{output_or_kill, output_unbounded, ProcessCleanup};
+/// A shell child that leads its own process group and dies with its handle, as
+/// the module-owned shell children do.
+fn shell_child(command: &str) -> tokio::process::Command {
+ let mut cmd = tokio::process::Command::new("sh");
+ cmd.arg("-c").arg(command).kill_on_drop(true);
+ openhuman_core::tools::timeout::own_process_group(cmd.as_std_mut());
+ cmd
+}
+
/// Cancelling a tool must also stop descendants of its shell.
#[cfg(target_os = "linux")]
#[tokio::test]