1use 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
27pub struct ShellRunner<E: CommandExecutor = SystemExecutor> {
29 workspace_root: PathBuf,
30 working_dir: PathBuf,
31 executor: E,
32}
33
34#[async_trait::async_trait]
39pub trait CommandExecutor: Send + Sync {
40 async fn execute(&self, command: &str, cwd: &Path) -> Result<ShellOutput>;
42}
43
44pub struct SystemExecutor {
51 shell: String,
52 env: hashbrown::HashMap<String, String>,
53}
54
55impl SystemExecutor {
56 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
100pub 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
130pub struct SnapshotExecutor {
136 shell: String,
137 snapshot: Option<std::sync::Arc<ShellSnapshot>>,
138}
139
140impl SnapshotExecutor {
141 pub fn new() -> Self {
145 Self { shell: resolve_fallback_shell(), snapshot: None }
146 }
147
148 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 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 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 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 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 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 pub fn cwd_relative(&self) -> String {
263 vtcode_commons::workspace_relative_display(&self.workspace_root, &self.working_dir)
264 }
265
266 pub fn cd(&mut self, path: &str) -> Result<()> {
268 let target = self.resolve_path(path);
269
270 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 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 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 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#[derive(Clone, Debug)]
354pub struct ShellOutput {
355 pub stdout: String,
356 pub stderr: String,
357 pub exit_code: i32,
358}
359
360impl ShellOutput {
361 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
373pub 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 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}