1use anyhow::Result;
18use base64::Engine as _;
19use base64::engine::general_purpose::URL_SAFE_NO_PAD;
20use serde::Deserialize;
21use serde_json::{json, Value};
22use std::io::{Read, Write};
23
24#[derive(Deserialize)]
27struct PreToolUseInput {
28 tool_name: String,
29 #[serde(default)]
30 tool_use_id: String,
31 #[serde(default)]
32 session_id: String,
33 #[serde(default)]
34 tool_input: Value,
35 #[serde(default)]
38 agent_id: Option<String>,
39}
40
41const WRAPPER_BINARY: &str = "agentmux-bashwrap";
42const WRAPPED_PREFIX: &str = "agentmux-bashwrap exec";
43
44pub fn run_pretooluse_bash() -> Result<()> {
45 let mut buf = String::new();
47 std::io::stdin().read_to_string(&mut buf)?;
48
49 let response = if crate::prefix::prefix_active() {
54 record_response(&buf)
55 } else {
56 build_response(&buf)
57 };
58 let stdout = std::io::stdout();
59 let mut handle = stdout.lock();
60 writeln!(handle, "{}", response)?;
61 Ok(())
62}
63
64pub fn build_response(stdin_payload: &str) -> Value {
68 let input: PreToolUseInput = match serde_json::from_str(stdin_payload) {
69 Ok(i) => i,
70 Err(_) => {
71 return passthrough();
74 }
75 };
76
77 if input.tool_name != "Bash" {
78 return passthrough();
79 }
80
81 let command = input
82 .tool_input
83 .get("command")
84 .and_then(|v| v.as_str())
85 .unwrap_or("");
86
87 if command.starts_with(WRAPPED_PREFIX) {
90 return passthrough();
91 }
92
93 let effective_command =
99 tee_redirect_rewrite(command).unwrap_or_else(|| command.to_string());
100
101 let declared_background = input
110 .tool_input
111 .get("run_in_background")
112 .and_then(|v| v.as_bool())
113 .unwrap_or(false);
114
115 let b64 = URL_SAFE_NO_PAD.encode(effective_command.as_bytes());
116 let agent = input
117 .agent_id
118 .as_deref()
119 .map(str::trim)
120 .filter(|a| !a.is_empty())
121 .map(|a| format!(" --agent={}", shell_quote(a)))
122 .unwrap_or_default();
123 let wrapped = format!(
124 "{} exec --tool-id={} --b64-cmd={}{}{}",
125 WRAPPER_BINARY,
126 shell_quote(&input.tool_use_id),
127 b64,
128 if declared_background { " --declared-background" } else { "" },
129 agent
130 );
131
132 let mut updated = match input.tool_input {
140 Value::Object(fields) => fields,
141 _ => serde_json::Map::new(),
142 };
143 updated.insert("command".to_string(), Value::String(wrapped));
144
145 json!({
146 "hookSpecificOutput": {
147 "hookEventName": "PreToolUse",
148 "permissionDecision": "allow",
149 "updatedInput": updated
150 }
151 })
152}
153
154pub fn record_response(stdin_payload: &str) -> Value {
163 let Ok(input) = serde_json::from_str::<PreToolUseInput>(stdin_payload) else {
164 return passthrough();
165 };
166 let command = input.tool_input.get("command").and_then(|v| v.as_str()).unwrap_or("");
167 let usable = input.tool_name == "Bash"
168 && !input.tool_use_id.is_empty()
169 && !input.session_id.is_empty()
170 && !command.starts_with(WRAPPED_PREFIX);
171 if usable {
172 let background = input.tool_input.get("run_in_background").and_then(|v| v.as_bool()).unwrap_or(false);
173 let mut record = crate::prefix::new_record(&input.tool_use_id, command, background);
174 record.description = input
175 .tool_input
176 .get("description")
177 .and_then(|v| v.as_str())
178 .map(str::trim)
179 .filter(|d| !d.is_empty())
180 .map(str::to_string);
181 record.agent_id = input.agent_id.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
182 if let Err(e) = crate::prefix::register(&input.session_id, &record) {
183 tracing::warn!(target: "bashwrap", tool_id = %input.tool_use_id, error = %e, "couldn't record the Bash call; it runs unstreamed");
184 }
185 }
186 crate::bash_timeout::response_from_env(&input.tool_input).unwrap_or_else(passthrough)
189}
190
191fn passthrough() -> Value {
192 json!({})
194}
195
196#[derive(Clone, Copy)]
225enum OutKind {
226 Out,
227 Append,
228 AmpOut,
229 AmpAppend,
230}
231
232struct ScanResult {
233 redir_start: usize,
234 target_start: usize,
235 target_end: usize,
236 append: bool,
237 combine_stderr: bool,
238}
239
240pub(crate) fn tee_redirect_rewrite(raw: &str) -> Option<String> {
243 let cmd = raw.trim();
244 if cmd.is_empty() {
245 return None;
246 }
247 let scan = scan_redirect(cmd)?;
248 let cmd_part = cmd[..scan.redir_start].trim();
249 if cmd_part.is_empty() {
250 return None;
251 }
252 let target = cmd[scan.target_start..scan.target_end].trim();
253 if target.is_empty() || is_dev_null(target) {
254 return None;
255 }
256 let aflag = if scan.append { "-a " } else { "" };
257 let stream = if scan.combine_stderr { " 2>&1 |" } else { " |" };
258 Some(format!(
259 "set -o pipefail; {{ {} ; }}{} tee {}-- {}",
260 cmd_part, stream, aflag, target
261 ))
262}
263
264fn is_space(c: u8) -> bool {
265 c == b' ' || c == b'\t' || c == b'\n' || c == b'\r'
266}
267
268fn is_dev_null(target: &str) -> bool {
270 let t = target.trim();
271 let unq = if (t.starts_with('"') && t.ends_with('"') && t.len() >= 2)
272 || (t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2)
273 {
274 &t[1..t.len() - 1]
275 } else {
276 t
277 };
278 unq == "/dev/null"
279}
280
281fn scan_redirect(cmd: &str) -> Option<ScanResult> {
284 let b = cmd.as_bytes();
285 let n = b.len();
286 let mut i = 0usize;
287 let mut in_single = false;
288 let mut in_double = false;
289 let mut in_backtick = false;
290 let mut paren_depth: i32 = 0;
291 let mut brace_depth: i32 = 0; let mut out_redirs: Vec<(OutKind, usize, usize)> = Vec::new();
294 let mut dups: Vec<(usize, usize)> = Vec::new(); let mut other_redir = false;
296 let mut list_op = false;
297
298 while i < n {
299 let c = b[i];
300 if in_single {
301 if c == b'\'' {
302 in_single = false;
303 }
304 i += 1;
305 continue;
306 }
307 if in_double {
308 if c == b'\\' && i + 1 < n {
309 i += 2;
310 continue;
311 }
312 if c == b'"' {
313 in_double = false;
314 }
315 i += 1;
316 continue;
317 }
318 if in_backtick {
319 if c == b'`' {
320 in_backtick = false;
321 }
322 i += 1;
323 continue;
324 }
325 match c {
327 b'\\' => {
328 i += 2;
329 continue;
330 }
331 b'\'' => {
332 in_single = true;
333 i += 1;
334 continue;
335 }
336 b'"' => {
337 in_double = true;
338 i += 1;
339 continue;
340 }
341 b'`' => {
342 in_backtick = true;
343 i += 1;
344 continue;
345 }
346 b'#' => {
347 let prev = if i == 0 { b' ' } else { b[i - 1] };
349 if is_space(prev) || matches!(prev, b';' | b'|' | b'&' | b'(' | b'`') {
350 return None;
351 }
352 i += 1;
353 continue;
354 }
355 b'(' => {
356 paren_depth += 1;
357 i += 1;
358 continue;
359 }
360 b')' => {
361 if paren_depth > 0 {
362 paren_depth -= 1;
363 }
364 i += 1;
365 continue;
366 }
367 b'$' => {
368 if i + 1 < n && b[i + 1] == b'{' {
372 brace_depth += 1;
373 i += 2;
374 } else {
375 i += 1;
376 }
377 continue;
378 }
379 b'}' => {
380 if brace_depth > 0 {
381 brace_depth -= 1;
382 }
383 i += 1;
384 continue;
385 }
386 _ => {}
387 }
388 if paren_depth > 0 || brace_depth > 0 {
392 i += 1;
393 continue;
394 }
395 match c {
397 b'<' => {
398 if i + 1 < n && (b[i + 1] == b'(' || b[i + 1] == b'<') {
399 return None; }
401 other_redir = true; i += 1;
403 }
404 b'>' => {
405 if i + 1 < n && b[i + 1] == b'(' {
406 return None; }
408 if i > 0 && b[i - 1].is_ascii_digit() {
409 if b[i - 1] == b'2' && i + 2 < n && b[i + 1] == b'&' && b[i + 2] == b'1' {
411 dups.push((i - 1, i + 3));
412 i += 3;
413 } else {
414 other_redir = true;
415 i += 1;
416 }
417 } else if i + 1 < n && b[i + 1] == b'>' {
418 out_redirs.push((OutKind::Append, i, i + 2));
419 i += 2;
420 } else if i + 1 < n && b[i + 1] == b'&' {
421 other_redir = true; i += 1;
423 } else {
424 out_redirs.push((OutKind::Out, i, i + 1));
425 i += 1;
426 }
427 }
428 b'&' => {
429 if i + 1 < n && b[i + 1] == b'&' {
430 list_op = true;
431 i += 2;
432 } else if i + 1 < n && b[i + 1] == b'>' {
433 if i + 2 < n && b[i + 2] == b'>' {
434 out_redirs.push((OutKind::AmpAppend, i, i + 3));
435 i += 3;
436 } else {
437 out_redirs.push((OutKind::AmpOut, i, i + 2));
438 i += 2;
439 }
440 } else {
441 list_op = true; i += 1;
443 }
444 }
445 b'|' => {
446 list_op = true;
453 i += if i + 1 < n && b[i + 1] == b'|' { 2 } else { 1 };
454 }
455 b';' | b'\n' | b'\r' => {
461 list_op = true;
462 i += 1;
463 }
464 _ => {
465 i += 1;
466 }
467 }
468 }
469 if in_single || in_double || in_backtick {
470 return None; }
472 if list_op || other_redir || out_redirs.len() != 1 {
473 return None;
474 }
475 let (kind, rstart, rend) = out_redirs[0];
476 if dups.iter().any(|(ds, _)| *ds < rstart) {
479 return None;
480 }
481 let (tstart, tend) = read_word(b, rend)?;
483 let mut j = skip_spaces(b, tend);
485 let mut combine = matches!(kind, OutKind::AmpOut | OutKind::AmpAppend);
486 if let Some((_, de)) = dups.iter().find(|(ds, _)| *ds == j) {
487 combine = true;
488 j = skip_spaces(b, *de);
489 }
490 if j != n {
491 return None; }
493 Some(ScanResult {
494 redir_start: rstart,
495 target_start: tstart,
496 target_end: tend,
497 append: matches!(kind, OutKind::Append | OutKind::AmpAppend),
498 combine_stderr: combine,
499 })
500}
501
502fn skip_spaces(b: &[u8], mut i: usize) -> usize {
503 while i < b.len() && is_space(b[i]) {
504 i += 1;
505 }
506 i
507}
508
509fn read_word(b: &[u8], from: usize) -> Option<(usize, usize)> {
512 let n = b.len();
513 let mut i = skip_spaces(b, from);
514 if i >= n {
515 return None;
516 }
517 let start = i;
518 let mut in_single = false;
519 let mut in_double = false;
520 while i < n {
521 let c = b[i];
522 if in_single {
523 if c == b'\'' {
524 in_single = false;
525 }
526 i += 1;
527 continue;
528 }
529 if in_double {
530 if c == b'\\' && i + 1 < n {
531 i += 2;
532 continue;
533 }
534 if c == b'"' {
535 in_double = false;
536 }
537 i += 1;
538 continue;
539 }
540 match c {
541 b'\'' => {
542 in_single = true;
543 i += 1;
544 }
545 b'"' => {
546 in_double = true;
547 i += 1;
548 }
549 b'\\' => {
550 i += 2;
551 }
552 _ if is_space(c) => break,
553 b'>' | b'<' | b'|' | b'&' | b';' | b'(' | b')' => break,
555 _ => {
556 i += 1;
557 }
558 }
559 }
560 if i == start {
561 return None;
562 }
563 Some((start, i))
564}
565
566fn shell_quote(s: &str) -> String {
581 if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
582 return s.to_string();
583 }
584 #[cfg(windows)]
585 {
586 let escaped = s.replace('"', "\"\"");
590 format!("\"{}\"", escaped)
591 }
592 #[cfg(not(windows))]
593 {
594 let escaped = s.replace('\'', r"'\''");
596 format!("'{}'", escaped)
597 }
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603 use serde_json::json;
604
605 fn payload(cmd: &str, id: &str) -> String {
606 json!({
607 "tool_name": "Bash",
608 "tool_use_id": id,
609 "tool_input": { "command": cmd },
610 "session_id": "sess-1",
611 "hook_event_name": "PreToolUse"
612 })
613 .to_string()
614 }
615
616 #[test]
617 fn rewrites_simple_bash_command() {
618 let resp = build_response(&payload("echo hi", "toolu_abc"));
619 let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
620 .as_str()
621 .unwrap();
622 assert!(cmd.starts_with("agentmux-bashwrap exec"));
623 assert!(cmd.contains("--tool-id=toolu_abc"));
624 assert!(cmd.contains("--b64-cmd=ZWNobyBoaQ"));
626 assert_eq!(
627 resp["hookSpecificOutput"]["permissionDecision"].as_str(),
628 Some("allow")
629 );
630 }
631
632 #[test]
633 fn preserves_multi_line_and_quotes_via_base64() {
634 let cmd = r#"echo "hello" && echo 'multi
635line' && cat $HOME/.env"#;
636 let resp = build_response(&payload(cmd, "toolu_x"));
637 let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
638 .as_str()
639 .unwrap();
640 let b64 = wrapped
642 .split("--b64-cmd=")
643 .nth(1)
644 .expect("b64 arg present");
645 let decoded = URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap();
646 let decoded = String::from_utf8(decoded).unwrap();
647 assert_eq!(decoded, cmd);
648 }
649
650 #[test]
651 fn is_no_op_on_already_wrapped_command() {
652 let cmd =
653 "agentmux-bashwrap exec --tool-id=toolu_y --b64-cmd=ZWNobyBoaQ";
654 let resp = build_response(&payload(cmd, "toolu_y"));
655 assert!(
656 resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
657 "should pass through (empty object), got {}",
658 resp
659 );
660 }
661
662 #[test]
663 fn passes_through_non_bash_tools() {
664 let payload = json!({
665 "tool_name": "Read",
666 "tool_use_id": "toolu_r",
667 "tool_input": { "file_path": "x.txt" }
668 })
669 .to_string();
670 let resp = build_response(&payload);
671 assert!(
672 resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
673 "non-Bash should pass through"
674 );
675 }
676
677 #[test]
678 fn passes_through_malformed_input() {
679 let resp = build_response("not json");
680 assert!(
681 resp.as_object().map(|m| m.is_empty()).unwrap_or(false),
682 "malformed → passthrough"
683 );
684 }
685
686 #[test]
687 fn rewrites_with_empty_b64_when_command_field_missing() {
688 let payload = json!({
703 "tool_name": "Bash",
704 "tool_use_id": "toolu_z",
705 "tool_input": {}
706 })
707 .to_string();
708 let resp = build_response(&payload);
709 let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
710 .as_str()
711 .unwrap();
712 assert!(
716 cmd.contains("--b64-cmd=") && (cmd.ends_with("--b64-cmd=") || cmd.contains("--b64-cmd= ")),
717 "expected empty b64-cmd argument, got: {}",
718 cmd
719 );
720 }
721
722 #[test]
723 fn threads_declared_background_flag_when_run_in_background_true() {
724 let payload = json!({
725 "tool_name": "Bash",
726 "tool_use_id": "toolu_bg",
727 "tool_input": { "command": "task dev", "run_in_background": true }
728 })
729 .to_string();
730 let resp = build_response(&payload);
731 let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
732 .as_str()
733 .unwrap();
734 assert!(
735 cmd.ends_with(" --declared-background"),
736 "expected the wrapped command to carry --declared-background, got: {cmd}"
737 );
738 }
739
740 #[test]
741 fn omits_declared_background_flag_when_run_in_background_false_or_absent() {
742 let with_false = json!({
743 "tool_name": "Bash",
744 "tool_use_id": "toolu_fg",
745 "tool_input": { "command": "echo hi", "run_in_background": false }
746 })
747 .to_string();
748 let without_field = json!({
749 "tool_name": "Bash",
750 "tool_use_id": "toolu_fg2",
751 "tool_input": { "command": "echo hi" }
752 })
753 .to_string();
754 for payload in [with_false, without_field] {
755 let resp = build_response(&payload);
756 let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"]
757 .as_str()
758 .unwrap();
759 assert!(
760 !cmd.contains("--declared-background"),
761 "expected no --declared-background flag, got: {cmd}"
762 );
763 }
764 }
765
766 #[test]
771 fn keeps_every_other_field_of_the_tool_input() {
772 let payload = json!({
773 "tool_name": "Bash",
774 "tool_use_id": "toolu_keep",
775 "tool_input": {
776 "command": "task dev",
777 "description": "Start the dev build",
778 "timeout": 7_200_000,
779 "run_in_background": true,
780 "dangerouslyDisableSandbox": false,
781 "some_future_field": { "nested": [1, 2] }
782 }
783 })
784 .to_string();
785 let resp = build_response(&payload);
786 let updated = &resp["hookSpecificOutput"]["updatedInput"];
787 assert!(updated["command"].as_str().unwrap().starts_with("agentmux-bashwrap exec"));
788 assert_eq!(updated["description"], json!("Start the dev build"));
789 assert_eq!(updated["timeout"], json!(7_200_000));
790 assert_eq!(updated["run_in_background"], json!(true));
791 assert_eq!(updated["dangerouslyDisableSandbox"], json!(false));
792 assert_eq!(updated["some_future_field"], json!({ "nested": [1, 2] }));
793 assert_eq!(updated.as_object().unwrap().len(), 6);
794 }
795
796 #[test]
799 fn a_subagents_call_names_the_agent_and_the_main_conversation_none() {
800 let mut p: Value = serde_json::from_str(&payload("echo hi", "toolu_sub")).unwrap();
801 p["agent_id"] = json!("a7e1898179149a4f7");
802 let resp = build_response(&p.to_string());
803 let cmd = resp["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap().to_string();
804 assert!(cmd.ends_with(" --agent=a7e1898179149a4f7"), "{cmd}");
805 let main = build_response(&payload("echo hi", "toolu_main"));
806 assert!(!main["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap().contains("--agent"));
807 }
808
809 #[test]
810 fn record_mode_keeps_the_subagent_on_the_record() {
811 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
812 let dir = std::env::temp_dir().join(format!("bashwrap-hook-agent-{}", std::process::id()));
813 std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
814 let payload = json!({
815 "tool_name": "Bash", "tool_use_id": "toolu_sub", "session_id": "sess-sub", "agent_id": "sub-7",
816 "tool_input": { "command": "git status" }
817 })
818 .to_string();
819 record_response(&payload);
820 let claimed = crate::prefix::claim("sess-sub", "git status");
821 std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
822 let _ = std::fs::remove_dir_all(&dir);
823 assert_eq!(claimed.expect("recorded").agent_id.as_deref(), Some("sub-7"));
824 }
825
826 #[test]
830 fn record_mode_gives_a_git_call_a_long_timeout_and_decides_nothing_else() {
831 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
832 let dir = std::env::temp_dir().join(format!("bashwrap-hook-git-{}", std::process::id()));
833 std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
834 let call = |command: &str| {
835 json!({
836 "tool_name": "Bash", "tool_use_id": "toolu_git", "session_id": "sess-git",
837 "tool_input": { "command": command, "description": "Push the branch" }
838 })
839 .to_string()
840 };
841 std::env::set_var("BASH_DEFAULT_TIMEOUT_MS", "30000");
842 let git = record_response(&call("git push origin x"));
843 let other = record_response(&call("cargo build"));
844 let long_build = json!({
845 "tool_name": "Bash", "tool_use_id": "toolu_long", "session_id": "sess-git",
846 "tool_input": { "command": "cargo build", "timeout": 600_000 }
847 })
848 .to_string();
849 let clamped = record_response(&long_build);
850 std::env::remove_var("BASH_DEFAULT_TIMEOUT_MS");
851 let no_default = record_response(&call("git push origin x"));
852 std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
853 let _ = std::fs::remove_dir_all(&dir);
854 let hso = &git["hookSpecificOutput"];
855 assert_eq!(hso["updatedInput"]["timeout"], 300_000);
856 assert_eq!(hso["updatedInput"]["description"], "Push the branch");
857 assert!(hso.get("permissionDecision").is_none());
858 assert_eq!(other, json!({}));
859 assert_eq!(clamped["hookSpecificOutput"]["updatedInput"]["timeout"], 30_000, "a long timeout is clamped so the call goes to the background");
860 assert_eq!(no_default, json!({}));
861 }
862
863 #[test]
866 fn record_mode_records_the_call_and_answers_nothing() {
867 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
868 let dir = std::env::temp_dir().join(format!("bashwrap-hook-record-{}", std::process::id()));
869 std::env::set_var("AGENTMUX_BASHWRAP_CALLS_DIR", &dir);
870 let payload = json!({
871 "tool_name": "Bash",
872 "tool_use_id": "toolu_rec",
873 "session_id": "sess-rec",
874 "tool_input": { "command": "cargo build", "description": "Build", "run_in_background": true }
875 })
876 .to_string();
877 let resp = record_response(&payload);
878 let claimed = crate::prefix::claim("sess-rec", "cargo build");
879 let described = claimed.as_ref().and_then(|c| c.description.clone());
880 let wrapped = json!({
881 "tool_name": "Bash", "tool_use_id": "toolu_w", "session_id": "sess-rec",
882 "tool_input": { "command": "agentmux-bashwrap exec --tool-id=x --b64-cmd=eA" }
883 })
884 .to_string();
885 let resp_wrapped = record_response(&wrapped);
886 let left = crate::prefix::claim("sess-rec", "any command");
887 std::env::remove_var("AGENTMUX_BASHWRAP_CALLS_DIR");
888 let _ = std::fs::remove_dir_all(&dir);
889
890 assert_eq!(resp, json!({}));
891 let claimed = claimed.expect("the call was recorded");
892 assert_eq!((claimed.tool_use_id.as_str(), claimed.run_in_background), ("toolu_rec", true));
893 assert_eq!(described.as_deref(), Some("Build"), "the call's description, for Tower");
894 assert_eq!(resp_wrapped, json!({}));
895 assert_eq!(left, None, "an already-wrapped command isn't recorded");
896 }
897
898 #[test]
899 fn record_mode_ignores_other_tools_and_malformed_payloads() {
900 assert_eq!(record_response("not json"), json!({}));
901 let read = json!({ "tool_name": "Read", "tool_use_id": "t", "session_id": "s", "tool_input": {} }).to_string();
902 assert_eq!(record_response(&read), json!({}));
903 }
904
905 #[test]
906 fn a_tool_input_that_is_not_an_object_still_gets_the_command() {
907 let payload = json!({
908 "tool_name": "Bash",
909 "tool_use_id": "toolu_odd",
910 "tool_input": "echo hi"
911 })
912 .to_string();
913 let resp = build_response(&payload);
914 let updated = resp["hookSpecificOutput"]["updatedInput"].as_object().unwrap();
915 assert_eq!(updated.len(), 1);
916 assert!(updated["command"].as_str().unwrap().starts_with("agentmux-bashwrap exec"));
917 }
918
919 #[test]
920 fn shell_quote_passes_safe_ids_unchanged() {
921 assert_eq!(shell_quote("toolu_abc-123"), "toolu_abc-123");
922 }
923
924 #[cfg(not(windows))]
925 #[test]
926 fn shell_quote_wraps_unsafe_ids_unix() {
927 let q = shell_quote("weird id");
928 assert_eq!(q, "'weird id'");
929 }
930
931 #[cfg(not(windows))]
932 #[test]
933 fn shell_quote_escapes_embedded_single_quotes_unix() {
934 let q = shell_quote("o'malley");
937 assert_eq!(q, r"'o'\''malley'");
938 }
939
940 #[cfg(windows)]
941 #[test]
942 fn shell_quote_wraps_unsafe_ids_windows() {
943 let q = shell_quote("weird id");
944 assert_eq!(q, "\"weird id\"");
945 }
946
947 #[cfg(windows)]
948 #[test]
949 fn shell_quote_escapes_embedded_double_quotes_windows() {
950 let q = shell_quote("a\"b");
953 assert_eq!(q, "\"a\"\"b\"");
954 }
955
956 #[test]
959 fn tee_rewrites_basic_redirect_forms() {
960 assert_eq!(
961 tee_redirect_rewrite("task package > build.log").unwrap(),
962 "set -o pipefail; { task package ; } | tee -- build.log"
963 );
964 assert_eq!(
965 tee_redirect_rewrite("make >> out.log").unwrap(),
966 "set -o pipefail; { make ; } | tee -a -- out.log"
967 );
968 assert_eq!(
969 tee_redirect_rewrite("task package > build.log 2>&1").unwrap(),
970 "set -o pipefail; { task package ; } 2>&1 | tee -- build.log"
971 );
972 assert_eq!(
973 tee_redirect_rewrite("make >> out.log 2>&1").unwrap(),
974 "set -o pipefail; { make ; } 2>&1 | tee -a -- out.log"
975 );
976 assert_eq!(
977 tee_redirect_rewrite("cmd &> all.log").unwrap(),
978 "set -o pipefail; { cmd ; } 2>&1 | tee -- all.log"
979 );
980 assert_eq!(
981 tee_redirect_rewrite("cmd &>> all.log").unwrap(),
982 "set -o pipefail; { cmd ; } 2>&1 | tee -a -- all.log"
983 );
984 }
985
986 #[test]
987 fn tee_bails_on_internal_pipeline() {
988 assert!(tee_redirect_rewrite("cargo build | grep error > errors.log").is_none());
991 }
992
993 #[test]
994 fn tee_bails_on_multiline_command() {
995 assert!(tee_redirect_rewrite("echo building\nmake > build.log").is_none());
998 assert!(tee_redirect_rewrite("cd src\nmake > build.log 2>&1").is_none());
999 assert_eq!(
1001 tee_redirect_rewrite("make \\\n --flag > build.log").unwrap(),
1002 "set -o pipefail; { make \\\n --flag ; } | tee -- build.log"
1003 );
1004 }
1005
1006 #[test]
1007 fn tee_handles_subshell_command() {
1008 assert_eq!(
1009 tee_redirect_rewrite("(cd src && make) > b.log 2>&1").unwrap(),
1010 "set -o pipefail; { (cd src && make) ; } 2>&1 | tee -- b.log"
1011 );
1012 }
1013
1014 #[test]
1015 fn tee_preserves_quoted_target() {
1016 assert_eq!(
1017 tee_redirect_rewrite(r#"cmd > "my out.log""#).unwrap(),
1018 r#"set -o pipefail; { cmd ; } | tee -- "my out.log""#
1019 );
1020 }
1021
1022 #[test]
1023 fn tee_bails_on_dev_null() {
1024 assert!(tee_redirect_rewrite("noisy > /dev/null").is_none());
1025 assert!(tee_redirect_rewrite("noisy > /dev/null 2>&1").is_none());
1026 assert!(tee_redirect_rewrite(r#"noisy > "/dev/null""#).is_none());
1027 }
1028
1029 #[test]
1030 fn tee_bails_on_quoted_comment_heredoc_procsub() {
1031 assert!(tee_redirect_rewrite("echo 'a > b'").is_none()); assert!(tee_redirect_rewrite("echo \"x > y\"").is_none()); assert!(tee_redirect_rewrite("make # writes > log").is_none()); assert!(tee_redirect_rewrite("cat <<EOF > f\nhi\nEOF").is_none()); assert!(tee_redirect_rewrite("diff <(a) > f").is_none()); }
1037
1038 #[test]
1039 fn tee_bails_on_non_trailing_multiple_or_fd_redirects() {
1040 assert!(tee_redirect_rewrite("cmd > f | grep x").is_none()); assert!(tee_redirect_rewrite("cmd > f && other").is_none()); assert!(tee_redirect_rewrite("a > f1 > f2").is_none()); assert!(tee_redirect_rewrite("cmd 2> err.log").is_none()); assert!(tee_redirect_rewrite("cmd >&2").is_none()); assert!(tee_redirect_rewrite("cmd 2>&1 > f").is_none()); assert!(tee_redirect_rewrite("echo hi").is_none()); assert!(tee_redirect_rewrite("server > log &").is_none()); }
1049
1050 #[test]
1051 fn tee_handles_param_expansion() {
1052 assert!(tee_redirect_rewrite("echo ${X:->f}").is_none());
1054 assert!(tee_redirect_rewrite("echo ${X/>/_}").is_none());
1055 assert_eq!(
1057 tee_redirect_rewrite("make > ${LOG}/out.log").unwrap(),
1058 "set -o pipefail; { make ; } | tee -- ${LOG}/out.log"
1059 );
1060 assert_eq!(
1062 tee_redirect_rewrite("echo ${X/>/_} > out.log").unwrap(),
1063 "set -o pipefail; { echo ${X/>/_} ; } | tee -- out.log"
1064 );
1065 }
1066
1067 #[test]
1068 fn tee_rewrite_round_trips_through_build_response_b64() {
1069 let resp = build_response(&payload("task package > build.log 2>&1", "toolu_t"));
1070 let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
1071 .as_str()
1072 .unwrap();
1073 let b64 = wrapped.split("--b64-cmd=").nth(1).expect("b64 arg");
1074 let decoded =
1075 String::from_utf8(URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap()).unwrap();
1076 assert_eq!(
1077 decoded,
1078 "set -o pipefail; { task package ; } 2>&1 | tee -- build.log"
1079 );
1080 assert!(decoded.starts_with("set -o pipefail;"));
1082 }
1083
1084 #[test]
1085 fn tee_non_redirect_command_encodes_verbatim() {
1086 let resp = build_response(&payload("echo hi", "toolu_a"));
1088 let wrapped = resp["hookSpecificOutput"]["updatedInput"]["command"]
1089 .as_str()
1090 .unwrap();
1091 let b64 = wrapped.split("--b64-cmd=").nth(1).unwrap();
1092 let decoded =
1093 String::from_utf8(URL_SAFE_NO_PAD.decode(b64.as_bytes()).unwrap()).unwrap();
1094 assert_eq!(decoded, "echo hi");
1095 }
1096}