Skip to main content

microclaw_engine/tools/
bash.rs

1use async_trait::async_trait;
2use serde_json::json;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use tracing::info;
6
7use crate::config::{RtkConfig, WorkingDirIsolation};
8use crate::internal::tool_runtime::sandbox::{SandboxExecOptions, SandboxMode, SandboxRouter};
9use microclaw_core::llm_types::ToolDefinition;
10use microclaw_core::text::floor_char_boundary;
11
12use super::{schema_object, Tool, ToolResult};
13
14pub struct BashTool {
15    working_dir: PathBuf,
16    working_dir_isolation: WorkingDirIsolation,
17    default_timeout_secs: u64,
18    sandbox_router: Option<Arc<SandboxRouter>>,
19    /// Compiled command-content patterns that always force operator approval,
20    /// independent of `tool_risk` chat-level gating. Empty = no inspection.
21    dangerous_patterns: Vec<(String, regex::Regex)>,
22    /// `Some` only when RTK rewriting is enabled in config.
23    rtk: Option<RtkConfig>,
24    /// Background processes shared with `bash_output` / `bash_kill`; `None`
25    /// disables `run_in_background`.
26    processes: Option<Arc<super::background_process::ProcessRegistry>>,
27}
28
29impl BashTool {
30    pub fn new(working_dir: &str) -> Self {
31        Self::new_with_isolation(working_dir, WorkingDirIsolation::Shared)
32    }
33
34    pub fn new_with_isolation(
35        working_dir: &str,
36        working_dir_isolation: WorkingDirIsolation,
37    ) -> Self {
38        Self {
39            working_dir: PathBuf::from(working_dir),
40            working_dir_isolation,
41            default_timeout_secs: 120,
42            sandbox_router: None,
43            dangerous_patterns: Vec::new(),
44            rtk: None,
45            processes: None,
46        }
47    }
48
49    pub fn with_default_timeout_secs(mut self, timeout_secs: u64) -> Self {
50        self.default_timeout_secs = timeout_secs;
51        self
52    }
53
54    pub fn with_sandbox_router(mut self, router: Arc<SandboxRouter>) -> Self {
55        self.sandbox_router = Some(router);
56        self
57    }
58
59    pub fn with_rtk(mut self, rtk: &RtkConfig) -> Self {
60        if rtk.enabled {
61            self.rtk = Some(rtk.clone());
62        }
63        self
64    }
65
66    /// Enable `run_in_background`, sharing processes with `bash_output` /
67    /// `bash_kill` built from the same registry.
68    pub fn with_process_registry(
69        mut self,
70        processes: Arc<super::background_process::ProcessRegistry>,
71    ) -> Self {
72        self.processes = Some(processes);
73        self
74    }
75
76    /// Compile and store dangerous-command patterns. Invalid regexes are
77    /// logged and skipped — operator typos must not break the bash tool.
78    pub fn with_dangerous_patterns(mut self, patterns: &[String]) -> Self {
79        for raw in patterns {
80            let with_flag = if raw.starts_with("(?i)") {
81                raw.clone()
82            } else {
83                format!("(?i){raw}")
84            };
85            match regex::Regex::new(&with_flag) {
86                Ok(re) => self.dangerous_patterns.push((raw.clone(), re)),
87                Err(e) => {
88                    tracing::warn!("ignoring invalid bash_dangerous_patterns entry {raw:?}: {e}")
89                }
90            }
91        }
92        self
93    }
94
95    async fn start_background(
96        &self,
97        session_key: &str,
98        command: &str,
99        exec_command: &str,
100        working_dir: &Path,
101        env_files: &[PathBuf],
102    ) -> ToolResult {
103        // The local OS sandbox can confine long-running processes too; a
104        // container sandbox cannot.
105        let local_spec = self
106            .sandbox_router
107            .as_ref()
108            .filter(|router| router.mode() != SandboxMode::Off)
109            .and_then(|router| router.local())
110            .map(|local| local.command_spec(exec_command, working_dir));
111        if local_spec.is_none()
112            && self
113                .sandbox_router
114                .as_ref()
115                .is_some_and(|router| router.mode() != SandboxMode::Off)
116        {
117            return ToolResult::error(
118                "run_in_background is only available when the sandbox is off; run the command in the foreground with a longer timeout_secs instead.".into(),
119            )
120            .with_error_type("execution_policy_blocked");
121        }
122        let mut envs = std::collections::HashMap::new();
123        for env_file in env_files {
124            if let Ok(content) = std::fs::read_to_string(env_file) {
125                envs.extend(crate::internal::tool_runtime::env_file::parse_dotenv(
126                    &content,
127                ));
128            }
129        }
130        let Some(processes) = &self.processes else {
131            return ToolResult::error(
132                "run_in_background is not available in this runtime; run the command in the foreground instead.".into(),
133            )
134            .with_error_type("execution_policy_blocked");
135        };
136        let spawned = match &local_spec {
137            Some(spec) => processes.spawn_spec(session_key, command, spec, working_dir, &envs),
138            None => processes.spawn(session_key, exec_command, working_dir, &envs),
139        };
140        match spawned {
141            Ok(id) => {
142                info!(
143                    "Started background bash {id} in {}: {command}",
144                    working_dir.display()
145                );
146                ToolResult::success(format!(
147                    "Started background process {id}: {command}\nRead its output with bash_output {{\"id\": \"{id}\"}} and stop it with bash_kill when you no longer need it."
148                ))
149            }
150            Err(msg) => ToolResult::error(msg).with_error_type("spawn_error"),
151        }
152    }
153}
154
155use crate::internal::tool_runtime::runtime::HIGH_RISK_APPROVED_KEY as BASH_HIGH_RISK_APPROVED_KEY;
156
157fn extract_env_files(input: &serde_json::Value) -> Vec<PathBuf> {
158    super::auth_context_from_input(input)
159        .map(|auth| auth.env_files.iter().map(PathBuf::from).collect())
160        .unwrap_or_default()
161}
162
163const REDACT_MIN_VALUE_LEN: usize = 8;
164
165fn redact_env_secrets(output: &str, env_files: &[PathBuf]) -> String {
166    let mut secrets: Vec<(String, String)> = Vec::new();
167    for env_file in env_files {
168        if let Ok(content) = std::fs::read_to_string(env_file) {
169            for (key, value) in crate::internal::tool_runtime::env_file::parse_dotenv(&content) {
170                if value.len() >= REDACT_MIN_VALUE_LEN {
171                    secrets.push((key, value));
172                }
173            }
174        }
175    }
176    if secrets.is_empty() {
177        return output.to_string();
178    }
179    secrets.sort_by_key(|secret| std::cmp::Reverse(secret.1.len()));
180    let mut redacted = output.to_string();
181    for (key, value) in &secrets {
182        redacted = redacted.replace(value, &format!("[REDACTED:{key}]"));
183    }
184    redacted
185}
186
187fn contains_explicit_tmp_absolute_path(command: &str) -> bool {
188    let mut start = 0usize;
189    while let Some(offset) = command[start..].find("/tmp/") {
190        let idx = start + offset;
191        let prev = if idx == 0 {
192            None
193        } else {
194            command[..idx].chars().next_back()
195        };
196        if prev.is_none()
197            || matches!(
198                prev,
199                Some(' ' | '\t' | '\n' | '\'' | '"' | '=' | '(' | ':' | ';' | '|')
200            )
201        {
202            return true;
203        }
204        start = idx + 5;
205    }
206    false
207}
208
209fn extract_explicit_tmp_absolute_path(command: &str) -> Option<String> {
210    let mut start = 0usize;
211    while let Some(offset) = command[start..].find("/tmp/") {
212        let idx = start + offset;
213        let prev = if idx == 0 {
214            None
215        } else {
216            command[..idx].chars().next_back()
217        };
218        if prev.is_none()
219            || matches!(
220                prev,
221                Some(' ' | '\t' | '\n' | '\'' | '"' | '=' | '(' | ':' | ';' | '|')
222            )
223        {
224            let suffix = &command[idx + 5..];
225            let end = suffix
226                .find(|c: char| c.is_whitespace() || matches!(c, '\'' | '"' | ')' | ';' | '|'))
227                .unwrap_or(suffix.len());
228            return Some(command[idx..idx + 5 + end].to_string());
229        }
230        start = idx + 5;
231    }
232    None
233}
234
235fn suggested_tmp_working_dir_path(working_dir: &Path, command: &str) -> Option<PathBuf> {
236    let tmp_path = extract_explicit_tmp_absolute_path(command)?;
237    let relative = tmp_path.trim_start_matches("/tmp/").trim();
238    if relative.is_empty() {
239        return Some(working_dir.to_path_buf());
240    }
241    Some(working_dir.join(relative))
242}
243
244fn command_accesses_dotenv(command: &str) -> bool {
245    let patterns = [".env", "dotenv", "env_file"];
246    let lower = command.to_ascii_lowercase();
247    patterns.iter().any(|p| lower.contains(p))
248}
249
250/// Ceiling on the rewrite subprocess; rtk classifies in <10ms, so hitting
251/// this means a hung binary, not a slow rewrite.
252const RTK_REWRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
253
254/// Ask the rtk binary for a token-efficient rewrite of `command`.
255///
256/// `rtk rewrite` exit-code protocol (rtk's hooks/claude/rtk-rewrite.sh is the
257/// reference consumer): 0 = rewritten (stdout), 1 = no RTK equivalent,
258/// 2 = deny rule, 3 = ask rule. Only exit 0 is accepted here — deny/ask
259/// express RTK-side permission rules that MicroClaw's own approval gates
260/// (`dangerous_patterns`, `tool_risk`) are responsible for, so those run the
261/// original command. Missing binary, timeout, or any other failure also fall
262/// back to the original command: RTK must never break the bash tool.
263async fn rtk_rewrite(binary_path: &str, command: &str) -> Option<String> {
264    let output = tokio::time::timeout(
265        RTK_REWRITE_TIMEOUT,
266        tokio::process::Command::new(binary_path)
267            .arg("rewrite")
268            .arg(command)
269            .stdin(std::process::Stdio::null())
270            .output(),
271    )
272    .await;
273    let output = match output {
274        Ok(Ok(output)) => output,
275        Ok(Err(e)) => {
276            tracing::warn!(
277                "rtk rewrite unavailable ({binary_path}): {e}; running original command"
278            );
279            return None;
280        }
281        Err(_) => {
282            tracing::warn!("rtk rewrite timed out; running original command");
283            return None;
284        }
285    };
286    if output.status.code() != Some(0) {
287        return None;
288    }
289    let rewritten = String::from_utf8_lossy(&output.stdout).trim().to_string();
290    if rewritten.is_empty() || rewritten == command {
291        return None;
292    }
293    Some(rewritten)
294}
295
296fn command_not_found_hint(router: Option<&Arc<SandboxRouter>>) -> &'static str {
297    match router {
298        Some(router) if router.mode() == SandboxMode::All => {
299            "Command was not found in the current execution environment. Install it on the host, or ensure the configured sandbox image contains it."
300        }
301        _ => {
302            "Command was not found on the host. Install it, or enable sandbox mode with an image that already contains the dependency."
303        }
304    }
305}
306
307#[async_trait]
308impl Tool for BashTool {
309    fn name(&self) -> &str {
310        "bash"
311    }
312
313    fn definition(&self) -> ToolDefinition {
314        ToolDefinition {
315            name: "bash".into(),
316            description: "Execute a bash command and return the output. IMPORTANT: You must CALL this tool (not write it as text) to run a command. Use for running shell commands, scripts, or system operations. Prefer relative paths rooted in the current chat working directory, and use its tmp/ subdirectory instead of absolute /tmp paths. Do not invent machine-specific absolute paths like /home/... or /Users/... unless the user or a tool already provided them.".into(),
317            input_schema: schema_object(
318                json!({
319                    "command": {
320                        "type": "string",
321                        "description": "The bash command to execute"
322                    },
323                    "run_in_background": {
324                        "type": "boolean",
325                        "description": "Start the command in the background (dev servers, watchers, long test runs) and return immediately with a process id; read its output with bash_output and stop it with bash_kill"
326                    },
327                    "timeout_secs": {
328                        "type": "integer",
329                        "description": "Timeout in seconds (defaults to configured tool timeout budget)"
330                    }
331                }),
332                &["command"],
333            ),
334        }
335    }
336
337    async fn execute(&self, input: serde_json::Value) -> ToolResult {
338        let command = match input.get("command").and_then(|v| v.as_str()) {
339            Some(c) => c,
340            None => return ToolResult::error("Missing 'command' parameter".into()),
341        };
342
343        // Command-content gate: certain shell snippets are dangerous regardless
344        // of which chat invoked the tool. Force operator approval before
345        // proceeding. The auto-retry path in tool_executor sees the
346        // `approval_required` error type and either retries with the marker
347        // (after explicit user approval) or pauses the agent.
348        let already_approved = input
349            .get(BASH_HIGH_RISK_APPROVED_KEY)
350            .and_then(|v| v.as_bool())
351            .unwrap_or(false);
352        if !already_approved {
353            for (raw, re) in &self.dangerous_patterns {
354                if re.is_match(command) {
355                    return ToolResult::error(format!(
356                        "Approval required: command matches dangerous pattern `{raw}`. Operator must explicitly approve before this runs."
357                    ))
358                    .with_error_type("approval_required");
359                }
360            }
361        }
362
363        let timeout_secs = input
364            .get("timeout_secs")
365            .and_then(|v| v.as_u64())
366            .unwrap_or(self.default_timeout_secs);
367        let base_dir =
368            super::resolve_tool_working_dir(&self.working_dir, self.working_dir_isolation, &input);
369        // A direct workspace (a MicroClaw Code project folder) runs
370        // commands from the project root so build and test tools find their
371        // manifests; isolated chat workspaces keep the scratch `tmp/` subdir.
372        let working_dir = if self.working_dir_isolation == WorkingDirIsolation::Direct {
373            base_dir.clone()
374        } else {
375            base_dir.join("tmp")
376        };
377        if let Err(e) = tokio::fs::create_dir_all(&working_dir).await {
378            return ToolResult::error(format!(
379                "Failed to create working directory {}: {e}",
380                working_dir.display()
381            ));
382        }
383
384        if contains_explicit_tmp_absolute_path(command) {
385            let suggested_path = suggested_tmp_working_dir_path(&working_dir, command)
386                .map(|p| p.display().to_string())
387                .unwrap_or_else(|| working_dir.display().to_string());
388            return ToolResult::error(format!(
389                "Command contains an absolute /tmp path. Use the current chat working directory instead: {}. For example, replace the /tmp path with {}.",
390                working_dir.display(),
391                suggested_path
392            ))
393            .with_error_type("path_policy_blocked");
394        }
395
396        let env_files = extract_env_files(&input);
397        if !env_files.is_empty() && command_accesses_dotenv(command) {
398            return ToolResult::error(
399                "Command appears to access .env files, which is blocked for security. Skill environment variables are already injected automatically.".into(),
400            )
401            .with_error_type("env_access_blocked");
402        }
403
404        // RTK rewrite runs after every gate above so the gates always judge
405        // the operator-visible command, never the rtk-prefixed variant.
406        let mut exec_command = command.to_string();
407        let mut rtk_rewritten = false;
408        if let Some(rtk) = &self.rtk {
409            if let Some(rewritten) = rtk_rewrite(&rtk.binary_path, command).await {
410                info!("rtk rewrite: {command} -> {rewritten}");
411                exec_command = rewritten;
412                rtk_rewritten = true;
413            }
414        }
415
416        info!(
417            "Executing bash in {}: {}",
418            working_dir.display(),
419            exec_command
420        );
421
422        let session_key = super::background_process::session_key(&input);
423        if input
424            .get("run_in_background")
425            .and_then(|v| v.as_bool())
426            .unwrap_or(false)
427        {
428            return self
429                .start_background(
430                    &session_key,
431                    command,
432                    &exec_command,
433                    &working_dir,
434                    &env_files,
435                )
436                .await;
437        }
438        let env_files_for_redact = env_files.clone();
439        let exec_opts = SandboxExecOptions {
440            timeout: std::time::Duration::from_secs(timeout_secs),
441            working_dir: Some(working_dir.clone()),
442            envs: std::collections::HashMap::new(),
443            env_files,
444        };
445        let mut result = if let Some(router) = &self.sandbox_router {
446            router.exec(&session_key, &exec_command, &exec_opts).await
447        } else {
448            crate::internal::tool_runtime::sandbox::exec_host_command(&exec_command, &exec_opts)
449                .await
450        };
451
452        // The rewrite decision is made on the host, but execution may land in
453        // a sandbox image that lacks the rtk binary (exit 127). Retry the
454        // original command so enabling RTK never makes a command fail that
455        // would have succeeded without it.
456        if rtk_rewritten && matches!(&result, Ok(output) if output.exit_code == 127) {
457            info!("rtk not available in execution environment; retrying original command");
458            result = if let Some(router) = &self.sandbox_router {
459                router.exec(&session_key, command, &exec_opts).await
460            } else {
461                crate::internal::tool_runtime::sandbox::exec_host_command(command, &exec_opts).await
462            };
463        }
464
465        match result {
466            Ok(output) => {
467                let stdout = output.stdout;
468                let stderr = output.stderr;
469                let exit_code = output.exit_code;
470
471                let mut result_text = String::new();
472                if !stdout.is_empty() {
473                    result_text.push_str(stdout.as_str());
474                }
475                if !stderr.is_empty() {
476                    if !result_text.is_empty() {
477                        result_text.push('\n');
478                    }
479                    result_text.push_str("STDERR:\n");
480                    result_text.push_str(stderr.as_str());
481                }
482                if result_text.is_empty() {
483                    result_text = format!("Command completed with exit code {exit_code}");
484                }
485
486                result_text = redact_env_secrets(&result_text, &env_files_for_redact);
487
488                if exit_code == 127 && stderr.to_ascii_lowercase().contains("command not found") {
489                    if !result_text.ends_with('\n') {
490                        result_text.push('\n');
491                    }
492                    result_text.push_str(command_not_found_hint(self.sandbox_router.as_ref()));
493                }
494
495                // Truncate very long output
496                if result_text.len() > 30000 {
497                    let cutoff = floor_char_boundary(&result_text, 30000);
498                    result_text.truncate(cutoff);
499                    result_text.push_str("\n... (output truncated)");
500                }
501
502                if exit_code == 0 {
503                    ToolResult::success(result_text).with_status_code(exit_code)
504                } else {
505                    ToolResult::error(format!("Exit code {exit_code}\n{result_text}"))
506                        .with_status_code(exit_code)
507                        .with_error_type("process_exit")
508                }
509            }
510            Err(e) => {
511                let msg = e.to_string();
512                if msg.contains("timed out after") {
513                    ToolResult::error(format!("Command timed out after {timeout_secs} seconds"))
514                        .with_error_type("timeout")
515                } else {
516                    ToolResult::error(format!("Failed to execute command: {e}"))
517                        .with_error_type("spawn_error")
518                }
519            }
520        }
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use serde_json::json;
528
529    fn sleep_command(seconds: u64) -> String {
530        if cfg!(target_os = "windows") {
531            format!("Start-Sleep -Seconds {seconds}")
532        } else {
533            format!("sleep {seconds}")
534        }
535    }
536
537    fn stderr_command() -> &'static str {
538        if cfg!(target_os = "windows") {
539            "[Console]::Error.WriteLine('err')"
540        } else {
541            "echo err >&2"
542        }
543    }
544
545    fn write_marker_command(file_name: &str) -> String {
546        if cfg!(target_os = "windows") {
547            format!("New-Item -ItemType File -Path '{file_name}' -Force | Out-Null")
548        } else {
549            format!("touch '{file_name}'")
550        }
551    }
552
553    fn echo_env_command(var_name: &str) -> String {
554        if cfg!(target_os = "windows") {
555            format!("$env:{var_name}")
556        } else {
557            format!("echo ${var_name}")
558        }
559    }
560
561    #[test]
562    fn test_contains_explicit_tmp_absolute_path_detection() {
563        assert!(contains_explicit_tmp_absolute_path("ls /tmp/x"));
564        assert!(contains_explicit_tmp_absolute_path("A=\"/tmp/x\"; echo $A"));
565        assert!(!contains_explicit_tmp_absolute_path(
566            "ls /Users/eevv/work/project/tmp/x"
567        ));
568    }
569
570    #[test]
571    fn test_extract_explicit_tmp_absolute_path() {
572        assert_eq!(
573            extract_explicit_tmp_absolute_path("git clone repo /tmp/lootbox"),
574            Some("/tmp/lootbox".to_string())
575        );
576        assert_eq!(
577            extract_explicit_tmp_absolute_path("A=\"/tmp/lootbox\"; echo $A"),
578            Some("/tmp/lootbox".to_string())
579        );
580    }
581
582    #[test]
583    fn test_suggested_tmp_working_dir_path() {
584        let work = Path::new("/workspace/chat/tmp");
585        assert_eq!(
586            suggested_tmp_working_dir_path(work, "git clone repo /tmp/lootbox"),
587            Some(PathBuf::from("/workspace/chat/tmp/lootbox"))
588        );
589    }
590
591    #[tokio::test]
592    async fn test_bash_echo() {
593        let tool = BashTool::new(".");
594        let result = tool.execute(json!({"command": "echo hello"})).await;
595        assert!(!result.is_error);
596        assert!(result.content.contains("hello"));
597    }
598
599    #[tokio::test]
600    async fn test_dangerous_pattern_returns_approval_required() {
601        let patterns = vec![r"\bsudo\b".to_string()];
602        let tool = BashTool::new(".").with_dangerous_patterns(&patterns);
603        let result = tool.execute(json!({"command": "sudo ls"})).await;
604        assert!(result.is_error, "expected approval gate, got success");
605        assert_eq!(result.error_type.as_deref(), Some("approval_required"));
606        assert!(result.content.contains("dangerous pattern"));
607    }
608
609    #[tokio::test]
610    async fn test_dangerous_pattern_skipped_after_approval_marker() {
611        let patterns = vec![r"\bsudo\b".to_string()];
612        let tool = BashTool::new(".").with_dangerous_patterns(&patterns);
613        // Marker present -> pattern check skipped. The actual sudo will likely
614        // fail on the test host, but we only want to verify the gate yielded.
615        let result = tool
616            .execute(json!({
617                "command": "echo not-actually-sudo",
618                "__microclaw_high_risk_approved": true,
619            }))
620            .await;
621        assert!(!result.is_error);
622        assert!(result.content.contains("not-actually-sudo"));
623    }
624
625    #[tokio::test]
626    async fn test_invalid_dangerous_pattern_is_skipped_gracefully() {
627        let patterns = vec!["[unclosed".to_string(), r"\brm\s+-rf\s+/".to_string()];
628        let tool = BashTool::new(".").with_dangerous_patterns(&patterns);
629        // The valid pattern still trips on the dangerous command.
630        let result = tool.execute(json!({"command": "rm -rf /tmp"})).await;
631        // Should fail on the path-policy gate instead of pattern match (since
632        // /tmp absolute path is a separate gate), so just assert we didn't panic.
633        let _ = result;
634    }
635
636    #[tokio::test]
637    async fn test_bash_exit_code_nonzero() {
638        let tool = BashTool::new(".");
639        let result = tool.execute(json!({"command": "exit 1"})).await;
640        assert!(result.is_error);
641        assert!(result.content.contains("Exit code 1"));
642    }
643
644    #[tokio::test]
645    async fn test_bash_stderr() {
646        let tool = BashTool::new(".");
647        let result = tool.execute(json!({"command": stderr_command()})).await;
648        assert!(!result.is_error); // exit code is 0
649        assert!(result.content.contains("STDERR"));
650        assert!(result.content.contains("err"));
651    }
652
653    #[tokio::test]
654    async fn test_bash_timeout() {
655        let tool = BashTool::new(".");
656        let result = tool
657            .execute(json!({"command": sleep_command(10), "timeout_secs": 1}))
658            .await;
659        assert!(result.is_error);
660        assert!(result.content.contains("timed out"));
661    }
662
663    #[tokio::test]
664    async fn test_bash_blocks_tmp_absolute_path() {
665        let tool = BashTool::new(".");
666        let result = tool.execute(json!({"command": "ls /tmp/x"})).await;
667        assert!(result.is_error);
668        assert_eq!(result.error_type.as_deref(), Some("path_policy_blocked"));
669        assert!(result.content.contains("current chat working directory"));
670        assert!(result.content.contains("replace the /tmp path"));
671    }
672
673    #[tokio::test]
674    async fn test_bash_missing_command() {
675        let tool = BashTool::new(".");
676        let result = tool.execute(json!({})).await;
677        assert!(result.is_error);
678        assert!(result.content.contains("Missing 'command'"));
679    }
680
681    #[test]
682    fn test_bash_tool_name_and_definition() {
683        let tool = BashTool::new(".");
684        assert_eq!(tool.name(), "bash");
685        let def = tool.definition();
686        assert_eq!(def.name, "bash");
687        assert!(def
688            .description
689            .contains("Prefer relative paths rooted in the current chat working directory"));
690        assert!(def.description.contains("/home/... or /Users/..."));
691        assert!(def.input_schema["properties"]["command"].is_object());
692    }
693
694    #[tokio::test]
695    async fn test_bash_uses_working_dir() {
696        let root = std::env::temp_dir().join(format!("microclaw_bash_{}", uuid::Uuid::new_v4()));
697        let work = root.join("workspace");
698        std::fs::create_dir_all(&work).unwrap();
699
700        let tool = BashTool::new(work.to_str().unwrap());
701        let marker = "cwd_marker.txt";
702        let result = tool
703            .execute(json!({"command": write_marker_command(marker)}))
704            .await;
705        assert!(!result.is_error);
706
707        let expected_marker = work.join("shared").join("tmp").join(marker);
708        assert!(expected_marker.exists());
709
710        let _ = std::fs::remove_dir_all(&root);
711    }
712
713    #[tokio::test]
714    async fn test_bash_chat_isolation_uses_chat_working_dir() {
715        let root = std::env::temp_dir().join(format!("microclaw_bash_{}", uuid::Uuid::new_v4()));
716        let work = root.join("workspace");
717        std::fs::create_dir_all(&work).unwrap();
718
719        let tool = BashTool::new_with_isolation(work.to_str().unwrap(), WorkingDirIsolation::Chat);
720        let marker = "chat_marker.txt";
721        let result = tool
722            .execute(json!({
723                "command": write_marker_command(marker),
724                "__microclaw_auth": {
725                    "caller_channel": "telegram",
726                    "caller_chat_id": -100123,
727                    "control_chat_ids": []
728                }
729            }))
730            .await;
731        assert!(!result.is_error);
732
733        let expected_marker = work
734            .join("chat")
735            .join("telegram")
736            .join("neg100123")
737            .join("tmp")
738            .join(marker);
739        assert!(expected_marker.exists());
740
741        let _ = std::fs::remove_dir_all(&root);
742    }
743
744    #[test]
745    fn test_extract_env_files_from_input() {
746        let input = json!({
747            "command": "echo hi",
748            "__microclaw_auth": {
749                "caller_channel": "telegram",
750                "caller_chat_id": 1,
751                "control_chat_ids": [],
752                "env_files": [
753                    "/home/user/.microclaw/skills/outline/.env",
754                    "/home/user/.microclaw/skills/weather/.env"
755                ]
756            }
757        });
758        let files = extract_env_files(&input);
759        assert_eq!(files.len(), 2);
760        assert_eq!(
761            files[0],
762            PathBuf::from("/home/user/.microclaw/skills/outline/.env")
763        );
764    }
765
766    #[test]
767    fn test_extract_env_files_empty_when_absent() {
768        let input = json!({"command": "echo hi"});
769        let files = extract_env_files(&input);
770        assert!(files.is_empty());
771    }
772
773    #[tokio::test]
774    async fn test_bash_injects_env_files_into_execution() {
775        let root =
776            std::env::temp_dir().join(format!("microclaw_bash_env_{}", uuid::Uuid::new_v4()));
777        let work = root.join("workspace");
778        std::fs::create_dir_all(&work).unwrap();
779
780        let env_dir = root.join("skill_env");
781        std::fs::create_dir_all(&env_dir).unwrap();
782        let env_file = env_dir.join(".env");
783        std::fs::write(&env_file, "TEST_SKILL_VAR=skill_value_42\n").unwrap();
784
785        let tool = BashTool::new(work.to_str().unwrap());
786        let result = tool
787            .execute(json!({
788                "command": echo_env_command("TEST_SKILL_VAR"),
789                "__microclaw_auth": {
790                    "caller_channel": "telegram",
791                    "caller_chat_id": 1,
792                    "control_chat_ids": [],
793                    "env_files": [env_file.to_string_lossy()]
794                }
795            }))
796            .await;
797        assert!(!result.is_error);
798        assert!(
799            result.content.contains("[REDACTED:TEST_SKILL_VAR]"),
800            "expected redacted output, got: {}",
801            result.content
802        );
803        assert!(!result.content.contains("skill_value_42"));
804
805        let _ = std::fs::remove_dir_all(&root);
806    }
807
808    #[test]
809    fn test_redact_env_secrets_replaces_values() {
810        let dir = std::env::temp_dir().join(format!("microclaw_redact_{}", uuid::Uuid::new_v4()));
811        std::fs::create_dir_all(&dir).unwrap();
812        let env_file = dir.join(".env");
813        std::fs::write(&env_file, "API_KEY=supersecretkey123\nSHORT=ab\n").unwrap();
814
815        let output = "Response: supersecretkey123 is the key";
816        let redacted = redact_env_secrets(output, &[env_file]);
817        assert!(redacted.contains("[REDACTED:API_KEY]"));
818        assert!(!redacted.contains("supersecretkey123"));
819        assert!(!redacted.contains("[REDACTED:SHORT]"));
820
821        let _ = std::fs::remove_dir_all(&dir);
822    }
823
824    #[test]
825    fn test_redact_env_secrets_no_env_files() {
826        let output = "some output text";
827        let redacted = redact_env_secrets(output, &[]);
828        assert_eq!(redacted, output);
829    }
830
831    /// Writes a fake `rtk` binary that speaks the `rtk rewrite` exit-code
832    /// protocol: exit 0 + rewritten command for `echo original`, exit 3 (ask)
833    /// for `echo askme`, exit 0 + nonexistent binary for `echo fallback`,
834    /// exit 1 (no equivalent) for everything else.
835    #[cfg(unix)]
836    fn write_fake_rtk(dir: &Path) -> PathBuf {
837        use std::os::unix::fs::PermissionsExt;
838        let path = dir.join("rtk");
839        std::fs::write(
840            &path,
841            r#"#!/bin/sh
842[ "$1" = "rewrite" ] || exit 1
843case "$2" in
844  "echo original") echo "echo rewritten-by-rtk"; exit 0 ;;
845  "echo askme") echo "echo SHOULD-NOT-RUN"; exit 3 ;;
846  "echo fallback") echo "microclaw_test_no_such_binary_xyz"; exit 0 ;;
847  *) exit 1 ;;
848esac
849"#,
850        )
851        .unwrap();
852        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
853        path
854    }
855
856    #[cfg(unix)]
857    fn rtk_test_tool() -> (BashTool, PathBuf) {
858        let root = std::env::temp_dir().join(format!("microclaw_rtk_{}", uuid::Uuid::new_v4()));
859        std::fs::create_dir_all(&root).unwrap();
860        let fake_rtk = write_fake_rtk(&root);
861        let tool = BashTool::new(".").with_rtk(&RtkConfig {
862            enabled: true,
863            binary_path: fake_rtk.to_string_lossy().into_owned(),
864        });
865        (tool, root)
866    }
867
868    #[cfg(unix)]
869    #[tokio::test]
870    async fn test_rtk_rewrite_applied_when_enabled() {
871        let (tool, root) = rtk_test_tool();
872        let result = tool.execute(json!({"command": "echo original"})).await;
873        assert!(!result.is_error);
874        assert!(result.content.contains("rewritten-by-rtk"));
875        let _ = std::fs::remove_dir_all(&root);
876    }
877
878    #[cfg(unix)]
879    #[tokio::test]
880    async fn test_rtk_no_equivalent_runs_original() {
881        let (tool, root) = rtk_test_tool();
882        let result = tool.execute(json!({"command": "echo untouched"})).await;
883        assert!(!result.is_error);
884        assert!(result.content.contains("untouched"));
885        let _ = std::fs::remove_dir_all(&root);
886    }
887
888    #[cfg(unix)]
889    #[tokio::test]
890    async fn test_rtk_ask_rule_runs_original() {
891        let (tool, root) = rtk_test_tool();
892        let result = tool.execute(json!({"command": "echo askme"})).await;
893        assert!(!result.is_error);
894        assert!(result.content.contains("askme"));
895        assert!(!result.content.contains("SHOULD-NOT-RUN"));
896        let _ = std::fs::remove_dir_all(&root);
897    }
898
899    #[cfg(unix)]
900    #[tokio::test]
901    async fn test_rtk_falls_back_to_original_on_exit_127() {
902        let (tool, root) = rtk_test_tool();
903        let result = tool.execute(json!({"command": "echo fallback"})).await;
904        assert!(
905            !result.is_error,
906            "expected fallback retry, got: {}",
907            result.content
908        );
909        assert!(result.content.contains("fallback"));
910        let _ = std::fs::remove_dir_all(&root);
911    }
912
913    #[cfg(unix)]
914    #[tokio::test]
915    async fn test_rtk_missing_binary_runs_original() {
916        let tool = BashTool::new(".").with_rtk(&RtkConfig {
917            enabled: true,
918            binary_path: "/nonexistent/path/to/rtk".to_string(),
919        });
920        let result = tool.execute(json!({"command": "echo hello"})).await;
921        assert!(!result.is_error);
922        assert!(result.content.contains("hello"));
923    }
924
925    #[tokio::test]
926    async fn test_rtk_disabled_config_is_ignored() {
927        let tool = BashTool::new(".").with_rtk(&RtkConfig {
928            enabled: false,
929            binary_path: "/nonexistent/path/to/rtk".to_string(),
930        });
931        assert!(tool.rtk.is_none());
932    }
933
934    #[test]
935    fn test_command_accesses_dotenv_detection() {
936        assert!(command_accesses_dotenv("cat .env"));
937        assert!(command_accesses_dotenv("cat /path/to/.env.local"));
938        assert!(command_accesses_dotenv("source dotenv"));
939        assert!(!command_accesses_dotenv("echo hello"));
940        assert!(!command_accesses_dotenv("ls -la"));
941    }
942
943    #[tokio::test]
944    async fn test_bash_blocks_dotenv_access_when_env_files_active() {
945        let tool = BashTool::new(".");
946        let result = tool
947            .execute(json!({
948                "command": "cat .env",
949                "__microclaw_auth": {
950                    "caller_channel": "telegram",
951                    "caller_chat_id": 1,
952                    "control_chat_ids": [],
953                    "env_files": ["/some/skill/.env"]
954                }
955            }))
956            .await;
957        assert!(result.is_error);
958        assert_eq!(result.error_type.as_deref(), Some("env_access_blocked"));
959    }
960
961    #[tokio::test]
962    async fn test_bash_allows_dotenv_mention_without_env_files() {
963        let tool = BashTool::new(".");
964        let result = tool
965            .execute(json!({
966                "command": "echo .env is a file"
967            }))
968            .await;
969        assert!(!result.is_error);
970    }
971}