Skip to content

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

refactor(timeout): delegate timeout handling to tinytools_std

Steven Enamakel41bec5cece56
diff --git a/crates/openhuman-core/src/tools/timeout/command_environment.rs b/crates/openhuman-core/src/tools/timeout/command_environment.rs
deleted file mode 100644
index c787db920c..0000000000
--- a/crates/openhuman-core/src/tools/timeout/command_environment.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-//! Child-process environment carried by one dispatch task.
-
-use std::{collections::BTreeMap, future::Future, sync::Arc};
-
-tokio::task_local! { static ACTIVE: CommandEnvironment; }
-
-/// A complete, turn-owned environment for builtin tool subprocesses.
-/// This never mutates the host process environment. Host-spawned tasks must
-/// explicitly inherit its scope. Interpreter pools cannot accept scoped work.
-#[derive(Clone)]
-pub struct CommandEnvironment(Arc<BTreeMap<String, String>>);
-
-impl CommandEnvironment {
- /// Own the exact variables permitted in child processes.
- pub fn new(env: impl IntoIterator<Item = (String, String)>) -> Self {
- Self(Arc::new(env.into_iter().collect()))
- }
- /// Whether this task requires its own child environment.
- pub fn is_active() -> bool {
- ACTIVE.try_with(|_| ()).is_ok()
- }
- /// Run a future using this environment for builtin subprocesses.
- pub async fn scope<F: Future>(&self, future: F) -> F::Output {
- ACTIVE.scope(self.clone(), future).await
- }
- /// Read a functional child variable from the scoped map, falling back to
- /// the process only when no map was supplied.
- pub fn var_os(name: &str) -> Option<std::ffi::OsString> {
- ACTIVE
- .try_with(|environment| environment.0.get(name).map(Into::into))
- .unwrap_or_else(|_| std::env::var_os(name))
- }
- /// UTF-8 counterpart used by managed interpreter command builders.
- pub fn var(name: &str) -> Result<String, std::env::VarError> {
- ACTIVE
- .try_with(|environment| {
- environment
- .0
- .get(name)
- .cloned()
- .ok_or(std::env::VarError::NotPresent)
- })
- .unwrap_or_else(|_| std::env::var(name))
- }
- pub(super) fn apply(command: &mut tokio::process::Command) {
- let _ = ACTIVE.try_with(|environment| {
- // Explicit runtime/security additions (managed PATH, scratch TMP,
- // Git policy) remain authoritative over the base environment.
- let explicit: Vec<_> = command
- .as_std()
- .get_envs()
- .map(|(key, value)| (key.to_owned(), value.map(ToOwned::to_owned)))
- .collect();
- command.env_clear().envs(environment.0.iter());
- for (key, value) in explicit {
- match value {
- Some(value) => {
- command.env(key, value);
- }
- None => {
- command.env_remove(key);
- }
- }
- }
- });
- }
-}
diff --git a/crates/openhuman-core/src/tools/timeout/group_exit.rs b/crates/openhuman-core/src/tools/timeout/group_exit.rs
deleted file mode 100644
index 665f4f3a4c..0000000000
--- a/crates/openhuman-core/src/tools/timeout/group_exit.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-//! Wait for signalled Linux process-group members to stop executing.
-//!
-//! The caller keeps the group leader unreaped during this check, reserving
-//! its PID and preventing a new process group from reusing the identifier.
-
-/// Wait until the reserved group contains no executing Linux processes.
-#[cfg(target_os = "linux")]
-pub(super) async fn wait(pid: u32) -> std::io::Result<()> {
- loop {
- let active = crate::core::runtime::spawn_blocking_scoped(move || active_members(pid))
- .await
- .map_err(std::io::Error::other)??;
- if !active {
- return Ok(());
- }
- tokio::time::sleep(std::time::Duration::from_millis(1)).await;
- }
-}
-
-/// Other platforms retain their existing direct-child acknowledgement.
-#[cfg(not(target_os = "linux"))]
-pub(super) async fn wait(_: u32) -> std::io::Result<()> {
- Ok(())
-}
-
-/// Inspect kernel process states without reaping the reserved group leader.
-#[cfg(target_os = "linux")]
-fn active_members(group: u32) -> std::io::Result<bool> {
- for entry in std::fs::read_dir("/proc")? {
- let entry = entry?;
- if entry.file_name().to_string_lossy().parse::<u32>().is_err() {
- continue;
- }
- // Process entries can disappear or become unreadable between
- // enumeration and reading.
- if let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) {
- if is_active_member(&stat, group) {
- return Ok(true);
- }
- }
- }
- Ok(false)
-}
-
-/// Zombies and dead tasks cannot execute further side effects.
-#[cfg(target_os = "linux")]
-pub(super) fn is_active_member(stat: &str, group: u32) -> bool {
- let Some((_, fields)) = stat.rsplit_once(") ") else {
- return false;
- };
- let mut fields = fields.split_whitespace();
- let state = fields.next();
- let process_group = fields.nth(1).and_then(|value| value.parse::<u32>().ok());
- process_group == Some(group) && !matches!(state, Some("Z" | "X" | "x"))
-}
-
-#[cfg(all(test, target_os = "linux"))]
-#[path = "group_exit_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/tools/timeout/group_exit_tests.rs b/crates/openhuman-core/src/tools/timeout/group_exit_tests.rs
deleted file mode 100644
index 4dd36b59f0..0000000000
--- a/crates/openhuman-core/src/tools/timeout/group_exit_tests.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use super::*;
-
-#[test]
-fn exited_members_do_not_block_cleanup_but_running_members_do() {
- for state in ["R", "S", "D", "T", "I"] {
- assert!(is_active_member(
- &format!("12 (name with ) spaces) {state} 1 42 42"),
- 42
- ));
- }
- for state in ["Z", "X", "x"] {
- assert!(!is_active_member(
- &format!("12 (sleep) {state} 1 42 42"),
- 42
- ));
- }
- assert!(!is_active_member("12 (sleep) R 1 43 43", 42));
- assert!(!is_active_member("malformed", 42));
-}
diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rs
index fe7dd7f898..da4dc0a244 100644
--- a/crates/openhuman-core/src/tools/timeout/mod.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod.rs
@@ -1,99 +1,67 @@
-//! Wall-clock timeout for tool execution (node/tool runtime + agent loop).
+//! Host adapter for tool-execution timeouts.
//!
-//! Resolution order, highest precedence first:
-//! 1. `OPENHUMAN_TOOL_TIMEOUT_SECS` environment variable (operator override).
-//! 2. The value pushed in from the persisted config via [`set_tool_timeout_secs`]
-//! (driven by the UI / `config.update_agent_settings` RPC).
-//! 3. The built-in [`DEFAULT_TIMEOUT_SECS`] (120) default.
+//! The bounds, resolution, process-group capture and cleanup live in
+//! `tinytools_std::timeout`. This module keeps only what OpenHuman owns: the
+//! `OPENHUMAN_TOOL_TIMEOUT_SECS` operator override, pushing the persisted
+//! config value into the module's settings, installing the harness-side
+//! settings, and carrying `CoreContext` into the module's waiter tasks.
//!
-//! The effective value lives in a process-global vendored
-//! [`ToolTimeoutSettings`] (atomic inside) and is read
-//! fresh on every tool call, so a UI change takes effect on the **next** tool
-//! call without a restart. The operator env var, when set to a valid value,
-//! always wins — config pushes are ignored while it is present (logged).
+//! Resolution order, highest precedence first:
+//! 1. `OPENHUMAN_TOOL_TIMEOUT_SECS` (operator override, when valid).
+//! 2. The value pushed from config via [`set_tool_timeout_secs`].
+//! 3. `tinytools_std::timeout::DEFAULT_TIMEOUT_SECS`.
-use std::sync::OnceLock;
-use std::time::Duration;
+use std::sync::{Once, OnceLock};
use tinyagents_harness::tool::ToolTimeoutSettings;
-use tinytools::ToolTimeout;
-
-mod command_environment;
-pub use command_environment::CommandEnvironment;
-mod group_exit;
-mod process_cleanup;
-pub use process_cleanup::ProcessCleanup;
+use tinytools_std::timeout::{
+ self as module, MAX_TIMEOUT_SECS, MIN_TIMEOUT_SECS, TOOL_TIMEOUT_GRACE_SECS,
+};
-/// Default tool-execution timeout in seconds when nothing else is configured.
-pub const DEFAULT_TIMEOUT_SECS: u64 = 120;
-/// Smallest accepted timeout. `0` would disable the timeout entirely, so it is
-/// rejected and falls back to the default.
-pub const MIN_TIMEOUT_SECS: u64 = 1;
-/// Largest accepted timeout (1 hour) — guards against typos that would make a
-/// hung tool wedge a session indefinitely.
-pub const MAX_TIMEOUT_SECS: u64 = 3600;
/// Operator override env var. Takes precedence over the persisted config value.
pub const ENV_VAR: &str = "OPENHUMAN_TOOL_TIMEOUT_SECS";
-/// Effective-unbounded cap (24h) for sandbox backends, which require a finite
-/// deadline. Scripting tools run truly unbounded on the native path, but the
-/// sandbox path substitutes this generous cap when no explicit `timeout_secs`
-/// was requested — long enough not to kill a legitimate long job, finite
-/// enough to eventually reclaim a wedged sandbox process.
-pub const SANDBOX_UNBOUNDED_CAP_SECS: u64 = 86_400;
-/// Grace slack (ms) the vendored settings add to an explicit per-call budget.
-const TOOL_TIMEOUT_GRACE_MS: u64 = TOOL_TIMEOUT_GRACE_SECS * 1000;
+static HARNESS_SETTINGS: OnceLock<ToolTimeoutSettings> = OnceLock::new();
+static CONFIGURE: Once = Once::new();
-/// Build vendored settings with OpenHuman's bounds and grace, inheriting
-/// `inherited_secs`.
-fn build_settings(inherited_secs: u64) -> ToolTimeoutSettings {
- ToolTimeoutSettings::new(
- inherited_secs.saturating_mul(1000),
- MIN_TIMEOUT_SECS * 1000,
- MAX_TIMEOUT_SECS * 1000,
- TOOL_TIMEOUT_GRACE_MS,
- )
+fn read_env() -> Option<String> {
+ std::env::var(ENV_VAR).ok()
}
-/// Process-global settings. Seeded from env/default on first touch; config
-/// pushes overwrite the inherited value through the vendored atomic.
-static SETTINGS: OnceLock<ToolTimeoutSettings> = OnceLock::new();
+/// Seed the module's process-global settings from env/default and register the
+/// task wrapper that keeps the caller's `CoreContext` in the module's waiter
+/// tasks. Idempotent; every entry point of this adapter calls it.
+fn ensure_configured() {
+ CONFIGURE.call_once(|| {
+ let secs = module::resolve_effective(module::DEFAULT_TIMEOUT_SECS, read_env().as_deref());
+ module::configure(module::TimeoutSettings::with_inherited_secs(secs));
+ module::set_task_wrapper(|fut| Box::pin(crate::core::runtime::scoped(fut)));
+ log::debug!("[tool_timeout] configured module settings inherited={secs}s");
+ });
+}
-fn settings() -> &'static ToolTimeoutSettings {
- SETTINGS.get_or_init(|| {
- build_settings(resolve_effective(
- DEFAULT_TIMEOUT_SECS,
- read_env().as_deref(),
- ))
+fn harness_settings() -> &'static ToolTimeoutSettings {
+ HARNESS_SETTINGS.get_or_init(|| {
+ ensure_configured();
+ ToolTimeoutSettings::new(
+ module::settings().inherited_timeout().as_millis() as u64,
+ MIN_TIMEOUT_SECS * 1000,
+ MAX_TIMEOUT_SECS * 1000,
+ TOOL_TIMEOUT_GRACE_SECS * 1000,
+ )
})
}
/// Install the process-global per-tool timeout settings on `harness`.
///
-/// The harness enforces a tool's [`ToolTimeout`] policy only when settings are
-/// installed (`AgentHarness::with_tool_timeout_settings`); without them every
-/// `Inherit` tool — MCP calls, `use_skill` dispatches, integration actions —
-/// ran until the run's wall-clock budget, so a hung call blocked the turn for
-/// ~600s instead of failing at the configured 120s (regressed when the host's
-/// own adapter deadline was removed in f33a398faa). The installed value is a
-/// clone of the shared settings, so later [`set_tool_timeout_secs`] pushes
-/// reach already-assembled harnesses on their next tool call.
-///
-/// Long-running tools opt out through their own policy rather than here:
-/// the scripting tool (`shell`) are `Unbounded` unless the call
-/// passes `timeout_secs`, media generation carries its own budget, and
-/// `composio_connect` / `browser` size theirs to the approval park they wait
-/// on inside `execute`.
+/// The harness enforces a tool's `ToolTimeout` policy only when settings are
+/// installed; without them every `Inherit` tool (MCP calls, `use_skill`,
+/// integration actions) ran until the run's wall-clock budget. The installed
+/// value shares its atomic with later [`set_tool_timeout_secs`] pushes.
pub fn install_harness_tool_timeouts<State: Send + Sync, Ctx: Send + Sync>(
harness: &mut tinyagents_harness::runtime::AgentHarness<State, Ctx>,
) {
- install_with(harness, settings().clone());
-}
-
-fn install_with<State: Send + Sync, Ctx: Send + Sync>(
- harness: &mut tinyagents_harness::runtime::AgentHarness<State, Ctx>,
- settings: ToolTimeoutSettings,
-) {
+ let settings = harness_settings().clone();
tracing::debug!(
inherited_secs = settings.inherited_timeout().map_or(0, |d| d.as_secs()),
"[tool_timeout] installing per-tool timeout settings on the harness"
@@ -101,328 +69,35 @@ fn install_with<State: Send + Sync, Ctx: Send + Sync>(
harness.with_tool_timeout_settings(settings);
}
-/// Parse a raw env-var value into a bounded timeout.
-///
-/// Testable split from the global resolution: this function is pure and never
-/// touches global state, so unit tests can exercise every path without racing
-/// on the atomic or mutating the process environment.
-///
-/// - `None` or a non-numeric string returns [`DEFAULT_TIMEOUT_SECS`].
-/// - Values outside `MIN_TIMEOUT_SECS..=MAX_TIMEOUT_SECS` are rejected (returns
-/// [`DEFAULT_TIMEOUT_SECS`]).
-/// - Valid values pass through unchanged.
-pub fn parse_tool_timeout_secs(raw: Option<&str>) -> u64 {
- raw.and_then(|s| s.parse::<u64>().ok())
- .filter(|&n| (MIN_TIMEOUT_SECS..=MAX_TIMEOUT_SECS).contains(&n))
- .unwrap_or(DEFAULT_TIMEOUT_SECS)
-}
-
-/// The operator env override, if `ENV_VAR` is set to a value inside the valid
-/// range. A present-but-invalid env value (non-numeric, `0`, out of range) is
-/// treated as "no override" so the config value still applies.
-fn env_override_from(raw: Option<&str>) -> Option<u64> {
- raw.and_then(|s| s.parse::<u64>().ok())
- .filter(|&n| (MIN_TIMEOUT_SECS..=MAX_TIMEOUT_SECS).contains(&n))
-}
-
-/// Pure resolver used by both seeding and config pushes. Env override wins;
-/// otherwise the (bounded) config value applies.
-fn resolve_effective(config_secs: u64, env_raw: Option<&str>) -> u64 {
- match env_override_from(env_raw) {
- Some(env) => env,
- None => parse_tool_timeout_secs(Some(&config_secs.to_string())),
- }
-}
-
-fn read_env() -> Option<String> {
- std::env::var(ENV_VAR).ok()
-}
-
/// `true` when the operator env var is set to a valid override, meaning UI /
-/// config changes to the timeout are ignored in favour of it. Surfaced to the
-/// frontend so the settings panel can explain why its control has no effect.
+/// config changes to the timeout are ignored in favour of it.
pub fn env_override_active() -> bool {
- env_override_from(read_env().as_deref()).is_some()
-}
-
-/// Effective inherited timeout in whole seconds, seeding the global settings
-/// from env/default on first read.
-fn current_secs() -> u64 {
- settings().inherited_timeout().map_or(0, |d| d.as_secs())
+ module::override_from(read_env().as_deref()).is_some()
}
/// Push a config-sourced timeout into the runtime. The operator env override,
-/// when active, always wins and `config_secs` is ignored (logged at debug).
-/// Returns the effective value stored after the call. Idempotent and safe to
-/// call repeatedly (e.g. at startup and on every config update).
+/// when active, always wins. Returns the effective value stored.
pub fn set_tool_timeout_secs(config_secs: u64) -> u64 {
+ ensure_configured();
let env_raw = read_env();
- let effective = resolve_effective(config_secs, env_raw.as_deref());
- settings().set_inherited_timeout_ms(effective.saturating_mul(1000));
- if env_override_from(env_raw.as_deref()).is_some() {
+ let effective = module::resolve_effective(config_secs, env_raw.as_deref());
+ let ms = effective.saturating_mul(1000);
+ module::settings().set_inherited_timeout_ms(ms);
+ harness_settings().set_inherited_timeout_ms(ms);
+ if module::override_from(env_raw.as_deref()).is_some() {
log::debug!(
"[tool_timeout] config update ignored: env {ENV_VAR}={effective}s overrides requested {config_secs}s"
);
} else {
- log::debug!(
- "[tool_timeout] runtime timeout set to {effective}s (requested {config_secs}s)"
- );
+ log::debug!("[tool_timeout] runtime timeout set to {effective}s (requested {config_secs}s)");
}
effective
}
-/// Effective timeout in seconds — used for logging and matching frontend
-/// timeouts. Read fresh on every call.
+/// Effective timeout in seconds, read fresh on every call.
pub fn tool_execution_timeout_secs() -> u64 {
- current_secs()
-}
-
-/// Resolve an **explicit** per-call timeout request for a tool that is
-/// otherwise unbounded (the scripting tool: `shell`).
-///
-/// Unlike most tools — which inherit the global config-driven timeout so a hung
-/// network/MCP call can't wedge a session — scripting tools run with **no**
-/// default deadline: a build / solver / test run legitimately takes minutes and
-/// must not be hard-killed by a default cap (issue #4023). A deadline applies
-/// only when the caller explicitly asks for one via `timeout_secs`.
-///
-/// Returns:
-/// - `None` → run unbounded. Used when no `timeout_secs` was supplied
-/// (`None`) or it was explicitly disabled (`Some(0)`).
-/// - `Some(secs)` → enforce this budget, clamped to `MIN_TIMEOUT_SECS..=cap`.
-/// `cap` lets callers with a tighter own-ceiling (e.g. node/npm at 1800s)
-/// pass it; most callers pass [`MAX_TIMEOUT_SECS`].
-pub fn explicit_call_timeout_secs(requested: Option<u64>, cap: u64) -> Option<u64> {
- let cap = cap.clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);
- match requested {
- None | Some(0) => None,
- Some(n) => Some(n.clamp(MIN_TIMEOUT_SECS, cap)),
- }
-}
-
-/// [`explicit_call_timeout_secs`] as a [`Duration`], or `None` for unbounded.
-pub fn explicit_call_timeout_duration(requested: Option<u64>, cap: u64) -> Option<Duration> {
- explicit_call_timeout_secs(requested, cap).map(Duration::from_secs)
-}
-
-/// Extra slack added on top of an explicit per-call budget before the hard
-/// `tokio::time::timeout` fires, so a tool that finishes right at its requested
-/// deadline isn't killed by scheduler jitter. The user-facing `timeout_secs`
-/// reported on a timeout is the un-padded request.
-const TOOL_TIMEOUT_GRACE_SECS: u64 = 5;
-
-/// Pure core of [`resolve_tool_deadline`]: the inherited timeout is a parameter
-/// so tests can table-drive it without touching the process-global.
-/// Run `cmd` to completion with its output captured, or kill it -- and every
-/// process it started -- when `deadline` passes.
-///
-/// `tokio::time::timeout(deadline, cmd.output())` only abandons the future.
-/// Without `kill_on_drop` the child is not even signalled, and a shell's
-/// pipeline (`grep -r … | head`) is a set of grandchildren that no kill of the
-/// direct child reaches anyway. One `grep -rl … /` the shell tool had reported
-/// as "timed out after 600s and was killed" ran on for half an hour at a full
-/// core inside a two-CPU container, starving the agent that had started it.
-///
-/// So the child is spawned as the leader of its own process group and the
-/// whole group is signalled when the deadline fires. The result has the same
-/// shape as `timeout(deadline, cmd.output())`, so a caller's match arms do not
-/// change. Stdio is set the way `output()` sets it: stdin closed, both output
-/// streams captured.
-pub async fn output_or_kill(
- cmd: &mut tokio::process::Command,
- deadline: Duration,
-) -> Result<std::io::Result<std::process::Output>, tokio::time::error::Elapsed> {
- tokio::time::timeout(deadline, output_unbounded(cmd)).await
-}
-
-/// Capture a command with no deadline, killing its process group if the
-/// future is dropped. The child is reaped by an owned waiter even when the
-/// 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(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 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 = crate::core::runtime::spawn_scoped(async move {
- let _reaped = reaped;
- 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)?
-}
-
-// The caller signals only the owned waiter. It never retains a PID after
-// that waiter reaps the child, so late future drops cannot kill a reused PID.
-struct CancelOnDrop(tokio::sync::watch::Sender<bool>);
-
-impl Drop for CancelOnDrop {
- fn drop(&mut self) {
- self.0.send_replace(true);
- }
-}
-
-struct CommandGroup(Option<u32>);
-
-impl CommandGroup {
- fn kill(&self) {
- if let Some(pid) = self.0 {
- kill_process_group(pid);
- }
- }
-}
-
-impl Drop for CommandGroup {
- fn drop(&mut self) {
- self.kill();
- }
-}
-
-async fn collect_command_output(
- mut child: tokio::process::Child,
- mut cancellation: tokio::sync::watch::Receiver<bool>,
-) -> std::io::Result<std::process::Output> {
- use tokio::io::AsyncReadExt;
-
- let mut group = CommandGroup(child.id());
- let mut stdout = child.stdout.take().expect("command stdout is piped");
- let mut stderr = child.stderr.take().expect("command stderr is piped");
- let mut stdout_bytes = Vec::new();
- let mut stderr_bytes = Vec::new();
- {
- let drain = async {
- tokio::try_join!(
- stdout.read_to_end(&mut stdout_bytes),
- stderr.read_to_end(&mut stderr_bytes),
- )
- };
- tokio::pin!(drain);
- tokio::select! {
- biased;
- _ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {
- // The leader has not been reaped, even if it already exited.
- // Its PID cannot be reused while signalling this group.
- group.kill();
- child.start_kill()?;
- if let Ok(result) = tokio::time::timeout(Duration::from_secs(2), drain).await {
- result?;
- }
- }
- result = &mut drain => { result?; }
- }
- }
- let status = tokio::select! {
- biased;
- _ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {
- group.kill();
- child.start_kill()?;
- // Pipe EOF and the shell's exit can precede a descendant's exit.
- // Keep the leader unreaped while checking the reserved group.
- let stopped = match group.0 {
- Some(pid) => group_exit::wait(pid).await,
- None => Ok(()),
- };
- let status = child.wait().await?;
- // Disarm before propagating a check error after reaping: its PID
- // could now be reused, including while unwinding this function.
- group.0 = None;
- stopped?;
- status
- }
- result = child.wait() => result?,
- };
- // No await between reaping and disarming. Only this waiter owns the PID.
- group.0 = None;
- Ok(std::process::Output {
- status,
- stdout: stdout_bytes,
- stderr: stderr_bytes,
- })
-}
-
-/// Make `cmd` the leader of a new process group when it is spawned, so that
-/// [`kill_process_group`] can reach everything it starts. A no-op off Unix.
-pub fn own_process_group(cmd: &mut std::process::Command) {
- #[cfg(unix)]
- {
- use std::os::unix::process::CommandExt;
- cmd.process_group(0);
- }
- #[cfg(not(unix))]
- {
- let _ = cmd;
- }
-}
-
-/// Send SIGKILL to the process group led by `pid` -- a child spawned via
-/// [`own_process_group`] and everything it started. Off Unix the direct child
-/// is what `kill_on_drop` reaches and no group exists to signal.
-pub fn kill_process_group(pid: u32) {
- #[cfg(unix)]
- {
- let Ok(pid) = i32::try_from(pid) else {
- return;
- };
- // SAFETY: a signal to a process group this process created; the kernel
- // validates the target, and a negative pid addresses the group.
- unsafe {
- libc::kill(-pid, libc::SIGKILL);
- }
- }
- #[cfg(not(unix))]
- {
- let _ = pid;
- }
-}
-
-#[cfg(test)]
-fn resolve_tool_deadline_with(policy: ToolTimeout, inherited_secs: u64) -> (Option<Duration>, u64) {
- resolve_with(&build_settings(inherited_secs), policy)
-}
-
-/// Delegate to the vendored resolver. An explicit millisecond request is
-/// rounded up to whole seconds first (OpenHuman reports whole-second budgets);
-/// clamping and the grace pad come from [`ToolTimeoutSettings`].
-fn resolve_with(settings: &ToolTimeoutSettings, policy: ToolTimeout) -> (Option<Duration>, u64) {
- let policy = match policy {
- ToolTimeout::Millis(req) => ToolTimeout::Millis(
- req.saturating_add(999)
- .saturating_div(1000)
- .saturating_mul(1000),
- ),
- other => other,
- };
- let resolved = settings.resolve(policy);
- (resolved.deadline, resolved.budget_ms / 1000)
+ ensure_configured();
+ module::settings().inherited_timeout().as_secs()
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/tools/timeout/mod_tests.rs b/crates/openhuman-core/src/tools/timeout/mod_tests.rs
index 16e578a646..a5f34e791d 100644
--- a/crates/openhuman-core/src/tools/timeout/mod_tests.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod_tests.rs
@@ -1,380 +1,43 @@
use super::*;
#[test]
-fn default_when_env_missing() {
- assert_eq!(parse_tool_timeout_secs(None), DEFAULT_TIMEOUT_SECS);
-}
-
-#[test]
-fn default_when_value_not_numeric() {
- assert_eq!(
- parse_tool_timeout_secs(Some("not-a-number")),
- DEFAULT_TIMEOUT_SECS
- );
- assert_eq!(parse_tool_timeout_secs(Some("")), DEFAULT_TIMEOUT_SECS);
- assert_eq!(parse_tool_timeout_secs(Some("12x")), DEFAULT_TIMEOUT_SECS);
-}
-
-#[test]
-fn default_when_value_zero() {
- // 0 seconds would disable the timeout — reject and fall back.
- assert_eq!(parse_tool_timeout_secs(Some("0")), DEFAULT_TIMEOUT_SECS);
-}
-
-#[test]
-fn default_when_value_above_max() {
- assert_eq!(parse_tool_timeout_secs(Some("3601")), DEFAULT_TIMEOUT_SECS);
+fn config_push_reaches_module_and_harness_settings() {
+ // Skip when an operator override would legitimately win.
+ if env_override_active() {
+ return;
+ }
+ let effective = set_tool_timeout_secs(321);
+ assert_eq!(effective, 321);
+ assert_eq!(tool_execution_timeout_secs(), 321);
assert_eq!(
- parse_tool_timeout_secs(Some("99999999999")),
- DEFAULT_TIMEOUT_SECS
+ harness_settings().inherited_timeout().map(|d| d.as_secs()),
+ Some(321)
);
+ set_tool_timeout_secs(module::DEFAULT_TIMEOUT_SECS);
}
#[test]
-fn default_when_value_negative_or_signed() {
- // Negative values fail u64 parse and fall back to default.
- assert_eq!(parse_tool_timeout_secs(Some("-5")), DEFAULT_TIMEOUT_SECS);
-}
-
-#[test]
-fn accepts_valid_values_at_boundaries() {
- assert_eq!(parse_tool_timeout_secs(Some("1")), MIN_TIMEOUT_SECS);
- assert_eq!(parse_tool_timeout_secs(Some("3600")), MAX_TIMEOUT_SECS);
-}
-
-#[test]
-fn accepts_valid_midrange_value() {
- assert_eq!(parse_tool_timeout_secs(Some("300")), 300);
-}
-
-#[test]
-fn env_override_takes_precedence_over_config() {
- // When the env var holds a valid value it wins over the config value.
- assert_eq!(resolve_effective(300, Some("600")), 600);
-}
-
-#[test]
-fn config_value_used_when_env_absent_or_invalid() {
- // No env → config drives the effective value (bounded).
- assert_eq!(resolve_effective(300, None), 300);
- // Present-but-invalid env (non-numeric / 0 / out of range) is ignored,
- // so the config value still applies.
- assert_eq!(resolve_effective(300, Some("nonsense")), 300);
- assert_eq!(resolve_effective(300, Some("0")), 300);
- assert_eq!(resolve_effective(300, Some("4000")), 300);
-}
-
-#[test]
-fn config_value_is_bounded() {
- // An out-of-range config value falls back to the default rather than
- // being applied verbatim.
- assert_eq!(resolve_effective(0, None), DEFAULT_TIMEOUT_SECS);
- assert_eq!(resolve_effective(99_999, None), DEFAULT_TIMEOUT_SECS);
-}
-
-#[test]
-fn explicit_call_timeout_unbounded_when_absent_or_disabled() {
- // No request, or an explicit 0, means "run unbounded" (None).
- assert_eq!(explicit_call_timeout_secs(None, MAX_TIMEOUT_SECS), None);
- assert_eq!(explicit_call_timeout_secs(Some(0), MAX_TIMEOUT_SECS), None);
-}
-
-#[test]
-fn explicit_call_timeout_enforces_and_clamps_request() {
- // An in-range request is enforced verbatim.
- assert_eq!(
- explicit_call_timeout_secs(Some(900), MAX_TIMEOUT_SECS),
- Some(900)
- );
- // Below the floor clamps up to MIN.
- assert_eq!(
- explicit_call_timeout_secs(Some(0), MAX_TIMEOUT_SECS),
- None,
- "0 disables rather than clamping to MIN"
- );
- // Above the cap clamps down to the cap.
- assert_eq!(
- explicit_call_timeout_secs(Some(99_999), MAX_TIMEOUT_SECS),
- Some(MAX_TIMEOUT_SECS)
- );
- // A tool with a tighter own ceiling (node/npm at 1800) clamps to it.
- assert_eq!(explicit_call_timeout_secs(Some(99_999), 1800), Some(1800));
- assert_eq!(explicit_call_timeout_secs(Some(600), 1800), Some(600));
-}
-
-#[test]
-fn explicit_call_timeout_duration_matches_secs() {
- assert_eq!(
- explicit_call_timeout_duration(Some(900), MAX_TIMEOUT_SECS),
- Some(Duration::from_secs(900))
- );
- assert_eq!(explicit_call_timeout_duration(None, MAX_TIMEOUT_SECS), None);
-}
-
-#[test]
-fn env_override_from_rejects_invalid() {
- assert_eq!(env_override_from(None), None);
- assert_eq!(env_override_from(Some("")), None);
- assert_eq!(env_override_from(Some("0")), None);
- assert_eq!(env_override_from(Some("abc")), None);
- assert_eq!(env_override_from(Some("3601")), None);
- assert_eq!(env_override_from(Some("120")), Some(120));
-}
-
-/// Table of `(policy, inherited config secs, expected (deadline_ms, budget_secs))`.
-/// Pins `resolve_tool_deadline` so its behaviour is identical whether it is
-/// implemented locally or delegated to the vendored `ToolTimeoutSettings`.
-#[test]
-fn resolve_tool_deadline_table() {
- use tinytools::ToolTimeout;
- let ms = |m: u64| Some(Duration::from_millis(m));
- let cases: Vec<(ToolTimeout, u64, (Option<Duration>, u64))> = vec![
- // Inherit: the global config value, no grace.
- (ToolTimeout::Inherit, 120, (ms(120_000), 120)),
- (ToolTimeout::Inherit, 1, (ms(1_000), 1)),
- (ToolTimeout::Inherit, 3600, (ms(3_600_000), 3600)),
- // Unbounded: no deadline, zero budget.
- (ToolTimeout::Unbounded, 120, (None, 0)),
- // Millis: rounded UP to whole seconds, clamped, +5s grace on deadline.
- (ToolTimeout::Millis(0), 120, (ms(6_000), 1)),
- (ToolTimeout::Millis(1), 120, (ms(6_000), 1)),
- (ToolTimeout::Millis(1_000), 120, (ms(6_000), 1)),
- (ToolTimeout::Millis(1_001), 120, (ms(7_000), 2)),
- (ToolTimeout::Millis(1_500), 120, (ms(7_000), 2)),
- (ToolTimeout::Millis(30_000), 120, (ms(35_000), 30)),
- (ToolTimeout::Millis(3_600_000), 120, (ms(3_605_000), 3600)),
- (ToolTimeout::Millis(3_600_001), 120, (ms(3_605_000), 3600)),
- (ToolTimeout::Millis(u64::MAX), 120, (ms(3_605_000), 3600)),
- ];
- for (policy, inherited_secs, expected) in cases {
- // Resolve against the pure helper so the process-global stays untouched.
- let got = resolve_tool_deadline_with(policy, inherited_secs);
- assert_eq!(
- got, expected,
- "policy {policy:?} inherited {inherited_secs}s"
- );
+fn out_of_range_config_push_falls_back_to_default() {
+ if env_override_active() {
+ return;
}
+ assert_eq!(set_tool_timeout_secs(0), module::DEFAULT_TIMEOUT_SECS);
+ assert_eq!(set_tool_timeout_secs(99_999), module::DEFAULT_TIMEOUT_SECS);
}
-/// Env / config precedence table for the effective inherited timeout.
#[test]
-fn resolve_effective_table() {
- let cases: &[(u64, Option<&str>, u64)] = &[
- (300, None, 300),
- (300, Some("600"), 600),
- (300, Some("1"), 1),
- (300, Some("3600"), 3600),
- (300, Some("3601"), 300),
- (300, Some("0"), 300),
- (300, Some("-1"), 300),
- (300, Some(""), 300),
- (300, Some("abc"), 300),
- (0, None, DEFAULT_TIMEOUT_SECS),
- (0, Some("45"), 45),
- (3601, None, DEFAULT_TIMEOUT_SECS),
- (u64::MAX, None, DEFAULT_TIMEOUT_SECS),
- (1, None, 1),
- (3600, None, 3600),
- ];
- for &(config, env, expected) in cases {
- assert_eq!(
- resolve_effective(config, env),
- expected,
- "config {config} env {env:?}"
- );
- }
+fn env_var_name_is_the_documented_wire_name() {
+ assert_eq!(ENV_VAR, "OPENHUMAN_TOOL_TIMEOUT_SECS");
}
-/// The deadline must take the command's whole process group with it. A shell
-/// pipeline is grandchildren of the tool's child, and a `grep -rl … /` the tool
-/// had reported as killed ran on for half an hour at a full core.
#[cfg(unix)]
#[tokio::test]
-async fn a_timed_out_command_takes_its_whole_process_group_with_it() {
- let dir = std::env::temp_dir().join(format!("oh-pgkill-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let pidfile = dir.join("grandchild.pid");
- // `sleep 30 &` is a grandchild in the shell's own process group; `wait`
- // keeps the shell alive past the deadline.
- let mut cmd = crate::agent::platform_shell::build_tokio_command(&format!(
- "sleep 30 & echo $! > {}; wait",
- pidfile.display()
- ));
- let result = output_or_kill(&mut cmd, Duration::from_millis(700)).await;
- assert!(result.is_err(), "the deadline must fire on a 30s sleep");
-
- let grandchild: i32 = loop {
- if let Ok(text) = std::fs::read_to_string(&pidfile) {
- if let Ok(pid) = text.trim().parse() {
- break pid;
- }
- }
- tokio::time::sleep(Duration::from_millis(20)).await;
- };
- let mut gone = false;
- for _ in 0..100 {
- // kill(pid, 0) succeeds while the process (or its zombie) exists.
- if unsafe { libc::kill(grandchild, 0) } != 0 {
- gone = true;
- break;
- }
- // A container's PID 1 may leave a killed orphan unreaped. It cannot
- // execute side effects; use the same kernel-state rule as cleanup.
- #[cfg(target_os = "linux")]
- if let Ok(stat) = std::fs::read_to_string(format!("/proc/{grandchild}/stat")) {
- let group = unsafe { libc::getpgid(grandchild) };
- if group > 0 && !super::group_exit::is_active_member(&stat, group as u32) {
- gone = true;
- break;
- }
- }
- tokio::time::sleep(Duration::from_millis(20)).await;
- }
- let _ = std::fs::remove_dir_all(&dir);
- assert!(gone, "grandchild {grandchild} survived the deadline");
-}
-
-/// Without a deadline the child still dies with the handle: a cancelled tool
-/// future must not leave the command running either.
-#[cfg(unix)]
-#[tokio::test]
-async fn a_shell_family_child_dies_with_a_dropped_future() {
- let dir = std::env::temp_dir().join(format!("oh-dropkill-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let pidfile = dir.join("child.pid");
- let mut cmd = crate::agent::platform_shell::build_tokio_command(&format!(
- "echo $$ > {}; sleep 30",
- pidfile.display()
- ));
- // `timeout` takes the future by value and drops it when the deadline
- // passes -- exactly the abandoned-future path a cancelled tool call takes.
- let _ = tokio::time::timeout(Duration::from_millis(300), cmd.output()).await;
- let shell: i32 = loop {
- if let Ok(text) = std::fs::read_to_string(&pidfile) {
- if let Ok(pid) = text.trim().parse() {
- break pid;
- }
- }
- tokio::time::sleep(Duration::from_millis(20)).await;
- };
- let mut gone = false;
- for _ in 0..100 {
- if unsafe { libc::kill(shell, 0) } != 0 {
- gone = true;
- break;
- }
- tokio::time::sleep(Duration::from_millis(20)).await;
- }
- let _ = std::fs::remove_dir_all(&dir);
- assert!(gone, "shell {shell} survived its dropped future");
-}
-
-// ── Harness installation (regression: the 120s default was never installed
-// into the TinyAgents harness after f33a398faa, so `Inherit` tools ran until
-// the run's wall-clock budget) ──────────────────────────────────────────────
-
-mod harness_install {
- use super::*;
- use std::sync::atomic::{AtomicBool, Ordering};
- use std::sync::Arc;
-
- use async_trait::async_trait;
- use serde_json::{json, Value};
- use tinyagents_harness::runtime::AgentHarness;
- use tinyagents_harness::testkit::{text_response, tool_call_response};
- use tinyinference_llm::message::Message;
- use tinyinference_llm::providers::MockModel;
- use tinyinference_llm::tool::ToolCall;
- use tinytools::{Tool, ToolResult};
-
- /// A tool that inherits the global timeout and never finishes in time.
- struct HungTool {
- finished: Arc<AtomicBool>,
- }
-
- #[async_trait]
- impl Tool for HungTool {
- fn name(&self) -> &str {
- "hung_mcp_call"
- }
- fn description(&self) -> &str {
- "stands in for an MCP call that never answers"
- }
- fn parameters_schema(&self) -> Value {
- json!({"type": "object"})
- }
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- tokio::time::sleep(Duration::from_secs(60)).await;
- self.finished.store(true, Ordering::SeqCst);
- Ok(ToolResult::success("too late"))
- }
- }
-
- #[test]
- fn the_host_installs_the_shared_settings() {
- let mut harness: AgentHarness<(), ()> = AgentHarness::new();
- assert!(harness.tool_timeout_settings().is_none());
- install_harness_tool_timeouts(&mut harness);
- let installed = harness
- .tool_timeout_settings()
- .expect("the host installs per-tool timeout settings");
- assert_eq!(installed, settings());
- assert_eq!(
- installed.resolve(ToolTimeout::Inherit).deadline,
- Some(Duration::from_secs(tool_execution_timeout_secs())),
- "an Inherit tool gets the configured deadline"
- );
- assert_eq!(
- installed.resolve(ToolTimeout::Unbounded).deadline,
- None,
- "long-running tools that declare Unbounded stay exempt"
- );
- }
-
- #[tokio::test]
- async fn a_hung_inherit_tool_is_cut_off_at_its_budget() {
- let finished = Arc::new(AtomicBool::new(false));
- let mut harness: AgentHarness<(), ()> = AgentHarness::new();
- harness.register_model(
- "mock",
- Arc::new(MockModel::with_responses(vec![
- tool_call_response(ToolCall::new("c1", "hung_mcp_call", json!({}))),
- text_response("done"),
- ])),
- );
- harness.register_tool(Arc::new(HungTool {
- finished: finished.clone(),
- }));
- // One-second inherited budget so the test is fast; production installs
- // the same type with the configured 120s.
- install_with(&mut harness, build_settings(1));
-
- let started = std::time::Instant::now();
- let run = harness
- .invoke_in_context(
- &(),
- tinyagents_harness::context::RunContext::new(
- tinyagents_harness::context::RunConfig::new("timeout-e2e"),
- (),
- ),
- vec![Message::user("go")],
- )
- .await
- .expect("a timed-out tool is a recoverable result, not a run failure");
- let elapsed = started.elapsed();
-
- assert!(
- elapsed < Duration::from_secs(20),
- "the call is cut at its budget, not left to run: {elapsed:?}"
- );
- assert!(
- !finished.load(Ordering::SeqCst),
- "the hung call never completed"
- );
- let transcript = format!("{:?}", run.messages);
- assert!(
- transcript.contains("hung_mcp_call") && transcript.contains("timed out after 1000 ms"),
- "the model is told the tool timed out: {transcript}"
- );
- }
+async fn adapter_wrapped_waiter_reaps_a_timed_out_group() {
+ ensure_configured();
+ let mut cmd = tokio::process::Command::new("sh");
+ cmd.args(["-c", "sleep 30 & wait"]);
+ let started = std::time::Instant::now();
+ let out = module::output_or_kill(&mut cmd, std::time::Duration::from_millis(200)).await;
+ assert!(out.is_err(), "deadline should elapse");
+ assert!(started.elapsed() < std::time::Duration::from_secs(10));
}
diff --git a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
deleted file mode 100644
index 566a60e340..0000000000
--- a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-//! Track command reaping for an embedder that awaits turn cancellation.
-
-use std::future::Future;
-use std::sync::{Arc, Mutex};
-
-use tokio::sync::watch;
-
-tokio::task_local! {
- static ACTIVE: Vec<ProcessCleanup>;
-}
-
-/// Command waiters belonging to one turn. Clone before scoping the turn;
-/// after dropping the turn future, [`wait`](Self::wait) awaits their reaping.
-/// Tasks spawned by a host tool must explicitly inherit this scope.
-#[derive(Clone, Default)]
-pub struct ProcessCleanup(Arc<Mutex<Vec<watch::Receiver<bool>>>>);
-
-impl ProcessCleanup {
- /// Whether the current task must acknowledge owned subprocess cleanup.
- /// Interpreter pools have no per-job cancellation acknowledgement and
- /// therefore cannot accept work from this scope.
- pub fn is_active() -> bool {
- ACTIVE.try_with(|_| ()).is_ok()
- }
-
- /// Run a future with command waiters registered to this turn.
- pub async fn scope<T>(&self, future: impl Future<Output = T>) -> T {
- 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.
- /// Call only after the scoped future has finished or been dropped, so no
- /// further commands can be registered by it.
- pub async fn wait(&self) {
- let waiters = self
- .0
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .clone();
- for mut waiter in waiters {
- let _ = waiter.wait_for(|done| *done).await;
- }
- }
-}
-
-pub(super) struct Reaped(watch::Sender<bool>);
-
-impl Reaped {
- pub(super) fn register() -> Self {
- let (done, waiter) = watch::channel(false);
- 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)
- }
-}
-
-impl Drop for Reaped {
- fn drop(&mut self) {
- self.0.send_replace(true);
- }
-}