1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4use tokio::io::AsyncReadExt;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ShellCommand {
18 pub command: String,
20 #[serde(default = "default_timeout")]
22 pub timeout_secs: u64,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub cwd: Option<String>,
27}
28
29fn default_timeout() -> u64 {
30 30
31}
32
33impl ShellCommand {
34 fn shell_escape(value: &str) -> String {
41 let escaped = value.replace('\'', "'\\''");
44 format!("'{}'", escaped)
45 }
46
47 fn escape_for_double_quote(value: &str) -> String {
54 value
55 .replace('\\', "\\\\")
56 .replace('"', "\\\"")
57 .replace('$', "\\$")
58 .replace('`', "\\`")
59 }
60
61 pub fn render(&self, vars: &HashMap<String, String>) -> String {
79 let chars: Vec<char> = self.command.chars().collect();
80 let mut result = String::new();
81 let mut i = 0;
82 let mut in_single = false;
83 let mut in_double = false;
84
85 while i < chars.len() {
86 let c = chars[i];
87
88 if c == '\'' && !in_double {
89 in_single = !in_single;
90 result.push(c);
91 i += 1;
92 } else if c == '"' && !in_single {
93 in_double = !in_double;
94 result.push(c);
95 i += 1;
96 } else if c == '{' {
97 if let Some(end) = chars[i + 1..].iter().position(|&ch| ch == '}') {
99 let var_name: String = chars[i + 1..i + 1 + end].iter().collect();
100 if let Some(value) = vars.get(&var_name) {
101 if in_double {
102 result.push_str(&Self::escape_for_double_quote(value));
105 } else if in_single {
106 result.push('\'');
111 result.push_str(&Self::shell_escape(value));
112 result.push('\'');
113 } else {
114 result.push_str(&Self::shell_escape(value));
116 }
117 i += end + 2;
118 continue;
119 }
120 }
121 result.push(c);
123 i += 1;
124 } else {
125 result.push(c);
126 i += 1;
127 }
128 }
129
130 result
131 }
132
133 fn environment(&self, vars: &HashMap<String, String>) -> Vec<(String, String)> {
135 let mut out = Vec::with_capacity(vars.len() * 2);
136 for (key, value) in vars {
137 out.push((
138 format!("TH_{}", key.to_uppercase().replace([' ', '-'], "_")),
139 value.clone(),
140 ));
141 }
142 for (key, value) in vars {
144 out.push((key.clone(), value.clone()));
145 }
146 out
147 }
148
149 pub async fn execute(&self, vars: &HashMap<String, String>) -> Result<String, String> {
157 self.execute_with_sandbox(vars, None).await
158 }
159
160 pub async fn execute_with_sandbox(
166 &self,
167 vars: &HashMap<String, String>,
168 sandbox: Option<&crate::sandbox::Sandbox>,
169 ) -> Result<String, String> {
170 let rendered = self.render(vars);
171 let env = self.environment(vars);
172
173 let mut cmd = match (sandbox, cfg!(target_os = "windows")) {
174 (Some(sb), _) => {
175 let (program, sb_args) = sb.argv_with_env(
179 &rendered,
180 self.cwd.as_deref().map(std::path::Path::new),
181 &env,
182 );
183 let mut c = tokio::process::Command::new(program);
184 c.args(sb_args);
185 c
186 }
187 (None, true) => {
188 let mut c = tokio::process::Command::new("cmd");
189 c.arg("/C").arg(&rendered);
190 c
191 }
192 (None, false) => {
193 let mut c = tokio::process::Command::new("sh");
194 c.arg("-c").arg(&rendered);
195 c
196 }
197 };
198
199 for (key, value) in &env {
204 cmd.env(key, value);
205 }
206
207 if let Some(ref cwd) = self.cwd {
212 cmd.current_dir(cwd);
213 }
214
215 #[cfg(unix)]
216 cmd.process_group(0);
217
218 let mut child = cmd
219 .stdin(std::process::Stdio::null())
220 .stdout(std::process::Stdio::piped())
221 .stderr(std::process::Stdio::piped())
222 .spawn()
223 .map_err(|e| format!("Failed to spawn command: {}", e))?;
224
225 let timeout = tokio::time::Duration::from_secs(self.timeout_secs);
226 let wait_result = tokio::time::timeout(timeout, child.wait()).await;
227
228 match wait_result {
229 Ok(Ok(status)) => {
230 let stdout = read_pipe(child.stdout.take()).await;
231 let stderr = read_pipe(child.stderr.take()).await;
232
233 if status.success() {
234 Ok(stdout.trim().to_string())
235 } else {
236 let mut msg =
237 format!("Command exited with code {}", status.code().unwrap_or(-1));
238 if !stderr.is_empty() {
239 msg.push_str(&format!("\n{}", stderr.trim()));
240 }
241 if !stdout.is_empty() {
242 msg.push_str(&format!("\n{}", stdout.trim()));
243 }
244 Err(msg)
245 }
246 }
247 Ok(Err(e)) => {
248 crate::tools::run::kill_child(child).await;
249 Err(format!("Failed to wait for command: {}", e))
250 }
251 Err(_) => {
252 crate::tools::run::kill_child(child).await;
253 Err(format!(
254 "Command timed out after {}s: {}",
255 self.timeout_secs, rendered
256 ))
257 }
258 }
259 }
260}
261
262async fn read_pipe<T: tokio::io::AsyncRead + Unpin>(mut pipe: Option<T>) -> String {
264 if let Some(ref mut r) = pipe.as_mut() {
265 let mut buf = String::new();
266 let _ = r.read_to_string(&mut buf).await;
267 buf
268 } else {
269 String::new()
270 }
271}
272
273pub async fn execute_shell_tool(command: &ShellCommand, args: &HashMap<String, String>) -> String {
278 execute_shell_tool_with_sandbox(command, args, None).await
279}
280
281pub async fn execute_shell_tool_with_sandbox(
283 command: &ShellCommand,
284 args: &HashMap<String, String>,
285 sandbox: Option<&crate::sandbox::Sandbox>,
286) -> String {
287 match command.execute_with_sandbox(args, sandbox).await {
288 Ok(stdout) => {
289 if stdout.is_empty() {
290 "(no output)".to_string()
291 } else {
292 stdout
293 }
294 }
295 Err(e) => format!("Error: {}", e),
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 #[test]
304 fn test_render_basic_substitution() {
305 let cmd = ShellCommand {
306 command: "echo {name}".to_string(),
307 timeout_secs: 5,
308 cwd: None,
309 };
310 let mut vars = HashMap::new();
311 vars.insert("name".to_string(), "world".to_string());
312 assert_eq!(cmd.render(&vars), "echo 'world'");
314 }
315
316 #[test]
317 fn test_render_multiple_vars() {
318 let cmd = ShellCommand {
319 command: "docker run --rm {image} sh -c {command}".to_string(),
320 timeout_secs: 30,
321 cwd: None,
322 };
323 let mut vars = HashMap::new();
324 vars.insert("image".to_string(), "ubuntu:latest".to_string());
325 vars.insert("command".to_string(), "ls -la".to_string());
326 assert_eq!(
328 cmd.render(&vars),
329 "docker run --rm 'ubuntu:latest' sh -c 'ls -la'"
330 );
331 }
332
333 #[test]
334 fn test_render_shell_escapes_single_quotes() {
335 let cmd = ShellCommand {
336 command: "echo {text}".to_string(),
337 timeout_secs: 5,
338 cwd: None,
339 };
340 let mut vars = HashMap::new();
341 vars.insert("text".to_string(), "I'll do it".to_string());
342 assert_eq!(cmd.render(&vars), "echo 'I'\\''ll do it'");
344 }
345
346 #[test]
347 fn test_render_shell_escapes_metacharacters() {
348 let cmd = ShellCommand {
349 command: "echo -n {response} | wc -c".to_string(),
350 timeout_secs: 5,
351 cwd: None,
352 };
353 let mut vars = HashMap::new();
354 vars.insert(
355 "response".to_string(),
356 "I'll find all files in `./src` and run $(whoami)".to_string(),
357 );
358 let rendered = cmd.render(&vars);
359 assert_eq!(
361 rendered,
362 "echo -n 'I'\\''ll find all files in `./src` and run $(whoami)' | wc -c"
363 );
364 }
365
366 #[test]
367 fn test_render_inside_double_quotes() {
368 let cmd = ShellCommand {
369 command: "echo \"{text}\"".to_string(),
370 timeout_secs: 5,
371 cwd: None,
372 };
373 let mut vars = HashMap::new();
374 vars.insert("text".to_string(), "He said \"hi\" and $HOME".to_string());
375 let rendered = cmd.render(&vars);
377 assert_eq!(rendered, "echo \"He said \\\"hi\\\" and \\$HOME\"");
378 }
379
380 #[test]
381 fn test_render_inside_double_quotes_backtick() {
382 let cmd = ShellCommand {
383 command: "echo \"{text}\"".to_string(),
384 timeout_secs: 5,
385 cwd: None,
386 };
387 let mut vars = HashMap::new();
388 vars.insert("text".to_string(), "run `whoami`".to_string());
389 let rendered = cmd.render(&vars);
390 assert_eq!(rendered, "echo \"run \\`whoami\\`\"");
391 }
392
393 #[test]
394 fn test_render_inside_double_quotes_simple() {
395 let cmd = ShellCommand {
396 command: "echo \"{name}\"".to_string(),
397 timeout_secs: 5,
398 cwd: None,
399 };
400 let mut vars = HashMap::new();
401 vars.insert("name".to_string(), "world".to_string());
402 let rendered = cmd.render(&vars);
404 assert_eq!(rendered, "echo \"world\"");
405 }
406
407 #[test]
408 fn test_render_inside_single_quotes() {
409 let cmd = ShellCommand {
410 command: "echo '{text}'".to_string(),
411 timeout_secs: 5,
412 cwd: None,
413 };
414 let mut vars = HashMap::new();
415 vars.insert("text".to_string(), "it's here".to_string());
416 let rendered = cmd.render(&vars);
417 assert_eq!(rendered, "echo '''it'\\''s here'''");
418 }
419
420 #[test]
421 fn test_render_inside_single_quotes_simple() {
422 let cmd = ShellCommand {
423 command: "echo '{name}'".to_string(),
424 timeout_secs: 5,
425 cwd: None,
426 };
427 let mut vars = HashMap::new();
428 vars.insert("name".to_string(), "world".to_string());
429 let rendered = cmd.render(&vars);
430 assert_eq!(rendered, "echo '''world'''");
431 }
432
433 #[test]
434 fn test_render_mixed_quotes_multiple_vars() {
435 let cmd = ShellCommand {
436 command: "echo \"{greeting}\" '{name}'".to_string(),
437 timeout_secs: 5,
438 cwd: None,
439 };
440 let mut vars = HashMap::new();
441 vars.insert("greeting".to_string(), "hello $USER".to_string());
442 vars.insert("name".to_string(), "world".to_string());
443 let rendered = cmd.render(&vars);
444 assert_eq!(rendered, "echo \"hello \\$USER\" '''world'''");
445 }
446
447 #[test]
448 fn test_render_nested_brace_not_var() {
449 let cmd = ShellCommand {
450 command: "echo {not_a_var}".to_string(),
451 timeout_secs: 5,
452 cwd: None,
453 };
454 let vars = HashMap::new();
455 assert_eq!(cmd.render(&vars), "echo {not_a_var}");
457 }
458
459 #[test]
460 fn test_render_unclosed_brace() {
461 let cmd = ShellCommand {
462 command: "echo {name".to_string(),
463 timeout_secs: 5,
464 cwd: None,
465 };
466 let mut vars = HashMap::new();
467 vars.insert("name".to_string(), "world".to_string());
468 assert_eq!(cmd.render(&vars), "echo {name");
470 }
471
472 #[test]
473 fn test_render_missing_var_stays_as_placeholder() {
474 let cmd = ShellCommand {
475 command: "echo {missing}".to_string(),
476 timeout_secs: 5,
477 cwd: None,
478 };
479 let vars = HashMap::new();
480 assert_eq!(cmd.render(&vars), "echo {missing}");
482 }
483
484 #[test]
485 fn test_render_no_vars() {
486 let cmd = ShellCommand {
487 command: "git status".to_string(),
488 timeout_secs: 5,
489 cwd: None,
490 };
491 let vars = HashMap::new();
492 assert_eq!(cmd.render(&vars), "git status");
493 }
494
495 #[test]
496 fn test_default_timeout() {
497 assert_eq!(default_timeout(), 30);
498 }
499
500 #[test]
501 fn test_shell_command_serde() {
502 let json = r#"{"command": "echo hi", "timeout_secs": 10}"#;
503 let cmd: ShellCommand = serde_json::from_str(json).unwrap();
504 assert_eq!(cmd.command, "echo hi");
505 assert_eq!(cmd.timeout_secs, 10);
506 assert!(cmd.cwd.is_none());
507 }
508
509 #[test]
510 fn test_shell_command_serde_default_timeout() {
511 let json = r#"{"command": "echo hi"}"#;
512 let cmd: ShellCommand = serde_json::from_str(json).unwrap();
513 assert_eq!(cmd.timeout_secs, 30);
514 }
515
516 #[test]
517 fn test_shell_command_serde_with_cwd() {
518 let json = r#"{"command": "ls", "timeout_secs": 5, "cwd": "/tmp"}"#;
519 let cmd: ShellCommand = serde_json::from_str(json).unwrap();
520 assert_eq!(cmd.cwd.as_deref(), Some("/tmp"));
521 }
522
523 #[tokio::test]
524 async fn test_execute_success() {
525 let cmd = ShellCommand {
526 command: "echo hello".to_string(),
527 timeout_secs: 5,
528 cwd: None,
529 };
530 let vars = HashMap::new();
531 let result = cmd.execute(&vars).await;
532 assert!(result.is_ok());
533 assert_eq!(result.unwrap(), "hello");
534 }
535
536 #[tokio::test]
537 async fn test_execute_with_substitution() {
538 let expected = if cfg!(target_os = "windows") {
541 "'world'"
542 } else {
543 "world"
544 };
545 let cmd = ShellCommand {
546 command: "echo {name}".to_string(),
547 timeout_secs: 5,
548 cwd: None,
549 };
550 let mut vars = HashMap::new();
551 vars.insert("name".to_string(), "world".to_string());
552 let result = cmd.execute(&vars).await;
553 assert!(result.is_ok());
554 assert_eq!(result.unwrap(), expected);
555 }
556
557 #[tokio::test]
558 async fn test_execute_failure() {
559 let cmd = ShellCommand {
560 command: "exit 1".to_string(),
561 timeout_secs: 5,
562 cwd: None,
563 };
564 let vars = HashMap::new();
565 let result = cmd.execute(&vars).await;
566 assert!(result.is_err());
567 assert!(result.unwrap_err().contains("exited with code 1"));
568 }
569
570 #[tokio::test]
571 async fn test_execute_timeout() {
572 let cmd = ShellCommand {
574 command: (if cfg!(target_os = "windows") {
575 "ping -n 100 127.0.0.1 > NUL"
576 } else {
577 "sleep 100"
578 })
579 .to_string(),
580 timeout_secs: 1,
581 cwd: None,
582 };
583 let vars = HashMap::new();
584 let result = cmd.execute(&vars).await;
585 assert!(result.is_err());
586 assert!(
587 result.unwrap_err().contains("timed out"),
588 "expected 'timed out' in error"
589 );
590 }
591
592 #[tokio::test]
593 async fn test_execute_env_var_available() {
594 let cmd = ShellCommand {
595 command: (if cfg!(target_os = "windows") {
596 "echo %TH_NAME%"
597 } else {
598 "echo $TH_NAME"
599 })
600 .to_string(),
601 timeout_secs: 5,
602 cwd: None,
603 };
604 let mut vars = HashMap::new();
605 vars.insert("name".to_string(), "from_env".to_string());
606 let result = cmd.execute(&vars).await;
607 assert!(result.is_ok());
608 assert_eq!(result.unwrap(), "from_env");
609 }
610
611 #[tokio::test]
612 async fn test_execute_cwd() {
613 let tmp = std::env::temp_dir();
614 let cmd = ShellCommand {
615 command: (if cfg!(target_os = "windows") {
616 "cd"
617 } else {
618 "pwd"
619 })
620 .to_string(),
621 timeout_secs: 5,
622 cwd: Some(tmp.to_string_lossy().to_string()),
623 };
624 let vars = HashMap::new();
625 let result = cmd.execute(&vars).await;
626 assert!(result.is_ok());
627 let expected = std::fs::canonicalize(&tmp)
628 .unwrap_or_else(|_| tmp.clone())
629 .to_string_lossy()
630 .to_string();
631 let actual = result.unwrap();
632 if cfg!(target_os = "windows") {
633 let actual_canon = std::fs::canonicalize(&actual)
634 .or_else(|_| std::path::Path::new(&actual).canonicalize())
635 .map(|p| p.to_string_lossy().to_string())
636 .unwrap_or(actual);
637 let expected_canon = std::fs::canonicalize(&expected)
638 .map(|p| p.to_string_lossy().to_string())
639 .unwrap_or(expected);
640 assert_eq!(actual_canon.to_lowercase(), expected_canon.to_lowercase());
641 } else {
642 assert_eq!(actual, expected);
643 }
644 }
645
646 #[tokio::test]
647 async fn test_execute_shell_tool_success() {
648 let expected = if cfg!(target_os = "windows") {
649 "hello 'world'"
650 } else {
651 "hello world"
652 };
653 let cmd = ShellCommand {
654 command: "echo hello {name}".to_string(),
655 timeout_secs: 5,
656 cwd: None,
657 };
658 let mut args = HashMap::new();
659 args.insert("name".to_string(), "world".to_string());
660 let result = execute_shell_tool(&cmd, &args).await;
661 assert_eq!(result, expected);
662 }
663
664 #[tokio::test]
665 async fn test_execute_shell_tool_error() {
666 let cmd = ShellCommand {
667 command: "exit 42".to_string(),
668 timeout_secs: 5,
669 cwd: None,
670 };
671 let args = HashMap::new();
672 let result = execute_shell_tool(&cmd, &args).await;
673 assert!(result.starts_with("Error:"));
674 }
675
676 #[tokio::test]
677 async fn test_execute_shell_tool_empty_output() {
678 let cmd = ShellCommand {
682 command: "exit 0".to_string(),
683 timeout_secs: 5,
684 cwd: None,
685 };
686 let args = HashMap::new();
687 let result = execute_shell_tool(&cmd, &args).await;
688 assert_eq!(result, "(no output)");
689 }
690
691 #[tokio::test]
692 async fn test_execute_double_quoted_var_with_special_chars() {
693 let cmd = ShellCommand {
694 command: "echo \"{text}\"".to_string(),
695 timeout_secs: 5,
696 cwd: None,
697 };
698 let mut vars = HashMap::new();
699 vars.insert("text".to_string(), "He said \"hi\" and $FOO".to_string());
700 let result = cmd.execute(&vars).await;
701 assert!(result.is_ok());
702 if cfg!(target_os = "windows") {
703 } else {
706 assert_eq!(result.unwrap(), "He said \"hi\" and $FOO");
707 }
708 }
709
710 #[tokio::test]
711 async fn test_execute_single_quoted_var_with_single_quote() {
712 let cmd = ShellCommand {
713 command: "echo '{text}'".to_string(),
714 timeout_secs: 5,
715 cwd: None,
716 };
717 let mut vars = HashMap::new();
718 vars.insert("text".to_string(), "it's here".to_string());
719 let result = cmd.execute(&vars).await;
720 assert!(result.is_ok());
721 if cfg!(target_os = "windows") {
722 } else {
724 assert_eq!(result.unwrap(), "it's here");
725 }
726 }
727
728 #[tokio::test]
729 async fn test_execute_unquoted_var_with_single_quote() {
730 let cmd = ShellCommand {
731 command: "echo {text}".to_string(),
732 timeout_secs: 5,
733 cwd: None,
734 };
735 let mut vars = HashMap::new();
736 vars.insert("text".to_string(), "it's here".to_string());
737 let result = cmd.execute(&vars).await;
738 assert!(result.is_ok());
739 if cfg!(target_os = "windows") {
740 } else {
742 assert_eq!(result.unwrap(), "it's here");
743 }
744 }
745}