vtcode-core 0.179.5

Core library for VT Code - a Rust-based terminal coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! High-level shell command runner and workspace utilities
//!
//! Provides workspace-safe shell operations (cd, ls, pwd, etc.) and
//! handles platform-specific shell detection.
//!
//! ## Shell Snapshots
//!
//! This module integrates with the shell snapshot system to avoid re-running
//! login scripts for every command. When a snapshot is available, commands
//! can be executed with the cached environment, significantly improving
//! startup time.

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::process::Command;
use tracing::debug;

use crate::telemetry::perf;
use crate::tools::command_cache::{InFlightState, cache_output, enter_inflight, finish_inflight, get_cached_output};
use crate::utils::path::{canonicalize_workspace, ensure_path_within_workspace};
use crate::utils::validation::validate_path_exists;

use super::shell_snapshot::{ShellSnapshot, global_snapshot_manager};

/// Represents a workspace-safe shell runner
pub struct ShellRunner<E: CommandExecutor = SystemExecutor> {
    workspace_root: PathBuf,
    working_dir: PathBuf,
    executor: E,
}

/// Trait for command execution strategies
#[async_trait::async_trait]
pub trait CommandExecutor: Send + Sync {
    /// Execute a command in the given directory
    async fn execute(&self, command: &str, cwd: &Path) -> Result<ShellOutput>;
}

/// Standard system command executor.
///
/// Every launch clears the inherited environment and rebuilds it from an explicit
/// map, so callers that already resolved the shared sandbox allowlist
/// ([`crate::sandboxing::build_sanitized_env`]) hand it to the child instead of
/// letting the shell inherit the full process environment.
pub struct SystemExecutor {
    shell: String,
    env: hashbrown::HashMap<String, String>,
}

impl SystemExecutor {
    /// Create an executor that launches commands with an already-sanitized environment.
    pub fn with_env(env: hashbrown::HashMap<String, String>) -> Self {
        Self { shell: resolve_fallback_shell(), env }
    }
}

impl Default for SystemExecutor {
    fn default() -> Self {
        Self::with_env(crate::sandboxing::build_sanitized_env(
            &std::env::vars().collect(),
            true,
            false,
            "shell-runner",
            &[],
        ))
    }
}

#[async_trait::async_trait]
impl CommandExecutor for SystemExecutor {
    async fn execute(&self, command_str: &str, cwd: &Path) -> Result<ShellOutput> {
        let mut tags = hashbrown::HashMap::new();
        tags.insert("subsystem".to_string(), "shell".to_string());
        tags.insert("program".to_string(), self.shell.clone());
        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);

        let mut cmd = Command::new(&self.shell);
        cmd.arg("-c")
            .arg(command_str)
            .current_dir(cwd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        cmd.env_clear().envs(&self.env);

        let output = cmd.output().await?;

        Ok(ShellOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            exit_code: output.status.code().unwrap_or(-1),
        })
    }
}

/// Executor that only logs commands without executing them
pub struct DryRunExecutor {
    pub log: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
}

impl Default for DryRunExecutor {
    fn default() -> Self {
        Self {
            log: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }
}

#[async_trait::async_trait]
impl CommandExecutor for DryRunExecutor {
    async fn execute(&self, command: &str, _cwd: &Path) -> Result<ShellOutput> {
        let mut log = self
            .log
            .lock()
            .map_err(|e| anyhow::anyhow!("DryRunExecutor log lock poisoned: {e}"))
            .context("Failed to record dry-run command")?;
        log.push(command.to_string());
        Ok(ShellOutput {
            stdout: format!("(dry-run) {command}"),
            stderr: String::new(),
            exit_code: 0,
        })
    }
}

/// Executor that uses shell snapshots for faster command execution.
///
/// This executor captures the shell environment once (after login scripts run)
/// and reuses it for subsequent commands, avoiding the overhead of re-running
/// login scripts for every command.
pub struct SnapshotExecutor {
    shell: String,
    snapshot: Option<std::sync::Arc<ShellSnapshot>>,
}

impl SnapshotExecutor {
    /// Create a new snapshot executor.
    ///
    /// The snapshot will be lazily captured on first command execution.
    pub fn new() -> Self {
        Self { shell: resolve_fallback_shell(), snapshot: None }
    }

