1use anyhow::{Context, Result};
2#[cfg(any(not(feature = "powershell-process"), feature = "pure-rust"))]
3use anyhow::{anyhow, bail};
4#[cfg(feature = "pure-rust")]
5use std::path::Path;
6use std::path::PathBuf;
7
8#[cfg(feature = "exec-events")]
9use parking_lot::Mutex;
10#[cfg(feature = "serde-errors")]
11use serde::{Deserialize, Serialize};
12#[cfg(feature = "pure-rust")]
13use std::fs;
14#[cfg(feature = "exec-events")]
15use std::sync::atomic::{AtomicU64, Ordering};
16#[cfg(feature = "dry-run")]
17use std::sync::{Arc, Mutex as DryRunMutex};
18
19#[cfg(feature = "exec-events")]
20use vtcode_exec_events::{
21 CommandExecutionItem, CommandExecutionStatus, EventEmitter, ItemCompletedEvent, ItemStartedEvent, ThreadEvent,
22 ThreadItem, ThreadItemDetails,
23};
24
25#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum CommandCategory {
29 ChangeDirectory,
30 ListDirectory,
31 PrintDirectory,
32 CreateDirectory,
33 Remove,
34 Copy,
35 Move,
36 Search,
37}
38
39#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42pub enum ShellKind {
43 Unix,
44 Windows,
45}
46
47#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
49#[derive(Debug, Clone)]
50pub struct CommandInvocation {
51 shell: ShellKind,
52 pub command: String,
53 form: CommandForm,
54 pub(crate) category: CommandCategory,
55 pub(crate) working_dir: PathBuf,
56 pub(crate) touched_paths: Vec<PathBuf>,
57 #[cfg_attr(feature = "serde-errors", serde(default))]
58 pub(crate) create_parents: bool,
59 #[cfg_attr(feature = "serde-errors", serde(default))]
63 pub(crate) recursive: bool,
64 #[cfg_attr(feature = "serde-errors", serde(default))]
65 pub(crate) show_hidden: bool,
66}
67
68#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
69#[derive(Debug, Clone)]
70enum CommandForm {
71 DirectArgv(Vec<String>),
72 ValidatedShellScript(String),
73 Invalid(String),
74}
75
76impl CommandInvocation {
77 pub(crate) fn new(shell: ShellKind, command: String, category: CommandCategory, working_dir: PathBuf) -> Self {
78 let form = match shell {
79 ShellKind::Unix => match shell_words::split(&command) {
80 Ok(argv) if !argv.is_empty() => CommandForm::DirectArgv(argv),
81 Ok(_) => CommandForm::Invalid("direct command is empty".to_owned()),
82 Err(error) => CommandForm::Invalid(format!("direct command is not valid argv: {error}")),
83 },
84 ShellKind::Windows => CommandForm::ValidatedShellScript(command.clone()),
85 };
86 Self {
87 shell,
88 command,
89 form,
90 category,
91 working_dir,
92 touched_paths: Vec::new(),
93 create_parents: false,
94 recursive: false,
95 show_hidden: false,
96 }
97 }
98
99 pub(crate) fn with_paths(mut self, paths: Vec<PathBuf>) -> Self {
100 self.touched_paths = paths;
101 self
102 }
103
104 pub(crate) fn with_create_parents(mut self, create_parents: bool) -> Self {
105 self.create_parents = create_parents;
106 self
107 }
108
109 pub(crate) fn with_recursive(mut self, recursive: bool) -> Self {
110 self.recursive = recursive;
111 self
112 }
113
114 pub(crate) fn with_show_hidden(mut self, show_hidden: bool) -> Self {
115 self.show_hidden = show_hidden;
116 self
117 }
118}
119
120#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct CommandStatus {
124 success: bool,
125 code: Option<i32>,
126}
127
128impl CommandStatus {
129 pub(crate) fn new(success: bool, code: Option<i32>) -> Self {
130 Self { success, code }
131 }
132
133 pub(crate) fn success(&self) -> bool {
134 self.success
135 }
136
137 fn code(&self) -> Option<i32> {
138 self.code
139 }
140
141 #[cold]
142 pub fn failure(code: Option<i32>) -> Self {
143 Self { success: false, code }
144 }
145}
146
147impl From<std::process::ExitStatus> for CommandStatus {
148 fn from(status: std::process::ExitStatus) -> Self {
149 let code = status.code();
150 Self { success: status.success(), code }
151 }
152}
153
154#[cfg_attr(feature = "serde-errors", derive(Serialize, Deserialize))]
156#[derive(Debug, Clone)]
157pub struct CommandOutput {
158 pub(crate) status: CommandStatus,
159 pub(crate) stdout: String,
160 pub(crate) stderr: String,
161}
162
163impl CommandOutput {
164 fn success(stdout: impl Into<String>) -> Self {
165 Self {
166 status: CommandStatus::new(true, Some(0)),
167 stdout: stdout.into(),
168 stderr: String::new(),
169 }
170 }
171
172 pub fn failure(code: Option<i32>, stdout: impl Into<String>, stderr: impl Into<String>) -> Self {
173 Self {
174 status: CommandStatus::failure(code),
175 stdout: stdout.into(),
176 stderr: stderr.into(),
177 }
178 }
179}
180
181pub trait CommandExecutor: Send + Sync {
187 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput>;
188}
189
190#[cfg(feature = "std-process")]
192pub struct ProcessCommandExecutor;
193
194#[cfg(feature = "std-process")]
195impl ProcessCommandExecutor {
196 fn new() -> Self {
197 Self
198 }
199}
200
201#[cfg(feature = "std-process")]
202impl Default for ProcessCommandExecutor {
203 fn default() -> Self {
204 Self::new()
205 }
206}
207
208#[cfg(feature = "std-process")]
209impl CommandExecutor for ProcessCommandExecutor {
210 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput> {
211 use std::process::Command;
212
213 let mut cmd = match &invocation.form {
214 CommandForm::DirectArgv(argv) => {
215 let (program, args) = argv.split_first().context("direct command is missing executable")?;
216 let mut command = Command::new(program);
217 command.args(args);
218 command
219 }
220 CommandForm::ValidatedShellScript(script) if invocation.shell == ShellKind::Unix => {
221 let mut command = Command::new("sh");
222 command.arg("-c").arg(script);
223 command
224 }
225 CommandForm::ValidatedShellScript(script) => {
226 #[cfg(not(feature = "powershell-process"))]
227 {
228 bail!("powershell-process feature disabled; enable it to execute Windows commands");
229 }
230 #[cfg(feature = "powershell-process")]
231 let mut command = Command::new("powershell");
232 command.arg("-NoProfile").arg("-NonInteractive").arg("-Command").arg(script);
233 #[cfg(feature = "powershell-process")]
234 {
235 command
236 }
237 }
238 CommandForm::Invalid(message) => return Err(anyhow::Error::msg(message.clone())),
239 };
240
241 #[cfg(unix)]
242 {
243 let directory = vtcode_commons::fs::bound_file::open_directory_handle(&invocation.working_dir)
244 .with_context(|| format!("bind command working directory {}", invocation.working_dir.display()))?;
245 vtcode_commons::fs::bound_file::set_command_working_directory(&mut cmd, &directory)
246 .context("confine command working directory")?;
247 cmd.current_dir(&invocation.working_dir);
248 }
249 #[cfg(not(unix))]
250 cmd.current_dir(&invocation.working_dir);
251 let output = cmd
252 .output()
253 .with_context(|| format!("failed to execute command: {}", invocation.command))?;
254
255 Ok(CommandOutput {
256 status: CommandStatus::from(output.status),
257 stdout: String::from_utf8(output.stdout).unwrap_or_else(|e| e.to_string()),
258 stderr: String::from_utf8(output.stderr).unwrap_or_else(|e| e.to_string()),
259 })
260 }
261}
262
263#[cfg(feature = "dry-run")]
264#[derive(Clone, Default)]
265pub struct DryRunCommandExecutor {
266 log: Arc<DryRunMutex<Vec<CommandInvocation>>>,
267}
268
269#[cfg(feature = "dry-run")]
270impl DryRunCommandExecutor {
271 pub fn new() -> Self {
272 Self::default()
273 }
274
275 pub fn logged_invocations(&self) -> Vec<CommandInvocation> {
276 match self.log.lock() {
277 Ok(guard) => guard.clone(),
278 Err(poisoned) => poisoned.into_inner().clone(),
279 }
280 }
281}
282
283#[cfg(feature = "dry-run")]
284impl CommandExecutor for DryRunCommandExecutor {
285 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput> {
286 let mut guard = match self.log.lock() {
287 Ok(guard) => guard,
288 Err(poisoned) => poisoned.into_inner(),
289 };
290 guard.push(invocation.clone());
291 Ok(match invocation.category {
292 CommandCategory::ListDirectory => CommandOutput::success("(dry-run listing)"),
293 _ => CommandOutput::success(String::new()),
294 })
295 }
296}
297
298#[cfg(feature = "pure-rust")]
299#[derive(Debug, Default, Clone, Copy)]
300pub struct PureRustCommandExecutor;
301
302#[cfg(feature = "pure-rust")]
303impl PureRustCommandExecutor {
304 fn resolve_primary_path(invocation: &CommandInvocation) -> Result<&PathBuf> {
305 invocation
306 .touched_paths
307 .first()
308 .ok_or_else(|| anyhow!("invocation missing target path"))
309 }
310
311 fn mkdir(path: &Path, create_parents: bool) -> Result<()> {
312 if create_parents {
313 fs::create_dir_all(path).with_context(|| format!("failed to create directory `{}`", path.display()))?
314 } else {
315 fs::create_dir(path).with_context(|| format!("failed to create directory `{}`", path.display()))?
316 }
317 Ok(())
318 }
319
320 fn rm(path: &Path, recursive: bool) -> Result<()> {
321 if path.is_dir() {
322 if recursive {
323 fs::remove_dir_all(path).with_context(|| format!("failed to remove directory `{}`", path.display()))?
324 } else {
325 fs::remove_dir(path).with_context(|| format!("failed to remove directory `{}`", path.display()))?
326 }
327 } else if path.exists() {
328 fs::remove_file(path).with_context(|| format!("failed to remove file `{}`", path.display()))?
329 }
330 Ok(())
331 }
332
333 fn copy_recursive(source: &Path, dest: &Path, recursive: bool) -> Result<()> {
334 let canonical_source = vtcode_commons::canonicalize(source)
335 .with_context(|| format!("failed to resolve copy source `{}`", source.display()))?;
336 if !canonical_source.is_dir() {
337 return Self::copy_single_file(&canonical_source, dest);
338 }
339 if !recursive {
340 bail!("copying directory `{}` requires recursive flag", source.display());
341 }
342 fs::create_dir_all(dest).with_context(|| format!("failed to create directory `{}`", dest.display()))?;
343 let canonical_dest = vtcode_commons::canonicalize(dest)
344 .with_context(|| format!("failed to resolve copy destination `{}`", dest.display()))?;
345 Self::copy_dir_anchored(&canonical_source, &canonical_source, &canonical_dest, &canonical_dest)
346 }
347
348 fn copy_dir_anchored(source_dir: &Path, source_anchor: &Path, dest_dir: &Path, dest_anchor: &Path) -> Result<()> {
361 for entry in
362 fs::read_dir(source_dir).with_context(|| format!("failed to read directory `{}`", source_dir.display()))?
363 {
364 let entry = entry?;
365 let canonical_entry = vtcode_commons::canonicalize(entry.path())
366 .with_context(|| format!("failed to resolve `{}`", entry.path().display()))?;
367 if !canonical_entry.starts_with(source_anchor) {
368 bail!(
369 "refusing to copy through symlink `{}` escaping `{}`",
370 entry.path().display(),
371 source_anchor.display()
372 );
373 }
374 let dest_path = dest_dir.join(entry.file_name());
375 Self::reject_escaping_destination_link(&dest_path, dest_anchor)?;
376 if canonical_entry.is_dir() {
377 fs::create_dir_all(&dest_path)
378 .with_context(|| format!("failed to create directory `{}`", dest_path.display()))?;
379 let canonical_dest_subdir = vtcode_commons::canonicalize(&dest_path)
382 .with_context(|| format!("failed to resolve `{}`", dest_path.display()))?;
383 if !canonical_dest_subdir.starts_with(dest_anchor) {
384 bail!("refusing to copy into `{}` escaping `{}`", dest_path.display(), dest_anchor.display());
385 }
386 Self::copy_dir_anchored(&canonical_entry, source_anchor, &canonical_dest_subdir, dest_anchor)?;
387 } else {
388 Self::copy_file(&canonical_entry, &dest_path)?;
389 }
390 }
391 Ok(())
392 }
393
394 fn copy_single_file(canonical_source: &Path, dest: &Path) -> Result<()> {
397 if let Some(parent) = dest.parent() {
398 fs::create_dir_all(parent)
399 .with_context(|| format!("failed to prepare destination directory `{}`", parent.display()))?;
400 let canonical_parent = vtcode_commons::canonicalize(parent)
401 .with_context(|| format!("failed to resolve `{}`", parent.display()))?;
402 Self::reject_escaping_destination_link(dest, &canonical_parent)?;
403 }
404 Self::copy_file(canonical_source, dest)
405 }
406
407 fn reject_escaping_destination_link(dest: &Path, dest_anchor: &Path) -> Result<()> {
412 if fs::symlink_metadata(dest).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
413 let canonical_dest = vtcode_commons::canonicalize(dest)
414 .with_context(|| format!("failed to resolve destination `{}`", dest.display()))?;
415 if !canonical_dest.starts_with(dest_anchor) {
416 bail!(
417 "refusing to copy through destination symlink `{}` escaping `{}`",
418 dest.display(),
419 dest_anchor.display()
420 );
421 }
422 }
423 Ok(())
424 }
425
426 fn copy_file(source: &Path, dest: &Path) -> Result<()> {
427 if let Some(parent) = dest.parent() {
428 fs::create_dir_all(parent)
429 .with_context(|| format!("failed to prepare destination directory `{}`", parent.display()))?;
430 }
431 fs::copy(source, dest)
432 .with_context(|| format!("failed to copy `{}` to `{}`", source.display(), dest.display()))?;
433 Ok(())
434 }
435
436 fn move_path(source: &Path, dest: &Path) -> Result<()> {
437 if let Some(parent) = dest.parent() {
438 fs::create_dir_all(parent)
439 .with_context(|| format!("failed to prepare destination directory `{}`", parent.display()))?;
440 }
441
442 if let Err(rename_err) = fs::rename(source, dest) {
443 Self::copy_recursive(source, dest, true)
444 .and_then(|_| Self::rm(source, true))
445 .with_context(|| {
446 format!("failed to move `{}` to `{}` via rename: {rename_err}", source.display(), dest.display())
447 })?;
448 }
449 Ok(())
450 }
451}
452
453#[cfg(feature = "pure-rust")]
454impl CommandExecutor for PureRustCommandExecutor {
455 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput> {
456 match invocation.category {
457 CommandCategory::ListDirectory => {
458 let path = Self::resolve_primary_path(invocation)?;
459 let mut entries = Vec::new();
460 for entry in
461 fs::read_dir(path).with_context(|| format!("failed to read directory `{}`", path.display()))?
462 {
463 let entry = entry?;
464 let name = entry.file_name();
465 let name = name.to_string_lossy();
466 if !invocation.show_hidden && name.starts_with('.') {
467 continue;
468 }
469 entries.push(name.to_string());
470 }
471 entries.sort();
472 Ok(CommandOutput::success(entries.join("\n")))
473 }
474 CommandCategory::CreateDirectory => {
475 let path = Self::resolve_primary_path(invocation)?;
476 Self::mkdir(path, invocation.create_parents)?;
477 Ok(CommandOutput::success(String::new()))
478 }
479 CommandCategory::Remove => {
480 let path = Self::resolve_primary_path(invocation)?;
481 Self::rm(path, invocation.recursive)?;
482 Ok(CommandOutput::success(String::new()))
483 }
484 CommandCategory::Copy => {
485 let source = invocation
486 .touched_paths
487 .first()
488 .ok_or_else(|| anyhow!("copy missing source path"))?;
489 let dest = invocation
490 .touched_paths
491 .get(1)
492 .ok_or_else(|| anyhow!("copy missing destination path"))?;
493 Self::copy_recursive(source.as_path(), dest.as_path(), invocation.recursive)?;
494 Ok(CommandOutput::success(String::new()))
495 }
496 CommandCategory::Move => {
497 let source = invocation
498 .touched_paths
499 .first()
500 .ok_or_else(|| anyhow!("move missing source path"))?;
501 let dest = invocation
502 .touched_paths
503 .get(1)
504 .ok_or_else(|| anyhow!("move missing destination path"))?;
505 Self::move_path(source.as_path(), dest.as_path())?;
506 Ok(CommandOutput::success(String::new()))
507 }
508 CommandCategory::Search => {
509 bail!("pure-rust executor does not implement search; enable std-process or provide a custom executor")
510 }
511 CommandCategory::ChangeDirectory | CommandCategory::PrintDirectory => {
512 Ok(CommandOutput::success(String::new()))
513 }
514 }
515 }
516}
517
518#[cfg(feature = "exec-events")]
519#[derive(Debug)]
520pub struct EventfulExecutor<E, T> {
521 inner: E,
522 emitter: Mutex<T>,
523 counter: AtomicU64,
524 id_prefix: String,
525}
526
527#[cfg(feature = "exec-events")]
528impl<E, T> EventfulExecutor<E, T>
529where
530 T: EventEmitter,
531{
532 pub fn new(inner: E, emitter: T) -> Self {
533 Self {
534 inner,
535 emitter: Mutex::new(emitter),
536 counter: AtomicU64::new(0),
537 id_prefix: "cmd-".to_string(),
538 }
539 }
540
541 pub fn with_id_prefix(inner: E, emitter: T, prefix: impl Into<String>) -> Self {
542 let mut executor = Self::new(inner, emitter);
543 executor.id_prefix = prefix.into();
544 executor
545 }
546
547 fn next_id(&self) -> String {
548 let value = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
549 let mut id = String::with_capacity(self.id_prefix.len() + 10);
550 id.push_str(&self.id_prefix);
551 use std::fmt::Write;
552 let _ = write!(id, "{value}");
553 id
554 }
555
556 fn emit_event(&self, event: ThreadEvent) {
557 let mut emitter = self.emitter.lock();
558 EventEmitter::emit(&mut *emitter, &event);
559 }
560
561 fn command_details(
562 &self,
563 invocation: &CommandInvocation,
564 status: CommandExecutionStatus,
565 output: Option<&CommandOutput>,
566 error: Option<&anyhow::Error>,
567 ) -> CommandExecutionItem {
568 let aggregated_output = if let Some(output) = output {
569 aggregate_output(output)
570 } else if let Some(err) = error {
571 err.to_string()
572 } else {
573 String::new()
574 };
575
576 CommandExecutionItem {
577 command: invocation.command.clone(),
578 arguments: None,
579 aggregated_output,
580 exit_code: output.and_then(|out| out.status.code()),
581 status,
582 }
583 }
584}
585
586#[cfg(feature = "exec-events")]
587impl<E, T> CommandExecutor for EventfulExecutor<E, T>
588where
589 E: CommandExecutor,
590 T: EventEmitter + Send,
591{
592 fn execute(&self, invocation: &CommandInvocation) -> Result<CommandOutput> {
593 let item_id = self.next_id();
594 let starting_item = ThreadItem {
595 context: None,
596 id: item_id.clone(),
597 details: ThreadItemDetails::CommandExecution(Box::new(self.command_details(
598 invocation,
599 CommandExecutionStatus::InProgress,
600 None,
601 None,
602 ))),
603 };
604 self.emit_event(ThreadEvent::ItemStarted(ItemStartedEvent { item: starting_item }));
605
606 match self.inner.execute(invocation) {
607 Ok(output) => {
608 let status = if output.status.success() {
609 CommandExecutionStatus::Completed
610 } else {
611 CommandExecutionStatus::Failed
612 };
613
614 let completed_item = ThreadItem {
615 context: None,
616 id: item_id,
617 details: ThreadItemDetails::CommandExecution(Box::new(self.command_details(
618 invocation,
619 status,
620 Some(&output),
621 None,
622 ))),
623 };
624 self.emit_event(ThreadEvent::ItemCompleted(ItemCompletedEvent { item: completed_item }));
625 Ok(output)
626 }
627 Err(err) => {
628 let failure = ThreadItem {
629 context: None,
630 id: item_id,
631 details: ThreadItemDetails::CommandExecution(Box::new(self.command_details(
632 invocation,
633 CommandExecutionStatus::Failed,
634 None,
635 Some(&err),
636 ))),
637 };
638 self.emit_event(ThreadEvent::ItemCompleted(ItemCompletedEvent { item: failure }));
639 Err(err)
640 }
641 }
642 }
643}
644
645#[cfg(feature = "exec-events")]
646fn aggregate_output(output: &CommandOutput) -> String {
647 let mut combined = String::new();
648 if !output.stdout.trim().is_empty() {
649 combined.push_str(output.stdout.trim());
650 }
651 if !output.stderr.trim().is_empty() {
652 if !combined.is_empty() {
653 combined.push('\n');
654 }
655 combined.push_str(output.stderr.trim());
656 }
657 combined
658}
659
660#[cfg(all(test, feature = "serde-errors"))]
661mod serde_tests {
662 use super::{CommandForm, CommandInvocation, CommandOutput, CommandStatus};
663 use serde::Serialize;
664 use serde::de::DeserializeOwned;
665
666 fn assert_serde<T: Serialize + DeserializeOwned>() {}
670
671 #[test]
676 fn serde_error_types_satisfy_serialize_and_deserialize() {
677 assert_serde::<CommandInvocation>();
678 assert_serde::<CommandForm>();
679 assert_serde::<CommandOutput>();
680 assert_serde::<CommandStatus>();
681 }
682}