Skip to content

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

feat(embed): own host hook subprocesses with stdin and awaited cleanup

Steven Enamakele2224a22a317
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index 1237479f56..01add1ddee 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -1,15 +1,10 @@
//! Encrypted-file keyring backend.
//!
-//! Stores all secrets in a single ChaCha20-Poly1305-encrypted file on disk,
-//! keyed by an app-scoped master key. The key is loaded once at core startup
-//! via [`init_master_key`] — from the environment when an operator supplies
-//! it ([`MASTER_KEY_ENV`] / [`MASTER_KEY_FILE_ENV`], for headless deployments
-//! with no OS keychain), otherwise from the OS keychain — and cached in a
-//! process-wide static. The backend itself never touches the OS keychain.
-//!
-//! This design reduces OS keychain access to exactly ONE call per process
-//! lifetime, avoiding the N-prompt problem where dev-signed macOS builds
-//! block on each individual keychain entry.
+//! Secrets share one ChaCha20-Poly1305 file and one app-scoped master key.
+//! [`init_master_key`] loads the key once from [`MASTER_KEY_ENV`] or
+//! [`MASTER_KEY_FILE_ENV`] for headless hosts, otherwise from the OS keychain.
+//! The cached key avoids repeated prompts in dev-signed macOS builds;
+//! this backend never reads the OS keychain itself.
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rs
index ed1ca3d503..8f2ab22bcd 100644
--- a/crates/openhuman-core/src/tools/timeout/mod.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod.rs
@@ -239,20 +239,42 @@ pub async fn output_or_kill(
/// caller cancels; a scoped [`ProcessCleanup`] can await that waiter.
pub async fn output_unbounded(
cmd: &mut tokio::process::Command,
+) -> std::io::Result<std::process::Output> {
+ output_with_input(cmd, None).await
+}
+
+/// Capture a command, optionally supplying stdin, in the current cleanup scope.
+pub async fn output_with_input(
+ cmd: &mut tokio::process::Command,
+ input: Option<Vec<u8>>,
) -> std::io::Result<std::process::Output> {
use std::process::Stdio;
- cmd.stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true);
+ cmd.stdin(if input.is_some() {
+ Stdio::piped()
+ } else {
+ Stdio::null()
+ })
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
CommandEnvironment::apply(cmd);
own_process_group(cmd.as_std_mut());
- let child = cmd.spawn()?;
+ let mut child = cmd.spawn()?;
+ let stdin = child.stdin.take();
let reaped = process_cleanup::Reaped::register();
let (cancel, cancellation) = tokio::sync::watch::channel(false);
let waiter = tokio::spawn(async move {
let _reaped = reaped;
- collect_command_output(child, cancellation).await
+ let write_input = async move {
+ if let (Some(mut stdin), Some(input)) = (stdin, input) {
+ use tokio::io::AsyncWriteExt;
+ // An early child exit closes stdin. Its exit status/output is
+ // authoritative; a broken pipe must not hide it.
+ let _ = stdin.write_all(&input).await;
+ }
+ };
+ let (_, output) = tokio::join!(write_input, collect_command_output(child, cancellation));
+ output
});
let _cancel_on_drop = CancelOnDrop(cancel);
waiter.await.map_err(std::io::Error::other)?
diff --git a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
index 471f484def..566a60e340 100644
--- a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
+++ b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
@@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex};
use tokio::sync::watch;
tokio::task_local! {
- static ACTIVE: ProcessCleanup;
+ static ACTIVE: Vec<ProcessCleanup>;
}
/// Command waiters belonging to one turn. Clone before scoping the turn;
@@ -25,7 +25,9 @@ impl ProcessCleanup {
/// Run a future with command waiters registered to this turn.
pub async fn scope<T>(&self, future: impl Future<Output = T>) -> T {
- ACTIVE.scope(self.clone(), future).await
+ let mut scopes = ACTIVE.try_with(Clone::clone).unwrap_or_default();
+ scopes.push(self.clone());
+ ACTIVE.scope(scopes, future).await
}
/// Wait for every registered command to exit and its output pipes to close.
@@ -48,12 +50,14 @@ pub(super) struct Reaped(watch::Sender<bool>);
impl Reaped {
pub(super) fn register() -> Self {
let (done, waiter) = watch::channel(false);
- let _ = ACTIVE.try_with(|cleanup| {
- cleanup
- .0
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .push(waiter);
+ let _ = ACTIVE.try_with(|scopes| {
+ for cleanup in scopes {
+ cleanup
+ .0
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .push(waiter.clone());
+ }
});
Self(done)
}
diff --git a/crates/openhuman-embed/src/process.rs b/crates/openhuman-embed/src/process.rs
index 25a04c054e..02819ca1ba 100644
--- a/crates/openhuman-embed/src/process.rs
+++ b/crates/openhuman-embed/src/process.rs
@@ -102,3 +102,24 @@ pub fn init_master_key() -> anyhow::Result<()> {
#[cfg(test)]
#[path = "process_tests.rs"]
mod tests;
+
+/// Run a host command with stdin and a deadline, owning its process group.
+/// Normal completion, timeout, and cancellation all reap the command. When
+/// called inside a cancellable turn, its cleanup is also tracked by that turn.
+/// Explicit command environment settings are preserved over `Turn::tool_env`.
+pub async fn command_output(
+ command: &mut tokio::process::Command,
+ input: Vec<u8>,
+ deadline: std::time::Duration,
+) -> std::io::Result<std::process::Output> {
+ let cleanup = openhuman_core::tools::timeout::ProcessCleanup::default();
+ let result = cleanup
+ .scope(tokio::time::timeout(
+ deadline,
+ openhuman_core::tools::timeout::output_with_input(command, Some(input)),
+ ))
+ .await;
+ cleanup.wait().await;
+ result
+ .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "host command timed out"))?
+}
diff --git a/crates/openhuman-embed/tests/process_cancellation.rs b/crates/openhuman-embed/tests/process_cancellation.rs
index 1670bb9ec4..ebbb932d16 100644
--- a/crates/openhuman-embed/tests/process_cancellation.rs
+++ b/crates/openhuman-embed/tests/process_cancellation.rs
@@ -185,3 +185,34 @@ async fn cancellable_turns_route_interpreters_away_from_unacknowledged_pools() {
.await;
assert!(openhuman_core::runtime::pool::node::enabled(&config));
}
+
+#[tokio::test]
+async fn host_commands_receive_stdin_and_timeout_after_reaping() {
+ let mut cmd = tokio::process::Command::new("/bin/sh");
+ cmd.args(["-c", "cat; printf stderr >&2"]);
+ let output = openhuman_embed::process::command_output(
+ &mut cmd,
+ b"payload".to_vec(),
+ Duration::from_secs(2),
+ )
+ .await
+ .unwrap();
+ assert_eq!(output.stdout, b"payload");
+ assert_eq!(output.stderr, b"stderr");
+ let scratch = tempfile::tempdir().unwrap();
+ let pidfile = scratch.path().join("host.pid");
+ let mut cmd = tokio::process::Command::new("/bin/sh");
+ cmd.args(["-c", &format!("echo $$ > {}; sleep 30", pidfile.display())]);
+ let outer = ProcessCleanup::default();
+ let result = outer
+ .scope(openhuman_embed::process::command_output(
+ &mut cmd,
+ Vec::new(),
+ Duration::from_millis(100),
+ ))
+ .await;
+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);
+ outer.wait().await;
+ let pid = std::fs::read_to_string(pidfile).unwrap();
+ assert!(!std::path::Path::new(&format!("/proc/{}", pid.trim())).exists());
+}