    /// Create a snapshot executor with a pre-captured snapshot.
    pub fn with_snapshot(snapshot: std::sync::Arc<ShellSnapshot>) -> Self {
        Self {
            shell: snapshot.shell_path.clone(),
            snapshot: Some(snapshot),
        }
    }

    /// Get or capture a shell snapshot.
    async fn get_snapshot(&self) -> Result<std::sync::Arc<ShellSnapshot>> {
        if let Some(ref snap) = self.snapshot {
            return Ok(std::sync::Arc::clone(snap));
        }
        global_snapshot_manager().get_or_capture().await
    }
}

impl Default for SnapshotExecutor {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl CommandExecutor for SnapshotExecutor {
    async fn execute(&self, command_str: &str, cwd: &Path) -> Result<ShellOutput> {
        let snapshot = self.get_snapshot().await?;

        let mut tags = hashbrown::HashMap::new();
        tags.insert("subsystem".to_string(), "shell_snapshot".to_string());
        tags.insert("program".to_string(), self.shell.clone());
        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);

        let mut cmd = Command::new(&self.shell);
        cmd.arg("-c")
            .arg(command_str)
            .current_dir(cwd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        cmd.env_clear();
        for (key, value) in &snapshot.env {
            cmd.env(key, value);
        }

        debug!(
            shell = %self.shell,
            env_vars = snapshot.env.len(),
            "Executing command with snapshot environment"
        );

        let output = cmd.output().await?;

        Ok(ShellOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            exit_code: output.status.code().unwrap_or(-1),
        })
    }
}

impl ShellRunner<SystemExecutor> {
    /// Create a new system shell runner anchored to the workspace root
    pub fn new(workspace_root: PathBuf) -> Self {
        let canonical_root = canonicalize_workspace(&workspace_root);
        Self {
            workspace_root: canonical_root.clone(),
            working_dir: canonical_root,
            executor: SystemExecutor::default(),
        }
    }
}

impl ShellRunner<SnapshotExecutor> {
    /// Create a new shell runner that uses environment snapshots.
    ///
    /// This avoids re-running login scripts for every command by capturing
    /// the shell environment once and reusing it.
    pub fn with_snapshot(workspace_root: PathBuf) -> Self {
        let canonical_root = canonicalize_workspace(&workspace_root);
        Self {
            workspace_root: canonical_root.clone(),
            working_dir: canonical_root,
            executor: SnapshotExecutor::new(),
        }
    }

    /// Create a new shell runner with a pre-captured snapshot.
    pub fn with_existing_snapshot(workspace_root: PathBuf, snapshot: std::sync::Arc<ShellSnapshot>) -> Self {
        let canonical_root = canonicalize_workspace(&workspace_root);
        Self {
            workspace_root: canonical_root.clone(),
            working_dir: canonical_root,
            executor: SnapshotExecutor::with_snapshot(snapshot),
        }
    }
}

impl<E: CommandExecutor> ShellRunner<E> {
    /// Create a new shell runner with a custom executor
    pub fn with_executor(workspace_root: PathBuf, executor: E) -> Self {
        let canonical_root = canonicalize_workspace(&workspace_root);
        Self {
            workspace_root: canonical_root.clone(),
            working_dir: canonical_root,
            executor,
        }
    }

    /// Get current working directory relative to workspace root
    pub fn cwd_relative(&self) -> String {
        self.working_dir
            .strip_prefix(&self.workspace_root)
            .unwrap_or(&self.working_dir)
            .to_string_lossy()
            .into_owned()
    }

    /// Change directory workspace-safely
    pub fn cd(&mut self, path: &str) -> Result<()> {
        let target = self.resolve_path(path);

        // Single metadata call avoids TOCTOU between exists() and is_dir()
        let meta = target
            .metadata()
            .map_err(|e| anyhow::anyhow!("directory `{path}` does not exist or is not accessible: {e}"))?;
        if !meta.is_dir() {
            bail!("path `{path}` is not a directory");
        }

        let normalized = ensure_path_within_workspace(&target, &self.workspace_root)?;

        self.working_dir = normalized;
        Ok(())
    }

