use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use tokio::io::AsyncReadExt;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellCommand {
pub command: String,
#[serde(default = "default_timeout")]
pub timeout_secs: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
}
fn default_timeout() -> u64 {
30
}
impl ShellCommand {
fn shell_escape(value: &str) -> String {
let escaped = value.replace('\'', "'\\''");
format!("'{}'", escaped)
}
fn escape_for_double_quote(value: &str) -> String {
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('$', "\\$")
.replace('`', "\\`")
}
pub fn render(&self, vars: &HashMap<String, String>) -> String {
let chars: Vec<char> = self.command.chars().collect();
let mut result = String::new();
let mut i = 0;
let mut in_single = false;
let mut in_double = false;
while i < chars.len() {
let c = chars[i];
if c == '\'' && !in_double {
in_single = !in_single;
result.push(c);
i += 1;
} else if c == '"' && !in_single {
in_double = !in_double;
result.push(c);
i += 1;
} else if c == '{' {
if let Some(end) = chars[i + 1..].iter().position(|&ch| ch == '}') {
let var_name: String = chars[i + 1..i + 1 + end].iter().collect();
if let Some(value) = vars.get(&var_name) {
if in_double {
result.push_str(&Self::escape_for_double_quote(value));
} else if in_single {
result.push('\'');
result.push_str(&Self::shell_escape(value));
result.push('\'');
} else {
result.push_str(&Self::shell_escape(value));
}
i += end + 2;
continue;
}
}
result.push(c);
i += 1;
} else {
result.push(c);
i += 1;
}
}
result
}
fn environment(&self, vars: &HashMap<String, String>) -> Vec<(String, String)> {
let mut out = Vec::with_capacity(vars.len() * 2);
for (key, value) in vars {
out.push((
format!("TH_{}", key.to_uppercase().replace([' ', '-'], "_")),
value.clone(),
));
}
for (key, value) in vars {
out.push((key.clone(), value.clone()));
}
out
}
pub async fn execute(&self, vars: &HashMap<String, String>) -> Result<String, String> {
self.execute_with_sandbox(vars, None).await
}
pub async fn execute_with_sandbox(
&self,
vars: &HashMap<String, String>,
sandbox: Option<&crate::sandbox::Sandbox>,
) -> Result<String, String> {
let rendered = self.render(vars);
let env = self.environment(vars);
let mut cmd = match (sandbox, cfg!(target_os = "windows")) {
(Some(sb), _) => {
let (program, sb_args) = sb.argv_with_env(
&rendered,
self.cwd.as_deref().map(std::path::Path::new),
&env,
);
let mut c = tokio::process::Command::new(program);
c.args(sb_args);
c
}
(None, true) => {
let mut c = tokio::process::Command::new("cmd");
c.arg("/C").arg(&rendered);
c
}
(None, false) => {
let mut c = tokio::process::Command::new("sh");
c.arg("-c").arg(&rendered);
c
}
};
for (key, value) in &env {
cmd.env(key, value);
}
if let Some(ref cwd) = self.cwd {
cmd.current_dir(cwd);
}
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to spawn command: {}", e))?;
let timeout = tokio::time::Duration::from_secs(self.timeout_secs);
let wait_result = tokio::time::timeout(timeout, child.wait()).await;
match wait_result {
Ok(Ok(status)) => {
let stdout = read_pipe(child.stdout.take()).await;
let stderr = read_pipe(child.stderr.take()).await;
if status.success() {
Ok(stdout.trim().to_string())
} else {
let mut msg =
format!("Command exited with code {}", status.code().unwrap_or(-1));
if !stderr.is_empty() {
msg.push_str(&format!("\n{}", stderr.trim()));
}
if !stdout.is_empty() {
msg.push_str(&format!("\n{}", stdout.trim()));
}
Err(msg)
}
}
Ok(Err(e)) => {
crate::tools::run::kill_child(child).await;
Err(format!("Failed to wait for command: {}", e))
}
Err(_) => {
crate::tools::run::kill_child(child).await;
Err(format!(
"Command timed out after {}s: {}",
self.timeout_secs, rendered
))
}
}
}
}
async fn read_pipe<T: tokio::io::AsyncRead + Unpin>(mut pipe: Option<T>) -> String {
if let Some(ref mut r) = pipe.as_mut() {
let mut buf = String::new();
let _ = r.read_to_string(&mut buf).await;
buf
} else {
String::new()
}
}
pub async fn execute_shell_tool(command: &ShellCommand, args: &HashMap<String, String>) -> String {
execute_shell_tool_with_sandbox(command, args, None).await
}
pub async fn execute_shell_tool_with_sandbox(
command: &ShellCommand,
args: &HashMap<String, String>,
sandbox: Option<&crate::sandbox::Sandbox>,
) -> String {
match command.execute_with_sandbox(args, sandbox).await {
Ok(stdout) => {
if stdout.is_empty() {
"(no output)".to_string()
} else {
stdout
}
}
Err(e) => format!("Error: {}", e),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_render_basic_substitution() {
let cmd = ShellCommand {
command: "echo {name}".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "world".to_string());
assert_eq!(cmd.render(&vars), "echo 'world'");
}
#[test]
fn test_render_multiple_vars() {
let cmd = ShellCommand {
command: "docker run --rm {image} sh -c {command}".to_string(),
timeout_secs: 30,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("image".to_string(), "ubuntu:latest".to_string());
vars.insert("command".to_string(), "ls -la".to_string());
assert_eq!(
cmd.render(&vars),
"docker run --rm 'ubuntu:latest' sh -c 'ls -la'"
);
}
#[test]
fn test_render_shell_escapes_single_quotes() {
let cmd = ShellCommand {
command: "echo {text}".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "I'll do it".to_string());
assert_eq!(cmd.render(&vars), "echo 'I'\\''ll do it'");
}
#[test]
fn test_render_shell_escapes_metacharacters() {
let cmd = ShellCommand {
command: "echo -n {response} | wc -c".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert(
"response".to_string(),
"I'll find all files in `./src` and run $(whoami)".to_string(),
);
let rendered = cmd.render(&vars);
assert_eq!(
rendered,
"echo -n 'I'\\''ll find all files in `./src` and run $(whoami)' | wc -c"
);
}
#[test]
fn test_render_inside_double_quotes() {
let cmd = ShellCommand {
command: "echo \"{text}\"".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "He said \"hi\" and $HOME".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo \"He said \\\"hi\\\" and \\$HOME\"");
}
#[test]
fn test_render_inside_double_quotes_backtick() {
let cmd = ShellCommand {
command: "echo \"{text}\"".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "run `whoami`".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo \"run \\`whoami\\`\"");
}
#[test]
fn test_render_inside_double_quotes_simple() {
let cmd = ShellCommand {
command: "echo \"{name}\"".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "world".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo \"world\"");
}
#[test]
fn test_render_inside_single_quotes() {
let cmd = ShellCommand {
command: "echo '{text}'".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "it's here".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo '''it'\\''s here'''");
}
#[test]
fn test_render_inside_single_quotes_simple() {
let cmd = ShellCommand {
command: "echo '{name}'".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "world".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo '''world'''");
}
#[test]
fn test_render_mixed_quotes_multiple_vars() {
let cmd = ShellCommand {
command: "echo \"{greeting}\" '{name}'".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("greeting".to_string(), "hello $USER".to_string());
vars.insert("name".to_string(), "world".to_string());
let rendered = cmd.render(&vars);
assert_eq!(rendered, "echo \"hello \\$USER\" '''world'''");
}
#[test]
fn test_render_nested_brace_not_var() {
let cmd = ShellCommand {
command: "echo {not_a_var}".to_string(),
timeout_secs: 5,
cwd: None,
};
let vars = HashMap::new();
assert_eq!(cmd.render(&vars), "echo {not_a_var}");
}
#[test]
fn test_render_unclosed_brace() {
let cmd = ShellCommand {
command: "echo {name".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "world".to_string());
assert_eq!(cmd.render(&vars), "echo {name");
}
#[test]
fn test_render_missing_var_stays_as_placeholder() {
let cmd = ShellCommand {
command: "echo {missing}".to_string(),
timeout_secs: 5,
cwd: None,
};
let vars = HashMap::new();
assert_eq!(cmd.render(&vars), "echo {missing}");
}
#[test]
fn test_render_no_vars() {
let cmd = ShellCommand {
command: "git status".to_string(),
timeout_secs: 5,
cwd: None,
};
let vars = HashMap::new();
assert_eq!(cmd.render(&vars), "git status");
}
#[test]
fn test_default_timeout() {
assert_eq!(default_timeout(), 30);
}
#[test]
fn test_shell_command_serde() {
let json = r#"{"command": "echo hi", "timeout_secs": 10}"#;
let cmd: ShellCommand = serde_json::from_str(json).unwrap();
assert_eq!(cmd.command, "echo hi");
assert_eq!(cmd.timeout_secs, 10);
assert!(cmd.cwd.is_none());
}
#[test]
fn test_shell_command_serde_default_timeout() {
let json = r#"{"command": "echo hi"}"#;
let cmd: ShellCommand = serde_json::from_str(json).unwrap();
assert_eq!(cmd.timeout_secs, 30);
}
#[test]
fn test_shell_command_serde_with_cwd() {
let json = r#"{"command": "ls", "timeout_secs": 5, "cwd": "/tmp"}"#;
let cmd: ShellCommand = serde_json::from_str(json).unwrap();
assert_eq!(cmd.cwd.as_deref(), Some("/tmp"));
}
#[tokio::test]
async fn test_execute_success() {
let cmd = ShellCommand {
command: "echo hello".to_string(),
timeout_secs: 5,
cwd: None,
};
let vars = HashMap::new();
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), "hello");
}
#[tokio::test]
async fn test_execute_with_substitution() {
let expected = if cfg!(target_os = "windows") {
"'world'"
} else {
"world"
};
let cmd = ShellCommand {
command: "echo {name}".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "world".to_string());
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected);
}
#[tokio::test]
async fn test_execute_failure() {
let cmd = ShellCommand {
command: "exit 1".to_string(),
timeout_secs: 5,
cwd: None,
};
let vars = HashMap::new();
let result = cmd.execute(&vars).await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("exited with code 1"));
}
#[tokio::test]
async fn test_execute_timeout() {
let cmd = ShellCommand {
command: (if cfg!(target_os = "windows") {
"ping -n 100 127.0.0.1 > NUL"
} else {
"sleep 100"
})
.to_string(),
timeout_secs: 1,
cwd: None,
};
let vars = HashMap::new();
let result = cmd.execute(&vars).await;
assert!(result.is_err());
assert!(
result.unwrap_err().contains("timed out"),
"expected 'timed out' in error"
);
}
#[tokio::test]
async fn test_execute_env_var_available() {
let cmd = ShellCommand {
command: (if cfg!(target_os = "windows") {
"echo %TH_NAME%"
} else {
"echo $TH_NAME"
})
.to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("name".to_string(), "from_env".to_string());
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), "from_env");
}
#[tokio::test]
async fn test_execute_cwd() {
let tmp = std::env::temp_dir();
let cmd = ShellCommand {
command: (if cfg!(target_os = "windows") {
"cd"
} else {
"pwd"
})
.to_string(),
timeout_secs: 5,
cwd: Some(tmp.to_string_lossy().to_string()),
};
let vars = HashMap::new();
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
let expected = std::fs::canonicalize(&tmp)
.unwrap_or_else(|_| tmp.clone())
.to_string_lossy()
.to_string();
let actual = result.unwrap();
if cfg!(target_os = "windows") {
let actual_canon = std::fs::canonicalize(&actual)
.or_else(|_| std::path::Path::new(&actual).canonicalize())
.map(|p| p.to_string_lossy().to_string())
.unwrap_or(actual);
let expected_canon = std::fs::canonicalize(&expected)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or(expected);
assert_eq!(actual_canon.to_lowercase(), expected_canon.to_lowercase());
} else {
assert_eq!(actual, expected);
}
}
#[tokio::test]
async fn test_execute_shell_tool_success() {
let expected = if cfg!(target_os = "windows") {
"hello 'world'"
} else {
"hello world"
};
let cmd = ShellCommand {
command: "echo hello {name}".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut args = HashMap::new();
args.insert("name".to_string(), "world".to_string());
let result = execute_shell_tool(&cmd, &args).await;
assert_eq!(result, expected);
}
#[tokio::test]
async fn test_execute_shell_tool_error() {
let cmd = ShellCommand {
command: "exit 42".to_string(),
timeout_secs: 5,
cwd: None,
};
let args = HashMap::new();
let result = execute_shell_tool(&cmd, &args).await;
assert!(result.starts_with("Error:"));
}
#[tokio::test]
async fn test_execute_shell_tool_empty_output() {
let cmd = ShellCommand {
command: "exit 0".to_string(),
timeout_secs: 5,
cwd: None,
};
let args = HashMap::new();
let result = execute_shell_tool(&cmd, &args).await;
assert_eq!(result, "(no output)");
}
#[tokio::test]
async fn test_execute_double_quoted_var_with_special_chars() {
let cmd = ShellCommand {
command: "echo \"{text}\"".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "He said \"hi\" and $FOO".to_string());
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
if cfg!(target_os = "windows") {
} else {
assert_eq!(result.unwrap(), "He said \"hi\" and $FOO");
}
}
#[tokio::test]
async fn test_execute_single_quoted_var_with_single_quote() {
let cmd = ShellCommand {
command: "echo '{text}'".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "it's here".to_string());
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
if cfg!(target_os = "windows") {
} else {
assert_eq!(result.unwrap(), "it's here");
}
}
#[tokio::test]
async fn test_execute_unquoted_var_with_single_quote() {
let cmd = ShellCommand {
command: "echo {text}".to_string(),
timeout_secs: 5,
cwd: None,
};
let mut vars = HashMap::new();
vars.insert("text".to_string(), "it's here".to_string());
let result = cmd.execute(&vars).await;
assert!(result.is_ok());
if cfg!(target_os = "windows") {
} else {
assert_eq!(result.unwrap(), "it's here");
}
}
}