The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(hooks): add shell command hook support
Steven Enamakelabb55f2a430e
diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rsindex 8aad17f48f..1a052b420d 100644--- a/crates/openhuman-core/src/hooks/host.rs+++ b/crates/openhuman-core/src/hooks/host.rs@@ -29,7 +29,7 @@ impl PromptEvaluator for HostPromptEvaluator {fn environment() -> HookEnvironment {HookEnvironment::new(PRODUCT_NAME, dirs::home_dir())- .with_shell(crate::agent::platform_shell::build_tokio_command)+ .with_shell(super::shell::command).with_prompt_evaluator(Arc::new(HostPromptEvaluator))}@@ -50,6 +50,9 @@ pub async fn reload(project_dir: Option<std::path::PathBuf>,workspace_dir: Option<std::path::PathBuf>,) -> Arc<HookConfig> {+ // Hook commands run under the shell TinyBox selects; ask it here, where the+ // caller is async, so the engine's synchronous shell factory can use it.+ super::shell::resolve().await;let current = environment();let loaded = tokio::task::spawn_blocking(move || {config::load(¤t, project_dir.as_deref(), workspace_dir.as_deref())diff --git a/crates/openhuman-core/src/hooks/mod.rs b/crates/openhuman-core/src/hooks/mod.rsindex 0cfbc8d6f4..a4195c6cec 100644--- a/crates/openhuman-core/src/hooks/mod.rs+++ b/crates/openhuman-core/src/hooks/mod.rs@@ -28,6 +28,7 @@pub mod bridge;pub mod host;pub mod ops;+mod shell;pub mod prompt_eval;pub mod schemas;diff --git a/crates/openhuman-core/src/hooks/shell.rs b/crates/openhuman-core/src/hooks/shell.rsnew file mode 100644index 0000000000..e13f091a85--- /dev/null+++ b/crates/openhuman-core/src/hooks/shell.rs@@ -0,0 +1,120 @@+//! 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}"),+ }+ }+}++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 mut 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(std::mem::replace(+ &mut process,+ std::process::Command::new(UNAVAILABLE),+ ));+ // 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());+ 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 --git a/crates/openhuman-core/src/hooks/shell_tests.rs b/crates/openhuman-core/src/hooks/shell_tests.rsnew file mode 100644index 0000000000..6ec9debe20--- /dev/null+++ b/crates/openhuman-core/src/hooks/shell_tests.rs@@ -0,0 +1,72 @@+//! The hook shell is TinyBox's selection with the hook command filled in.++use super::*;+use tinybox_bus::ShellFlavor;++fn posix() -> ShellInvocation {+ ShellInvocation {+ flavor: ShellFlavor::Posix,+ program: "/bin/bash".into(),+ arguments: vec![+ "-p".into(),+ "-c".into(),+ format!("set -o pipefail\n{PLACEHOLDER}"),+ ],+ raw_arguments: None,+ bootstrap_environment: Vec::new(),+ remove_environment: vec!["BASH_ENV".into()],+ }+}++fn cmd() -> ShellInvocation {+ ShellInvocation {+ flavor: ShellFlavor::Cmd,+ program: r"C:\Windows\System32\cmd.exe".into(),+ arguments: vec!["/D".into(), "/S".into(), "/C".into()],+ raw_arguments: Some(format!("\"{PLACEHOLDER}\"")),+ bootstrap_environment: Vec::new(),+ remove_environment: Vec::new(),+ }+}++#[test]+fn the_hook_command_replaces_the_placeholder_in_the_selected_arguments() {+ let process = from_selection(&posix(), "echo 'a b' | cat");+ assert_eq!(process.get_program(), "/bin/bash");+ let args: Vec<_> = process+ .get_args()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect();+ assert_eq!(args, ["-p", "-c", "set -o pipefail\necho 'a b' | cat"]);+ assert!(process+ .get_envs()+ .any(|(name, value)| name == "BASH_ENV" && value.is_none()));+}++#[test]+fn a_command_that_contains_the_placeholder_text_is_not_rewritten_twice() {+ let process = from_selection(&posix(), PLACEHOLDER);+ let last = process.get_args().last().unwrap().to_string_lossy().into_owned();+ assert_eq!(last, format!("set -o pipefail\n{PLACEHOLDER}"));+}++#[test]+fn a_selection_must_embed_the_command_exactly_once() {+ assert!(embeds_placeholder_once(&posix()));+ assert!(embeds_placeholder_once(&cmd()));+ let mut none = posix();+ none.arguments = vec!["-c".into(), "true".into()];+ assert!(!embeds_placeholder_once(&none));+ let mut twice = posix();+ twice.arguments.push(PLACEHOLDER.into());+ assert!(!embeds_placeholder_once(&twice));+}++#[test]+fn an_unresolved_selection_fails_the_spawn_instead_of_picking_a_shell() {+ // A fresh slot is process-global state; this test only reads the factory's+ // behavior when nothing was installed or after clearing it.+ *slot().write().unwrap() = None;+ let process = command("echo hi");+ assert_eq!(process.as_std().get_program(), UNAVAILABLE);+}diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex 09ada5ffc9..46f610763d 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -548,6 +548,23 @@ impl ShellTool {}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() {+ for name in crate::sandbox::ops::SANDBOX_ENV_PASSTHROUGH {+ if let Some(value) = crate::tools::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);+ }+ }+ }+// Keep command-valued repository Git settings from executing host// programs when a shell command happens to invoke git.for (key, value) in tinytools_std::filesystem::shell_git_env() {