    /// List directory contents (simplified version of ListDirHandler)
    pub async fn ls(&self, path: Option<&str>) -> Result<Vec<Value>> {
        let target = match path {
            Some(p) => self.resolve_path(p),
            None => self.working_dir.clone(),
        };

        validate_path_exists(&target, "path")?;
        ensure_path_within_workspace(&target, &self.workspace_root)?;

        let mut entries = Vec::new();
        let mut read_dir = tokio::fs::read_dir(&target).await?;

        while let Some(entry) = read_dir.next_entry().await? {
            let metadata = entry.metadata().await?;
            entries.push(json!({
                "name": entry.file_name().to_string_lossy(),
                "is_dir": metadata.is_dir(),
                "size": metadata.len(),
            }));
        }

        Ok(entries)
    }

    /// Execute a shell command in the current working directory
    pub async fn exec(&self, command_str: &str) -> Result<ShellOutput> {
        if let Some(cached) = get_cached_output(command_str, &self.working_dir) {
            return Ok(cached);
        }

        let mut inflight_token = None;
        if let Some(inflight) = enter_inflight(command_str, &self.working_dir).await {
            match inflight {
                InFlightState::Wait(receiver) => {
                    if let Ok(result) = receiver.await {
                        return result.map_err(|msg| anyhow::anyhow!(msg));
                    }
                }
                InFlightState::Owner(token) => {
                    inflight_token = Some(token);
                }
            }
        }

        let output = self.executor.execute(command_str, &self.working_dir).await;

        if let Some(token) = inflight_token {
            let result = output.as_ref().map(|out| out.clone()).map_err(|err| err.to_string());
            finish_inflight(token, result).await;
        }

        let output = output?;
        cache_output(command_str, &self.working_dir, output.clone());
        Ok(output)
    }

    /// Resolve a path relative to current working directory
    fn resolve_path(&self, path: &str) -> PathBuf {
        let path = Path::new(path);
        if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.working_dir.join(path)
        }
    }
}

/// Output from a shell command
#[derive(Clone, Debug)]
pub struct ShellOutput {
    pub stdout: String,
    pub stderr: String,
    pub exit_code: i32,
}

impl ShellOutput {
    /// Sanitize output to redact any secrets that may have been printed
    ///
    /// This should be called before displaying output in UI or writing to logs
    pub fn sanitize_secrets(&self) -> Self {
        Self {
            stdout: vtcode_commons::sanitizer::redact_secrets(self.stdout.clone()),
            stderr: vtcode_commons::sanitizer::redact_secrets(self.stderr.clone()),
            exit_code: self.exit_code,
        }
    }
}

/// Resolve the fallback shell for command execution when program is not found.
pub fn resolve_fallback_shell() -> String {
    if let Ok(shell) = std::env::var("SHELL") {
        let trimmed = shell.trim();
        if !trimmed.is_empty() && Path::new(trimmed).exists() {
            return trimmed.to_string();
        }
    }

    const SHELL_CANDIDATES: &[&str] = &["/bin/bash", "/usr/bin/bash", "/bin/zsh", "/bin/sh"];

    for shell_path in SHELL_CANDIDATES {
        if Path::new(shell_path).exists() {
            return shell_path.to_string();
        }
    }

    "/bin/sh".to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn default_system_executor_runs_with_a_sanitized_environment() {
        let root = tempfile::tempdir().unwrap();
        let runner = ShellRunner::new(root.path().to_path_buf());

        // The child must still run (PATH survives the allowlist) but must see the
        // rebuilt environment rather than an inherited one.
        let output = runner.exec("echo $VTCODE_SANDBOX_ACTIVE").await.unwrap();

        assert_eq!(output.exit_code, 0, "{output:?}");
        assert_eq!(output.stdout.trim(), "1", "{output:?}");
    }
}