Skip to content

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

feat(embed): await per-turn cancellation and reap tool commands

Steven Enamakelac0b5a68db55
diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
index eaef0c2e54..72c3f01685 100644
--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
@@ -313,7 +313,7 @@ impl NodeExecTool {
// completion (no harness/tool timeout on long scripts).
let result = match explicit_timeout {
Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
- None => Ok(cmd.output().await),
+ None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),
};
match result {
diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
index 4b415b1942..479a4ffc50 100644
--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
@@ -304,7 +304,7 @@ impl NpmExecTool {
// completion (no harness/tool timeout on long installs/builds).
let result = match explicit_timeout {
Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
- None => Ok(cmd.output().await),
+ None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),
};
match result {
diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
index 5ec0d45af7..598f292d8c 100644
--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
@@ -314,7 +314,7 @@ impl PythonExecTool {
let result = match explicit_timeout {
Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
- None => Ok(cmd.output().await),
+ None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),
};
match result {
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index 4aa2b2d1fd..0116805aaa 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -442,7 +442,7 @@ impl ShellTool {
);
let result = match explicit_timeout {
Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
- None => Ok(cmd.output().await),
+ None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),
};
let tool_result = match result {
diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rs
index fa9b9e13e7..6144a7c2b5 100644
--- a/crates/openhuman-core/src/tools/timeout/mod.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod.rs
@@ -18,6 +18,9 @@ use std::time::Duration;
use tinyagents_harness::tool::ToolTimeoutSettings;
use tinytools::ToolTimeout;
+mod process_cleanup;
+pub use process_cleanup::ProcessCleanup;
+
/// 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
@@ -226,28 +229,83 @@ 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> {
use std::process::Stdio;
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
own_process_group(cmd.as_std_mut());
- let child = match cmd.spawn() {
- Ok(child) => child,
- Err(error) => return Ok(Err(error)),
- };
+ let child = cmd.spawn()?;
let pid = child.id();
- match tokio::time::timeout(deadline, child.wait_with_output()).await {
- Ok(output) => Ok(output),
- Err(elapsed) => {
- if let Some(pid) = pid {
- kill_process_group(pid);
- }
- Err(elapsed)
+ 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 mut group = CommandGroup { pid, cancel };
+ let result = waiter.await.map_err(std::io::Error::other)?;
+ group.pid = None;
+ result
+}
+
+struct CommandGroup {
+ pid: Option<u32>,
+ cancel: tokio::sync::watch::Sender<bool>,
+}
+
+impl Drop for CommandGroup {
+ fn drop(&mut self) {
+ if let Some(pid) = self.pid {
+ kill_process_group(pid);
+ self.cancel.send_replace(true);
}
}
}
+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 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 wait = async {
+ tokio::select! {
+ biased;
+ _ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {
+ // Reap the direct child on every platform. On Unix the
+ // caller has also signalled the process group.
+ child.kill().await?;
+ child.wait().await
+ }
+ result = child.wait() => result,
+ }
+ };
+ let (status, _, _) = tokio::try_join!(
+ wait,
+ stdout.read_to_end(&mut stdout_bytes),
+ stderr.read_to_end(&mut stderr_bytes),
+ )?;
+ 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) {
diff --git a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
new file mode 100644
index 0000000000..94535c0efc
--- /dev/null
+++ b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs
@@ -0,0 +1,59 @@
+//! 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: 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 {
+ /// 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
+ }
+
+ /// 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(|cleanup| {
+ cleanup
+ .0
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .push(waiter);
+ });
+ Self(done)
+ }
+}
+
+impl Drop for Reaped {
+ fn drop(&mut self) {
+ self.0.send_replace(true);
+ }
+}
diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.md
index c342b18199..a1e18849c3 100644
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@ -77,6 +77,32 @@ that controllers emit. `CoreAgent` runs the runtime's orchestrator over the
facade does not model yet; a raw call that keeps coming back is a candidate
for a typed method here.
+## Cancelling one turn
+
+Acquire `Turn::cancellation_handle()` before sending a turn. The handle is
+cloneable and `cancel().await` waits for the turn to stop and for tracked
+commands to be reaped. The agent remains available for later turns:
+
+```rust,no_run
+# async fn demo(agent: &openhuman_embed::Agent) -> Result<(), Box<dyn std::error::Error>> {
+let mut turn = agent.turn("Run the job.");
+let cancel = turn.cancellation_handle();
+let running = tokio::spawn(turn.send());
+// When the host receives an abort request:
+cancel.cancel().await;
+assert!(matches!(running.await?, Err(openhuman_embed::CoreError::TurnCancelled { .. })));
+# Ok(())
+# }
+```
+
+Cancellation is scoped to this turn, including while waiting for inference.
+Before send, cancellation prevents dispatch; after completion it is a no-op.
+On Unix, the built-in shell, Node, Python and npm commands kill their process
+group, including descendants. Other platforms stop the direct command. Host
+tools that spawn independent tasks or processes must provide their own cleanup;
+MCP server lifecycles remain owned by the agent. Keep polling `send()` while
+awaiting cancellation, for example in a spawned task as above.
+
## Using it
Add the dependency with the default contributor features, or pick a narrow
diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rs
index ad42eb1e55..8564acf322 100644
--- a/crates/openhuman-embed/src/error.rs
+++ b/crates/openhuman-embed/src/error.rs
@@ -26,6 +26,12 @@ use openhuman_core::core::StructuredRpcError;
/// Error returned by every typed facade call.
#[derive(Debug, thiserror::Error)]
pub enum CoreError {
+ /// The host cancelled this turn through its cancellation handle.
+ #[error("{method}: turn cancelled")]
+ TurnCancelled {
+ /// RPC method the turn was dispatching.
+ method: &'static str,
+ },
/// The domain returned a structured error envelope.
#[error("{method}: {message}")]
Domain {
@@ -167,7 +173,8 @@ impl CoreError {
| CoreError::Decode { method, .. }
| CoreError::InsecureRoute { method, .. }
| CoreError::InvalidRoute { method }
- | CoreError::AgentRemoved { method, .. } => method,
+ | CoreError::AgentRemoved { method, .. }
+ | CoreError::TurnCancelled { method } => method,
}
}
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 0ff7d09900..7eb65983ad 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -118,6 +118,7 @@ pub mod process;
pub mod profiles;
mod runtime;
mod turn;
+mod turn_cancellation;
/// Core internals for `openhuman-tinyhumans` and `openhuman-rpc` only; see
/// the module docs. Not part of the host-facing API.
@@ -215,6 +216,7 @@ pub use complete::{
};
pub use session_store::{InMemorySessionStores, SessionStoreProvider};
pub use turn::{absolute, Route, Turn, TurnOutcome, TurnRequest};
+pub use turn_cancellation::TurnCancellation;
use std::sync::Arc;
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 0f453a9b69..5400b3e760 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -258,6 +258,7 @@ pub struct Turn {
response_format: Option<crate::complete::ResponseFormat>,
max_tokens: Option<u32>,
untrusted_input: bool,
+ cancellation: Option<crate::TurnCancellation>,
}
impl Turn {
@@ -273,6 +274,7 @@ impl Turn {
response_format: None,
max_tokens: None,
untrusted_input: false,
+ cancellation: None,
}
}
@@ -474,6 +476,38 @@ impl Turn {
/// that is a build/composition fact, not a failure, and a host should hide
/// the surface rather than report an error.
pub async fn send(mut self) -> Result<TurnOutcome, CoreError> {
+ let Some(cancellation) = self.cancellation.take() else {
+ return self.send_inner().await;
+ };
+ let _guard = cancellation.enter();
+ let outcome = cancellation
+ .cleanup()
+ .scope(async {
+ tokio::select! {
+ biased;
+ _ = cancellation.cancelled() => {
+ log::debug!("[embed][agent] turn cancelled");
+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })
+ }
+ outcome = Box::pin(self.send_inner()) => outcome,
+ }
+ })
+ .await;
+ // The dispatch future is dropped before waiting for its command
+ // waiters. No new command can register after this point.
+ cancellation.cleanup().wait().await;
+ outcome
+ }
+
+ /// Obtain a cloneable handle that cancels only this turn and awaits its
+ /// subprocess cleanup. Acquire it before moving the turn to `send()`.
+ pub fn cancellation_handle(&mut self) -> crate::TurnCancellation {
+ self.cancellation
+ .get_or_insert_with(Default::default)
+ .clone()
+ }
+
+ async fn send_inner(mut self) -> Result<TurnOutcome, CoreError> {
// The core neither mints nor returns a session id, so continuing a
// conversation would otherwise be impossible without the caller
// inventing an id scheme — which every embedder has then done
@@ -573,6 +607,7 @@ impl Turn {
crate::error::CoreError::InsecureRoute { .. } => "insecure_route",
crate::error::CoreError::InvalidRoute { .. } => "invalid_route",
crate::error::CoreError::AgentRemoved { .. } => "agent_removed",
+ crate::error::CoreError::TurnCancelled { .. } => "turn_cancelled",
};
log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");
});
diff --git a/crates/openhuman-embed/src/turn_cancellation.rs b/crates/openhuman-embed/src/turn_cancellation.rs
new file mode 100644
index 0000000000..2b8f97ccef
--- /dev/null
+++ b/crates/openhuman-embed/src/turn_cancellation.rs
@@ -0,0 +1,79 @@
+//! A cancellation request and the acknowledgement that the turn has stopped.
+
+use std::sync::Arc;
+
+use openhuman_core::tools::timeout::ProcessCleanup;
+use tokio::sync::watch;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Phase {
+ Pending,
+ Running,
+ Finished,
+}
+
+struct State {
+ requested: watch::Sender<bool>,
+ phase: watch::Sender<Phase>,
+ cleanup: ProcessCleanup,
+}
+
+/// A handle to one [`Turn`](crate::Turn), obtained before sending it.
+/// Clones address the same turn; other turns on its agent are unaffected.
+#[derive(Clone)]
+pub struct TurnCancellation(Arc<State>);
+
+impl Default for TurnCancellation {
+ fn default() -> Self {
+ Self(Arc::new(State {
+ requested: watch::Sender::new(false),
+ phase: watch::Sender::new(Phase::Pending),
+ cleanup: ProcessCleanup::default(),
+ }))
+ }
+}
+
+impl TurnCancellation {
+ /// Request cancellation and wait until the turn future has stopped and
+ /// its tracked command waiters have finished. On Unix, built-in shell,
+ /// Node, Python and npm tools kill the whole process group before reaping.
+ /// Host tools that spawn their own tasks or processes own their cleanup.
+ ///
+ /// Before send, this returns immediately and the turn is refused when
+ /// sent. Calling again, or after the turn ended, is safe. Keep polling the
+ /// send future (usually in another Tokio task) while awaiting cancellation.
+ pub async fn cancel(&self) {
+ self.0.requested.send_replace(true);
+ let mut phase = self.0.phase.subscribe();
+ if *phase.borrow_and_update() == Phase::Running {
+ let _ = phase.wait_for(|phase| *phase == Phase::Finished).await;
+ }
+ self.0.cleanup.wait().await;
+ }
+
+ pub(crate) async fn cancelled(&self) {
+ let mut requested = self.0.requested.subscribe();
+ let _ = requested.wait_for(|requested| *requested).await;
+ }
+
+ pub(crate) fn enter(&self) -> TurnGuard {
+ self.0.phase.send_replace(Phase::Running);
+ TurnGuard {
+ cancellation: self.clone(),
+ }
+ }
+
+ pub(crate) fn cleanup(&self) -> &ProcessCleanup {
+ &self.0.cleanup
+ }
+}
+
+pub(crate) struct TurnGuard {
+ cancellation: TurnCancellation,
+}
+
+impl Drop for TurnGuard {
+ fn drop(&mut self) {
+ self.cancellation.0.phase.send_replace(Phase::Finished);
+ }
+}
diff --git a/crates/openhuman-embed/tests/README.md b/crates/openhuman-embed/tests/README.md
index 400c8a6900..1c58a5bad6 100644
--- a/crates/openhuman-embed/tests/README.md
+++ b/crates/openhuman-embed/tests/README.md
@@ -37,6 +37,8 @@ recorded on the wrong server.
| [`memory_facade.rs`](memory_facade.rs) | `Runtime::memory` over TinyMemory's in-memory reference engine keeps two tenant roots apart. |
| [`saas_profiles.rs`](saas_profiles.rs) | A `ProfileRuntime` (SaaS mode, in-process): two users on thread `t1` see only their own messages and ride their own credential, a held `ProfileHandle` keeps its profile from release, a relayed Telegram message lands on the user's `channel:` thread with its `channel_outbound` reply on that user's events only, and the process refuses any other core afterwards. Inference is `common::echo_inference` behind `common::PointedTransport`. |
| [`public_api.rs`](public_api.rs) | Compile-time check that the host-facing types and signatures stay exported. |
+| [`turn_cancellation.rs`](turn_cancellation.rs) | Cancellation before send, during inference and during a builtin shell command; repeated requests and agent reuse. |
+| [`process_cancellation.rs`](process_cancellation.rs) | On Linux, dropping a command future kills its shell descendants. |
## Running
diff --git a/crates/openhuman-embed/tests/process_cancellation.rs b/crates/openhuman-embed/tests/process_cancellation.rs
new file mode 100644
index 0000000000..f353454cfa
--- /dev/null
+++ b/crates/openhuman-embed/tests/process_cancellation.rs
@@ -0,0 +1,123 @@
+//! Cancelling a tool output future must stop its shell descendants.
+
+#![cfg(target_os = "linux")]
+
+use openhuman_core::tools::timeout::{output_or_kill, output_unbounded, ProcessCleanup};
+use std::time::Duration;
+
+/// Cancelling a tool must also stop descendants of its shell.
+#[cfg(target_os = "linux")]
+#[tokio::test]
+async fn dropping_command_output_kills_the_shells_children() {
+ for bounded in [true, false] {
+ dropped_command(bounded).await;
+ }
+}
+
+async fn dropped_command(bounded: bool) {
+ let scratch = tempfile::tempdir().unwrap();
+ let pidfile = scratch.path().join("child.pid");
+ let mut cmd = openhuman_core::agent::platform_shell::build_tokio_command(&format!(
+ "sleep 30 & echo $$ $! > {}; wait",
+ pidfile.display()
+ ));
+ let cleanup = ProcessCleanup::default();
+ let mut run = Box::pin(cleanup.scope(async {
+ if bounded {
+ output_or_kill(&mut cmd, Duration::from_secs(60))
+ .await
+ .unwrap()
+ } else {
+ output_unbounded(&mut cmd).await
+ }
+ }));
+ let (shell, child): (i32, i32) = tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ tokio::select! {
+ result = &mut run => panic!("command ended before cancellation: {result:?}"),
+ _ = tokio::time::sleep(Duration::from_millis(10)) => {}
+ }
+ if let Ok(pid) = std::fs::read_to_string(&pidfile) {
+ let mut pids = pid.split_whitespace().filter_map(|pid| pid.parse().ok());
+ if let (Some(shell), Some(child)) = (pids.next(), pids.next()) {
+ break (shell, child);
+ }
+ }
+ }
+ })
+ .await
+ .unwrap();
+ drop(run);
+ tokio::time::timeout(Duration::from_secs(2), cleanup.wait())
+ .await
+ .unwrap();
+ assert!(
+ !std::path::Path::new(&format!("/proc/{shell}")).exists(),
+ "direct shell was not reaped"
+ );
+ let stopped = tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ let stat = std::fs::read_to_string(format!("/proc/{child}/stat"));
+ if stat
+ .as_ref()
+ .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
+ || stat.as_ref().is_ok_and(|s| {
+ s.rsplit_once(") ")
+ .is_some_and(|(_, rest)| rest.starts_with('Z'))
+ })
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await;
+ // Clean up even on the unfixed implementation.
+ if stopped.is_err() {
+ let _ = std::process::Command::new("kill")
+ .args(["-KILL", &child.to_string()])
+ .status();
+ }
+ assert!(
+ stopped.is_ok(),
+ "shell child {child} survived dropped output future"
+ );
+}
+
+#[tokio::test]
+async fn captured_commands_preserve_output_and_exit_status() {
+ for bounded in [true, false] {
+ let mut cmd = openhuman_core::agent::platform_shell::build_tokio_command(
+ "printf stdout; printf stderr >&2; exit 7",
+ );
+ let output = if bounded {
+ output_or_kill(&mut cmd, Duration::from_secs(5))
+ .await
+ .unwrap()
+ .unwrap()
+ } else {
+ output_unbounded(&mut cmd).await.unwrap()
+ };
+ assert_eq!(output.stdout, b"stdout");
+ assert_eq!(output.stderr, b"stderr");
+ assert_eq!(output.status.code(), Some(7));
+ }
+ let mut missing = tokio::process::Command::new("/does-not-exist/openhuman-test");
+ assert_eq!(
+ output_unbounded(&mut missing).await.unwrap_err().kind(),
+ std::io::ErrorKind::NotFound
+ );
+}
+
+#[tokio::test]
+async fn deadline_kills_and_reaps_a_command() {
+ let cleanup = ProcessCleanup::default();
+ let mut command = openhuman_core::agent::platform_shell::build_tokio_command("sleep 30");
+ assert!(cleanup
+ .scope(output_or_kill(&mut command, Duration::from_millis(30)))
+ .await
+ .is_err());
+ tokio::time::timeout(Duration::from_secs(2), cleanup.wait())
+ .await
+ .unwrap();
+}
diff --git a/crates/openhuman-embed/tests/turn_cancellation.rs b/crates/openhuman-embed/tests/turn_cancellation.rs
new file mode 100644
index 0000000000..0973411a3d
--- /dev/null
+++ b/crates/openhuman-embed/tests/turn_cancellation.rs
@@ -0,0 +1,173 @@
+//! Awaited cancellation stops one turn while leaving its agent reusable.
+
+mod common;
+
+use std::time::Duration;
+
+use common::{offline_config, provider, route, runtime, stub_backend};
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentSpec, CoreError, Runtime, ToolScopeSpec, Workspace,
+};
+
+#[test]
+fn cancellation_is_awaited_and_scoped_to_one_turn() {
+ runtime().block_on(async {
+ tokio::spawn(scenario()).await.unwrap();
+ });
+}
+
+async fn scenario() {
+ let backend = stub_backend().await;
+ let provider = provider("finished").await;
+ let runtime = Runtime::builder()
+ .config(offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .build()
+ .await
+ .unwrap();
+ let agent = runtime
+ .agent(AgentSpec::new("worker").provider(route(&provider, "test-model")))
+ .unwrap();
+
+ // Cancellation before send never reaches inference and cannot hang.
+ let mut turn = agent.turn("cancel before sending");
+ let cancel = turn.cancellation_handle();
+ tokio::time::timeout(Duration::from_secs(2), cancel.cancel())
+ .await
+ .unwrap();
+ assert!(matches!(
+ turn.send().await,
+ Err(CoreError::TurnCancelled { .. })
+ ));
+ assert!(common::chat_requests(&provider).await.is_empty());
+
+ // A later turn on the same agent remains usable.
+ let mut turn = agent.turn("answer normally");
+ let cancel = turn.cancellation_handle();
+ assert_eq!(turn.send().await.unwrap().reply, "finished");
+ tokio::time::timeout(Duration::from_secs(2), cancel.cancel())
+ .await
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(2), cancel.cancel())
+ .await
+ .unwrap();
+ // Stop an active model request while another agent remains usable.
+ let slow = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(common::chat_completion("too late"))
+ .set_delay(Duration::from_secs(30)),
+ )
+ .mount(&slow)
+ .await;
+ let blocked = runtime
+ .agent(AgentSpec::new("blocked").provider(route(&slow, "test-model")))
+ .unwrap();
+ let mut turn = blocked.turn("wait for inference");
+ let cancel = turn.cancellation_handle();
+ let sent = tokio::spawn(turn.send());
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while common::chat_requests(&slow).await.is_empty() {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .unwrap();
+ let clone = cancel.clone();
+ tokio::time::timeout(Duration::from_secs(5), async {
+ tokio::join!(cancel.cancel(), clone.cancel());
+ })
+ .await
+ .unwrap();
+ assert!(matches!(
+ sent.await.unwrap(),
+ Err(CoreError::TurnCancelled { .. })
+ ));
+ assert_eq!(agent.run("still usable").await.unwrap().reply, "finished");
+
+ // An externally dropped send future also acknowledges cancellation.
+ let mut turn = blocked.turn("drop this inference request");
+ let cancel = turn.cancellation_handle();
+ let sent = tokio::spawn(turn.send());
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while common::chat_requests(&slow).await.len() < 2 {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .unwrap();
+ sent.abort();
+ assert!(sent.await.unwrap_err().is_cancelled());
+ tokio::time::timeout(Duration::from_secs(2), cancel.cancel())
+ .await
+ .unwrap();
+
+ let mut invalid = agent
+ .turn("invalid route")
+ .route(openhuman_embed::Route::openai_compatible(
+ "https://example.invalid/v1",
+ "",
+ ));
+ let cancel = invalid.cancellation_handle();
+ assert!(matches!(
+ invalid.send().await,
+ Err(CoreError::InvalidRoute { .. })
+ ));
+ tokio::time::timeout(Duration::from_secs(2), cancel.cancel())
+ .await
+ .unwrap();
+
+ #[cfg(target_os = "linux")]
+ {
+ // Exercise the builtin shell with no tool timeout, including a
+ // grandchild. A cancel acknowledgement must follow reaping.
+ let scratch = tempfile::tempdir().unwrap();
+ let pidfile = scratch.path().join("child.pid");
+ let shell_provider = common::scripted_provider(vec![common::tool_call_completion(
+ "shell", &serde_json::json!({"command": format!("sleep 30 & echo $! > {}; wait", pidfile.display())}).to_string()
+ )], "should not finish").await;
+ let shell = runtime
+ .agent(
+ AgentSpec::new("shell-worker")
+ .provider(route(&shell_provider, "test-model"))
+ .access(Access::full())
+ .action_dir(scratch.path())
+ .definition(
+ AgentDefinitionSpec::new()
+ .tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ ),
+ )
+ .unwrap();
+ let mut turn = shell.turn("Run the shell command.");
+ let cancel = turn.cancellation_handle();
+ let sent = tokio::spawn(turn.send());
+ let child: i32 = common::eventually("running shell child", || {
+ std::fs::read_to_string(&pidfile).ok()?.trim().parse().ok()
+ })
+ .await;
+ let cancelled = tokio::time::timeout(Duration::from_secs(5), cancel.cancel()).await;
+ let live = std::fs::read_to_string(format!("/proc/{child}/stat")).is_ok_and(|s| {
+ !s.rsplit_once(") ")
+ .is_some_and(|(_, rest)| rest.starts_with('Z'))
+ });
+ // Always clean up if the regression returns.
+ if live {
+ let _ = std::process::Command::new("kill")
+ .args(["-KILL", &child.to_string()])
+ .status();
+ }
+ cancelled.unwrap();
+ assert!(!live, "shell child survived awaited cancellation");
+ assert!(matches!(
+ sent.await.unwrap(),
+ Err(CoreError::TurnCancelled { .. })
+ ));
+ assert_eq!(
+ shell.run("answer normally").await.unwrap().reply,
+ "should not finish"
+ );
+ }
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 167ad79e01..912c2b7530 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -660,6 +660,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |
| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused |
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
+| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |
## Summary