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