Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Shell tool: a timeout or cancelled turn stops the command and everything it started
Lin (kwant bot)abf6322d3b8e
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 7a09a1f5..d8b8dc2d 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -37,7 +37,7 @@ impl Drop for ProcessGroup {}/// Starts the CLI as the leader of its own process group, for [`ProcessGroup`].-fn own_process_group(cmd: &mut Command) {+pub(crate) fn own_process_group(cmd: &mut Command) {#[cfg(unix)]cmd.process_group(0);#[cfg(not(unix))]diff --git a/src/tools/shell.rs b/src/tools/shell.rsindex 4a9de2da..4da8945d 100644--- a/src/tools/shell.rs+++ b/src/tools/shell.rs@@ -1,7 +1,10 @@use super::ToolError;+use crate::drivers::cli::{own_process_group, ProcessGroup};use serde_json::{json, Value};use std::path::Path;+use std::process::Stdio;use std::time::Duration;+use tokio::io::AsyncReadExt;use tokio::process::Command;use tokio::time::timeout;@@ -15,21 +18,61 @@ pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, Toollet mut cmd = Command::new("bash");cmd.arg("-c").arg(command_str);cmd.current_dir(workspace);+ cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());+ // A cancelled turn drops this future; neither bash nor anything it started may outlive it+ cmd.kill_on_drop(true);+ own_process_group(&mut cmd);- let output = timeout(Duration::from_secs(timeout_secs), cmd.output())- .await- .map_err(|_| ToolError::Execution("Command execution timed out".into()))?+ let mut child = cmd+ .spawn().map_err(|e| ToolError::Execution(format!("Failed to execute shell: {}", e)))?;+ // Declared after the child, so on cancel it drops first and kills the group while bash is unreaped+ let mut group = ProcessGroup::of(&child);+ let mut stdout_pipe = child.stdout.take();+ let mut stderr_pipe = child.stderr.take();- let stdout = String::from_utf8_lossy(&output.stdout).to_string();- let stderr = String::from_utf8_lossy(&output.stderr).to_string();- let exit_code = output.status.code().unwrap_or(-1);+ let run = async {+ let mut stdout = Vec::new();+ let mut stderr = Vec::new();+ let read_out = async {+ if let Some(p) = stdout_pipe.as_mut() {+ let _ = p.read_to_end(&mut stdout).await;+ }+ };+ let read_err = async {+ if let Some(p) = stderr_pipe.as_mut() {+ let _ = p.read_to_end(&mut stderr).await;+ }+ };+ let (status, _, _) = tokio::join!(child.wait(), read_out, read_err);+ (status, stdout, stderr)+ };++ let (status, stdout, stderr) = match timeout(Duration::from_secs(timeout_secs), run).await {+ Ok(done) => done,+ Err(_) => {+ // Kill the whole group (background jobs too) before bash can be reaped and its id reused+ drop(group);+ let _ = child.kill().await;+ return Err(ToolError::Execution(format!(+ "Command timed out after {}s and was stopped, with everything it started",+ timeout_secs+ )));+ }+ };+ // Finished normally: anything it deliberately left running in the background is kept+ group.disarm();+ let status = status.map_err(|e| ToolError::Execution(format!("Failed to execute shell: {}", e)))?;++ let stdout = String::from_utf8_lossy(&stdout).to_string();+ let stderr = String::from_utf8_lossy(&stderr).to_string();+ let exit_code = status.code().unwrap_or(-1);Ok(json!({"command": command_str,"stdout": stdout,"stderr": stderr,"exit_code": exit_code,- "success": output.status.success()+ "success": status.success()}))}diff --git a/tests/shell_tool_test.rs b/tests/shell_tool_test.rsnew file mode 100644index 00000000..59f35a55--- /dev/null+++ b/tests/shell_tool_test.rs@@ -0,0 +1,58 @@+//! The shell tool stops what it started: on timeout and when its turn is cancelled.+use kwnt::tools::shell::execute_shell;+use serde_json::json;+use std::time::Duration;+use tempfile::tempdir;++#[tokio::test]+async fn a_timed_out_command_does_not_finish_later() {+ let tmp = tempdir().unwrap();+ let marker = tmp.path().join("marker");+ let args = json!({ "command": format!("sleep 3; touch {}", marker.display()), "timeout_secs": 1 });+ let err = execute_shell(tmp.path(), &args).await.unwrap_err();+ assert!(err.to_string().contains("timed out"), "{err}");+ tokio::time::sleep(Duration::from_secs(4)).await;+ assert!(!marker.exists(), "the command kept running after its timeout");+}++#[tokio::test]+async fn a_timeout_also_stops_background_jobs() {+ let tmp = tempdir().unwrap();+ let marker = tmp.path().join("grandchild");+ // A backgrounded subshell is a grandchild of the tool; it must die with bash+ let args = json!({+ "command": format!("(sleep 3; touch {}) & sleep 10", marker.display()),+ "timeout_secs": 1+ });+ assert!(execute_shell(tmp.path(), &args).await.is_err());+ tokio::time::sleep(Duration::from_secs(4)).await;+ assert!(!marker.exists(), "a background job outlived the timed-out command");+}++#[tokio::test]+async fn a_cancelled_turn_stops_the_command() {+ let tmp = tempdir().unwrap();+ let marker = tmp.path().join("cancelled");+ let args = json!({+ "command": format!("(sleep 3; touch {m}) & sleep 3; touch {m}", m = marker.display()),+ "timeout_secs": 30+ });+ let dir = tmp.path().to_path_buf();+ let task = tokio::spawn(async move { execute_shell(&dir, &args).await });+ tokio::time::sleep(Duration::from_millis(500)).await;+ task.abort();+ let _ = task.await;+ tokio::time::sleep(Duration::from_secs(4)).await;+ assert!(!marker.exists(), "the command kept running after its turn was cancelled");+}++#[tokio::test]+async fn a_finished_command_still_returns_its_output() {+ let tmp = tempdir().unwrap();+ let args = json!({ "command": "echo out; echo err >&2; exit 3" });+ let v = execute_shell(tmp.path(), &args).await.unwrap();+ assert_eq!(v["stdout"], "out\n");+ assert_eq!(v["stderr"], "err\n");+ assert_eq!(v["exit_code"], 3);+ assert_eq!(v["success"], false);+}