Skip to main content

vtcode_core/tools/
shell.rs

1//! High-level shell command runner and workspace utilities
2//!
3//! Provides workspace-safe shell operations (cd, ls, pwd, etc.) and
4//! handles platform-specific shell detection.
5//!
6//! ## Shell Snapshots
7//!
8//! This module integrates with the shell snapshot system to avoid re-running
9//! login scripts for every command. When a snapshot is available, commands
10//! can be executed with the cached environment, significantly improving
11//! startup time.
12
13use anyhow::{Context, Result, bail};
14use serde_json::{Value, json};
15use std::path::{Path, PathBuf};
16use std::process::Stdio;
17use tokio::process::Command;
18use tracing::debug;
19
20use crate::telemetry::perf;
21use crate::tools::command_cache::{InFlightState, cache_output, enter_inflight, finish_inflight, get_cached_output};
22use crate::utils::path::{canonicalize_workspace, ensure_path_within_workspace};
23use crate::utils::validation::validate_path_exists;
24
25use super::shell_snapshot::{ShellSnapshot, global_snapshot_manager};
26
27/// Represents a workspace-safe shell runner
28pub struct ShellRunner<E: CommandExecutor = SystemExecutor> {
29    workspace_root: PathBuf,
30    working_dir: PathBuf,
31    executor: E,
32}
33
34/// Trait for command execution strategies (async, string-command form).
35///
36/// See [`vtcode_bash_runner::CommandExecutor`] for the sync
37/// validated-invocation counterpart used by the bash-runner crate.
38#[async_trait::async_trait]
39pub trait CommandExecutor: Send + Sync {
40    /// Execute a command in the given directory
41    async fn execute(&self, command: &str, cwd: &Path) -> Result<ShellOutput>;
42}
43
44/// Standard system command executor.
45///
46/// Every launch clears the inherited environment and rebuilds it from an explicit
47/// map, so callers that already resolved the shared sandbox allowlist
48/// ([`crate::sandboxing::build_sanitized_env`]) hand it to the child instead of
49/// letting the shell inherit the full process environment.
50pub struct SystemExecutor {
51    shell: String,
52    env: hashbrown::HashMap<String, String>,
53}
54
55impl SystemExecutor {
56    /// Create an executor that launches commands with an already-sanitized environment.
57    pub fn with_env(env: hashbrown::HashMap<String, String>) -> Self {
58        Self { shell: resolve_fallback_shell(), env }
59    }
60}
61
62impl Default for SystemExecutor {
63    fn default() -> Self {
64        Self::with_env(crate::sandboxing::build_sanitized_env(
65            &std::env::vars().collect(),
66            true,
67            false,
68            "shell-runner",
69            &[],
70        ))
71    }
72}
73
74#[async_trait::async_trait]
75impl CommandExecutor for SystemExecutor {
76    async fn execute(&self, command_str: &str, cwd: &Path) -> Result<ShellOutput> {
77        let mut tags = hashbrown::HashMap::new();
78        tags.insert("subsystem".to_string(), "shell".to_string());
79        tags.insert("program".to_string(), self.shell.clone());
80        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);
81
82        let mut cmd = Command::new(&self.shell);
83        cmd.arg("-c")
84            .arg(command_str)
85            .current_dir(cwd)
86            .stdout(Stdio::piped())
87            .stderr(Stdio::piped());
88        cmd.env_clear().envs(&self.env);
89
90        let output = cmd.output().await?;
91
92        Ok(ShellOutput {
93            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
94            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
95            exit_code: output.status.code().unwrap_or(-1),
96        })
97    }
98}
99
100/// Executor that only logs commands without executing them
101pub struct DryRunExecutor {
102    pub log: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
103}
104
105impl Default for DryRunExecutor {
106    fn default() -> Self {
107        Self {
108            log: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
109        }
110    }
111}
112
113#[async_trait::async_trait]
114impl CommandExecutor for DryRunExecutor {
115    async fn execute(&self, command: &str, _cwd: &Path) -> Result<ShellOutput> {
116        let mut log = self
117            .log
118            .lock()
119            .map_err(|e| anyhow::anyhow!("DryRunExecutor log lock poisoned: {e}"))
120            .context("Failed to record dry-run command")?;
121        log.push(command.to_string());
122        Ok(ShellOutput {
123            stdout: format!("(dry-run) {command}"),
124            stderr: String::new(),
125            exit_code: 0,
126        })
127    }
128}
129
130/// Executor that uses shell snapshots for faster command execution.
131///
132/// This executor captures the shell environment once (after login scripts run)
133/// and reuses it for subsequent commands, avoiding the overhead of re-running
134/// login scripts for every command.
135pub struct SnapshotExecutor {
136    shell: String,
137    snapshot: Option<std::sync::Arc<ShellSnapshot>>,
138}
139
140impl SnapshotExecutor {
141    /// Create a new snapshot executor.
142    ///
143    /// The snapshot will be lazily captured on first command execution.
144    pub fn new() -> Self {
145        Self { shell: resolve_fallback_shell(), snapshot: None }
146    }
147
148    /// Create a snapshot executor with a pre-captured snapshot.
149    pub fn with_snapshot(snapshot: std::sync::Arc<ShellSnapshot>) -> Self {
150        Self {
151            shell: snapshot.shell_path.clone(),
152            snapshot: Some(snapshot),
153        }
154    }
155
156    /// Get or capture a shell snapshot.
157    async fn get_snapshot(&self) -> Result<std::sync::Arc<ShellSnapshot>> {
158        if let Some(ref snap) = self.snapshot {
159            return Ok(std::sync::Arc::clone(snap));
160        }
161        global_snapshot_manager().get_or_capture().await
162    }
163}
164
165impl Default for SnapshotExecutor {
166    fn default() -> Self {
167        Self::new()
168    }
169}
170
171#[async_trait::async_trait]
172impl CommandExecutor for SnapshotExecutor {
173    async fn execute(&self, command_str: &str, cwd: &Path) -> Result<ShellOutput> {
174        let snapshot = self.get_snapshot().await?;
175
176        let mut tags = hashbrown::HashMap::new();
177        tags.insert("subsystem".to_string(), "shell_snapshot".to_string());
178        tags.insert("program".to_string(), self.shell.clone());
179        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);
180
181        let mut cmd = Command::new(&self.shell);
182        cmd.arg("-c")
183            .arg(command_str)
184            .current_dir(cwd)
185            .stdout(Stdio::piped())
186            .stderr(Stdio::piped());
187
188        cmd.env_clear();
189        for (key, value) in &snapshot.env {
190            cmd.env(key, value);
191        }
192
193        debug!(
194            shell = %self.shell,
195            env_vars = snapshot.env.len(),
196            "Executing command with snapshot environment"
197        );
198
199        let output = cmd.output().await?;
200
201        Ok(ShellOutput {
202            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
203            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
204            exit_code: output.status.code().unwrap_or(-1),
205        })
206    }
207}
208
209impl ShellRunner<SystemExecutor> {
210    /// Create a new system shell runner anchored to the workspace root
211    pub fn new(workspace_root: PathBuf) -> Self {
212        let canonical_root = canonicalize_workspace(&workspace_root);
213        Self {
214            workspace_root: canonical_root.clone(),
215            working_dir: canonical_root,
216            executor: SystemExecutor::default(),
217        }
218    }
219}
220
221impl ShellRunner<SnapshotExecutor> {
222    /// Create a new shell runner that uses environment snapshots.
223    ///
224    /// This avoids re-running login scripts for every command by capturing
225    /// the shell environment once and reusing it.
226    pub fn with_snapshot(workspace_root: PathBuf) -> Self {
227        let canonical_root = canonicalize_workspace(&workspace_root);
228        Self {
229            workspace_root: canonical_root.clone(),
230            working_dir: canonical_root,
231            executor: SnapshotExecutor::new(),
232        }
233    }
234
235    /// Create a new shell runner with a pre-captured snapshot.
236    pub fn with_existing_snapshot(workspace_root: PathBuf, snapshot: std::sync::Arc<ShellSnapshot>) -> Self {
237        let canonical_root = canonicalize_workspace(&workspace_root);
238        Self {
239            workspace_root: canonical_root.clone(),
240            working_dir: canonical_root,
241            executor: SnapshotExecutor::with_snapshot(snapshot),
242        }
243    }
244}
245
246impl<E: CommandExecutor> ShellRunner<E> {
247    /// Create a new shell runner with a custom executor
248    pub fn with_executor(workspace_root: PathBuf, executor: E) -> Self {
249        let canonical_root = canonicalize_workspace(&workspace_root);
250        Self {
251            workspace_root: canonical_root.clone(),
252            working_dir: canonical_root,
253            executor,
254        }
255    }
256
257    /// Get current working directory relative to workspace root.
258    ///
259    /// Uses the shared renderer so a workspace reached through an alias
260    /// (`/var` vs macOS's `/private/var`) still yields a relative path instead
261    /// of falling back to the absolute one.
262    pub fn cwd_relative(&self) -> String {
263        vtcode_commons::workspace_relative_display(&self.workspace_root, &self.working_dir)
264    }
265
266    /// Change directory workspace-safely
267    pub fn cd(&mut self, path: &str) -> Result<()> {
268        let target = self.resolve_path(path);
269
270        // Single metadata call avoids TOCTOU between exists() and is_dir()
271        let meta = target
272            .metadata()
273            .map_err(|e| anyhow::anyhow!("directory `{path}` does not exist or is not accessible: {e}"))?;
274        if !meta.is_dir() {
275            bail!("path `{path}` is not a directory");
276        }
277
278        let normalized = ensure_path_within_workspace(&target, &self.workspace_root)?;
279
280        self.working_dir = normalized;
281        Ok(())
282    }
283
284    /// List directory contents (simplified version of ListDirHandler)
285    pub async fn ls(&self, path: Option<&str>) -> Result<Vec<Value>> {
286        let target = match path {
287            Some(p) => self.resolve_path(p),
288            None => self.working_dir.clone(),
289        };
290
291        validate_path_exists(&target, "path")?;
292        ensure_path_within_workspace(&target, &self.workspace_root)?;
293
294        let mut entries = Vec::new();
295        let mut read_dir = tokio::fs::read_dir(&target).await?;
296
297        while let Some(entry) = read_dir.next_entry().await? {
298            let metadata = entry.metadata().await?;
299            entries.push(json!({
300                "name": entry.file_name().to_string_lossy(),
301                "is_dir": metadata.is_dir(),
302                "size": metadata.len(),
303            }));
304        }
305
306        Ok(entries)
307    }
308
309    /// Execute a shell command in the current working directory
310    pub async fn exec(&self, command_str: &str) -> Result<ShellOutput> {
311        if let Some(cached) = get_cached_output(command_str, &self.working_dir) {
312            return Ok(cached);
313        }
314
315        let mut inflight_token = None;
316        if let Some(inflight) = enter_inflight(command_str, &self.working_dir).await {
317            match inflight {
318                InFlightState::Wait(receiver) => {
319                    if let Ok(result) = receiver.await {
320                        return result.map_err(|msg| anyhow::anyhow!(msg));
321                    }
322                }
323                InFlightState::Owner(token) => {
324                    inflight_token = Some(token);
325                }
326            }
327        }
328
329        let output = self.executor.execute(command_str, &self.working_dir).await;
330
331        if let Some(token) = inflight_token {
332            let result = output.as_ref().map(|out| out.clone()).map_err(|err| err.to_string());
333            finish_inflight(token, result).await;
334        }
335
336        let output = output?;
337        cache_output(command_str, &self.working_dir, output.clone());
338        Ok(output)
339    }
340
341    /// Resolve a path relative to current working directory
342    fn resolve_path(&self, path: &str) -> PathBuf {
343        let path = Path::new(path);
344        if path.is_absolute() {
345            path.to_path_buf()
346        } else {
347            self.working_dir.join(path)
348        }
349    }
350}
351
352/// Output from a shell command
353#[derive(Clone, Debug)]
354pub struct ShellOutput {
355    pub stdout: String,
356    pub stderr: String,
357    pub exit_code: i32,
358}
359
360impl ShellOutput {
361    /// Sanitize output to redact any secrets that may have been printed
362    ///
363    /// This should be called before displaying output in UI or writing to logs
364    pub fn sanitize_secrets(&self) -> Self {
365        Self {
366            stdout: vtcode_commons::sanitizer::redact_secrets(self.stdout.clone()),
367            stderr: vtcode_commons::sanitizer::redact_secrets(self.stderr.clone()),
368            exit_code: self.exit_code,
369        }
370    }
371}
372
373/// Resolve the fallback shell for command execution when program is not found.
374pub fn resolve_fallback_shell() -> String {
375    if let Ok(shell) = std::env::var("SHELL") {
376        let trimmed = shell.trim();
377        if !trimmed.is_empty() && Path::new(trimmed).exists() {
378            return trimmed.to_string();
379        }
380    }
381
382    const SHELL_CANDIDATES: &[&str] = &["/bin/bash", "/usr/bin/bash", "/bin/zsh", "/bin/sh"];
383
384    for shell_path in SHELL_CANDIDATES {
385        if Path::new(shell_path).exists() {
386            return shell_path.to_string();
387        }
388    }
389
390    "/bin/sh".to_string()
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[tokio::test]
398    async fn default_system_executor_runs_with_a_sanitized_environment() {
399        let root = tempfile::tempdir().unwrap();
400        let runner = ShellRunner::new(root.path().to_path_buf());
401
402        // The child must still run (PATH survives the allowlist) but must see the
403        // rebuilt environment rather than an inherited one.
404        let output = runner.exec("echo $VTCODE_SANDBOX_ACTIVE").await.unwrap();
405
406        assert_eq!(output.exit_code, 0, "{output:?}");
407        assert_eq!(output.stdout.trim(), "1", "{output:?}");
408    }
409}