1use std::collections::BTreeMap;
9use std::ffi::OsStr;
10use std::path::{Component, Path, PathBuf};
11use std::time::{Duration, Instant, SystemTime};
12
13use async_trait::async_trait;
14use tokio::process::{Child, ChildStderr, ChildStdout};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum BackendKind {
18 Local,
19 Docker,
20 Ssh,
21}
22
23impl BackendKind {
24 pub fn as_str(self) -> &'static str {
25 match self {
26 Self::Local => "local",
27 Self::Docker => "docker",
28 Self::Ssh => "ssh",
29 }
30 }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash)]
36pub struct BackendPath(String);
37
38impl BackendPath {
39 pub fn new(path: impl Into<String>) -> Self {
40 Self(path.into())
41 }
42
43 pub fn is_anchored(path: &str) -> bool {
47 path == "~" || path.starts_with("~/") || Self::is_absolute(path)
48 }
49
50 pub fn is_absolute(path: impl AsRef<str>) -> bool {
54 let path = path.as_ref();
55 let bytes = path.as_bytes();
56 path.starts_with('/')
57 || path.starts_with("\\\\")
58 || (bytes.len() >= 3
59 && bytes[0].is_ascii_alphabetic()
60 && bytes[1] == b':'
61 && matches!(bytes[2], b'\\' | b'/'))
62 }
63
64 pub fn as_str(&self) -> &str {
65 &self.0
66 }
67
68 pub fn display(&self) -> &str {
69 &self.0
70 }
71
72 pub fn join(&self, child: impl AsRef<str>) -> Self {
73 let child = child.as_ref();
74 if child.is_empty() {
75 return self.clone();
76 }
77 if self.0.starts_with('/') {
78 if child.starts_with('/') {
79 return Self(child.to_string());
80 }
81 return Self(format!(
82 "{}/{}",
83 self.0.trim_end_matches('/'),
84 child.trim_start_matches('/')
85 ));
86 }
87 let mut path = PathBuf::from(&self.0);
88 path.push(child);
89 Self(path.to_string_lossy().into_owned())
90 }
91
92 pub fn parent(&self) -> Option<Self> {
93 if self.0.starts_with('/') {
94 let trimmed = self.0.trim_end_matches('/');
95 if trimmed.is_empty() {
96 return None;
97 }
98 let (parent, _) = trimmed.rsplit_once('/')?;
99 return Some(Self(if parent.is_empty() {
100 "/".to_string()
101 } else {
102 parent.to_string()
103 }));
104 }
105 Path::new(&self.0)
106 .parent()
107 .map(|path| Self(path.to_string_lossy().into_owned()))
108 }
109
110 pub fn file_name(&self) -> Option<&str> {
111 if self.0.starts_with('/') {
112 return self
113 .0
114 .trim_end_matches('/')
115 .rsplit('/')
116 .next()
117 .filter(|name| !name.is_empty());
118 }
119 Path::new(&self.0).file_name().and_then(OsStr::to_str)
120 }
121
122 pub fn extension(&self) -> Option<&str> {
123 if self.0.starts_with('/') {
124 return self
125 .file_name()?
126 .rsplit_once('.')
127 .and_then(|(stem, extension)| {
128 (!stem.is_empty() && !extension.is_empty()).then_some(extension)
129 });
130 }
131 Path::new(&self.0).extension().and_then(OsStr::to_str)
132 }
133
134 pub fn with_extension(&self, extension: &str) -> Self {
135 if self.0.starts_with('/') {
136 let file_name = self.file_name().unwrap_or_default();
137 let stem = file_name
138 .rsplit_once('.')
139 .map_or(file_name, |(stem, _)| stem);
140 let replacement = if extension.is_empty() {
141 stem.to_string()
142 } else {
143 format!("{stem}.{extension}")
144 };
145 return if let Some(parent) = self.parent() {
146 parent.join(&replacement)
147 } else {
148 Self(replacement)
149 };
150 }
151 let mut path = PathBuf::from(&self.0);
152 path.set_extension(extension);
153 Self(path.to_string_lossy().into_owned())
154 }
155}
156
157impl std::fmt::Display for BackendPath {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 self.0.fmt(f)
160 }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum BackendFileType {
165 File,
166 Directory,
167 Symlink,
168 Other,
169}
170
171#[derive(Debug, Clone)]
172pub struct BackendMetadata {
173 pub file_type: BackendFileType,
174 pub len: u64,
175 pub modified: Option<SystemTime>,
176}
177
178impl BackendMetadata {
179 pub fn is_file(&self) -> bool {
180 self.file_type == BackendFileType::File
181 }
182
183 pub fn is_dir(&self) -> bool {
184 self.file_type == BackendFileType::Directory
185 }
186}
187
188#[derive(Debug, Clone)]
189pub struct BackendDirEntry {
190 pub path: BackendPath,
191 pub metadata: BackendMetadata,
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum WriteMode {
196 Overwrite,
197 Append,
198}
199
200#[derive(Debug, Clone)]
201pub enum CommandSpec {
202 Shell(String),
203 Argv { program: String, args: Vec<String> },
204}
205
206impl CommandSpec {
207 pub fn as_posix_shell(&self) -> String {
208 match self {
209 Self::Shell(command) => command.clone(),
210 Self::Argv { program, args } => std::iter::once(program.as_str())
211 .chain(args.iter().map(String::as_str))
212 .map(shell_quote)
213 .collect::<Vec<_>>()
214 .join(" "),
215 }
216 }
217}
218
219#[derive(Debug, Clone)]
220pub struct ExecutionRequest {
221 pub command: CommandSpec,
222 pub cwd: Option<BackendPath>,
223 pub env: BTreeMap<String, String>,
224 pub env_remove: Vec<String>,
225 pub stdin: Option<Vec<u8>>,
226 pub keep_stdin: bool,
231}
232
233impl ExecutionRequest {
234 pub fn shell(command: impl Into<String>) -> Self {
235 Self {
236 command: CommandSpec::Shell(command.into()),
237 cwd: None,
238 env: BTreeMap::new(),
239 env_remove: Vec::new(),
240 stdin: None,
241 keep_stdin: false,
242 }
243 }
244
245 pub fn argv(program: impl Into<String>, args: Vec<String>) -> Self {
246 Self {
247 command: CommandSpec::Argv {
248 program: program.into(),
249 args,
250 },
251 cwd: None,
252 env: BTreeMap::new(),
253 env_remove: Vec::new(),
254 stdin: None,
255 keep_stdin: false,
256 }
257 }
258}
259
260#[derive(Debug)]
261pub struct ExecutionOutput {
262 pub exit_code: i32,
263 pub stdout: Vec<u8>,
264 pub stderr: Vec<u8>,
265 pub duration_ms: u64,
266 pub timed_out: bool,
267}
268
269impl ExecutionOutput {
270 pub fn stdout_lossy(&self) -> String {
271 String::from_utf8_lossy(&self.stdout).into_owned()
272 }
273
274 pub fn stderr_lossy(&self) -> String {
275 String::from_utf8_lossy(&self.stderr).into_owned()
276 }
277}
278
279#[derive(Debug, Clone)]
283pub struct ProcessHandle {
284 display_id: u32,
285 local_pid: Option<u32>,
286 remote_token: Option<String>,
287}
288
289impl ProcessHandle {
290 #[doc(hidden)]
293 pub fn new(display_id: u32, local_pid: Option<u32>, remote_token: Option<String>) -> Self {
294 Self {
295 display_id,
296 local_pid,
297 remote_token,
298 }
299 }
300
301 pub fn display_id(&self) -> u32 {
302 self.display_id
303 }
304
305 pub fn local_pid(&self) -> Option<u32> {
306 self.local_pid
307 }
308
309 #[doc(hidden)]
313 pub fn remote_token(&self) -> Option<&str> {
314 self.remote_token.as_deref()
315 }
316}
317
318pub struct SpawnedProcess {
319 handle: ProcessHandle,
320 child: Child,
321}
322
323impl SpawnedProcess {
324 pub fn new(handle: ProcessHandle, child: Child) -> Self {
325 Self { handle, child }
326 }
327
328 #[doc(hidden)]
331 pub fn set_remote_token(&mut self, token: String) {
332 self.handle.remote_token = Some(token);
333 }
334
335 pub fn handle(&self) -> &ProcessHandle {
336 &self.handle
337 }
338
339 pub fn take_stdout(&mut self) -> Option<ChildStdout> {
340 self.child.stdout.take()
341 }
342
343 pub fn take_stderr(&mut self) -> Option<ChildStderr> {
344 self.child.stderr.take()
345 }
346
347 pub fn take_stdin(&mut self) -> Option<tokio::process::ChildStdin> {
350 self.child.stdin.take()
351 }
352
353 pub fn into_child(self) -> Child {
354 self.child
355 }
356}
357
358#[async_trait]
359pub trait ExecutionBackend: Send + Sync {
360 fn kind(&self) -> BackendKind;
361 fn id(&self) -> &str;
362 fn approval_scope(&self) -> &str;
363 fn workspace_root(&self) -> &BackendPath;
364 fn home_hint(&self) -> &BackendPath;
365 fn allows_outside_workspace(&self) -> bool;
366
367 async fn home_dir(&self) -> anyhow::Result<BackendPath>;
368 async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath>;
369 async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath>;
370 async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata>;
371 async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>>;
372 async fn write(
373 &self,
374 path: &BackendPath,
375 content: &[u8],
376 mode: WriteMode,
377 create_parents: bool,
378 ) -> anyhow::Result<()>;
379 async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()>;
380 async fn copy(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()>;
381 #[allow(dead_code)]
382 async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()>;
383 #[allow(dead_code)]
384 async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()>;
385 async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()>;
387 async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>>;
388 async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess>;
389 async fn terminate(&self, handle: &ProcessHandle, grace: Duration) -> anyhow::Result<()>;
390
391 async fn execute(
392 &self,
393 request: ExecutionRequest,
394 timeout: Duration,
395 ) -> anyhow::Result<ExecutionOutput> {
396 execute_spawned(self, request, timeout).await
397 }
398
399 async fn import_local_file(
402 &self,
403 local_path: &Path,
404 destination: &BackendPath,
405 ) -> anyhow::Result<BackendPath> {
406 let bytes = tokio::fs::read(local_path).await?;
407 self.write(destination, &bytes, WriteMode::Overwrite, true)
408 .await?;
409 Ok(destination.clone())
410 }
411
412 async fn export_local_file(
414 &self,
415 source: &BackendPath,
416 local_path: &Path,
417 ) -> anyhow::Result<()> {
418 let bytes = self.read(source).await?;
419 if let Some(parent) = local_path.parent() {
420 tokio::fs::create_dir_all(parent).await?;
421 }
422 tokio::fs::write(local_path, bytes).await?;
423 Ok(())
424 }
425
426 async fn resolve_executable(&self, executable: &str) -> anyhow::Result<Option<BackendPath>> {
431 let mut candidates = vec![executable.to_string()];
432 if !executable.contains('/') && !executable.contains('\\') {
433 let home = self.home_dir().await?;
434 for relative in [
435 ".local/bin",
436 ".cargo/bin",
437 ".npm-global/bin",
438 ".bun/bin",
439 ".deno/bin",
440 "go/bin",
441 "miniforge3/bin",
442 "anaconda3/bin",
443 "bin",
444 ] {
445 candidates.push(home.join(relative).join(executable).to_string());
446 }
447 for directory in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
448 candidates.push(format!("{directory}/{executable}"));
449 }
450 }
451 candidates.dedup();
452
453 for candidate in candidates {
454 let request = ExecutionRequest::argv(
455 "sh",
456 vec![
457 "-c".to_string(),
458 "command -v -- \"$1\" 2>/dev/null".to_string(),
459 "sh".to_string(),
460 candidate,
461 ],
462 );
463 let output = self.execute(request, Duration::from_secs(5)).await?;
464 if output.exit_code == 0
465 && let Some(resolved) = output
466 .stdout_lossy()
467 .lines()
468 .map(str::trim)
469 .find(|line| !line.is_empty())
470 {
471 return Ok(Some(BackendPath::new(resolved.to_string())));
472 }
473 }
474 Ok(None)
475 }
476
477 async fn executable_exists(&self, executable: &str) -> anyhow::Result<bool> {
478 Ok(self.resolve_executable(executable).await?.is_some())
479 }
480}
481
482async fn execute_spawned<B: ExecutionBackend + ?Sized>(
483 backend: &B,
484 request: ExecutionRequest,
485 timeout: Duration,
486) -> anyhow::Result<ExecutionOutput> {
487 let started = Instant::now();
488 let mut spawned = backend.spawn(request).await?;
489 let handle = spawned.handle().clone();
490 let stdout = spawned
491 .take_stdout()
492 .ok_or_else(|| anyhow::anyhow!("execution backend did not provide stdout"))?;
493 let stderr = spawned
494 .take_stderr()
495 .ok_or_else(|| anyhow::anyhow!("execution backend did not provide stderr"))?;
496 let mut child = spawned.into_child();
497
498 let stdout_task = tokio::spawn(async move {
499 let mut reader = stdout;
500 let mut bytes = Vec::new();
501 tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
502 Ok::<_, std::io::Error>(bytes)
503 });
504 let stderr_task = tokio::spawn(async move {
505 let mut reader = stderr;
506 let mut bytes = Vec::new();
507 tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
508 Ok::<_, std::io::Error>(bytes)
509 });
510
511 let (status, timed_out) = match tokio::time::timeout(timeout, child.wait()).await {
512 Ok(status) => (Some(status?), false),
513 Err(_) => {
514 backend
515 .terminate(&handle, Duration::from_secs(2))
516 .await
517 .ok();
518 let status = tokio::time::timeout(Duration::from_secs(3), child.wait())
519 .await
520 .ok()
521 .and_then(Result::ok);
522 (status, true)
523 }
524 };
525
526 let stdout = stdout_task
527 .await
528 .ok()
529 .and_then(Result::ok)
530 .unwrap_or_default();
531 let stderr = stderr_task
532 .await
533 .ok()
534 .and_then(Result::ok)
535 .unwrap_or_default();
536
537 Ok(ExecutionOutput {
538 exit_code: status.and_then(|status| status.code()).unwrap_or(-1),
539 stdout,
540 stderr,
541 duration_ms: started.elapsed().as_millis() as u64,
542 timed_out,
543 })
544}
545
546pub fn shell_quote(value: &str) -> String {
548 if value.is_empty() {
549 return "''".to_string();
550 }
551 format!("'{}'", value.replace('\'', "'\"'\"'"))
552}
553
554#[derive(Debug, Clone, PartialEq, Eq)]
559pub struct LexicalPaths {
560 kind: BackendKind,
561 workspace_root: BackendPath,
562 home: BackendPath,
563}
564
565impl LexicalPaths {
566 pub fn of(backend: &dyn ExecutionBackend) -> Self {
567 Self {
568 kind: backend.kind(),
569 workspace_root: backend.workspace_root().clone(),
570 home: backend.home_hint().clone(),
571 }
572 }
573
574 pub fn daemon_host() -> Self {
577 let workspace = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
578 let canonical = dunce::canonicalize(&workspace).unwrap_or_else(|_| workspace.clone());
579 let home = dirs::home_dir().unwrap_or_else(|| canonical.clone());
580 Self {
581 kind: BackendKind::Local,
582 workspace_root: BackendPath::new(canonical.to_string_lossy().into_owned()),
583 home: BackendPath::new(home.to_string_lossy().into_owned()),
584 }
585 }
586
587 pub fn normalize(&self, path: &str) -> anyhow::Result<BackendPath> {
588 normalize_lexically(self.kind, &self.workspace_root, &self.home, path)
589 }
590
591 pub fn posix(workspace_root: &str, home: &str) -> Self {
593 Self {
594 kind: BackendKind::Ssh,
595 workspace_root: BackendPath::new(workspace_root),
596 home: BackendPath::new(home),
597 }
598 }
599}
600
601pub fn normalize_lexically(
602 kind: BackendKind,
603 workspace_root: &BackendPath,
604 home: &BackendPath,
605 path: &str,
606) -> anyhow::Result<BackendPath> {
607 let expanded = if path == "~" {
608 home.as_str().to_string()
609 } else if let Some(rest) = path.strip_prefix("~/") {
610 home.join(rest).to_string()
611 } else if Path::new(path).is_absolute() {
612 path.to_string()
613 } else {
614 workspace_root.join(path).to_string()
615 };
616 match kind {
617 BackendKind::Local => Ok(BackendPath::new(
618 normalize_local_lexically(Path::new(&expanded))?
619 .to_string_lossy()
620 .into_owned(),
621 )),
622 BackendKind::Docker | BackendKind::Ssh => {
623 Ok(BackendPath::new(normalize_posix_absolute(&expanded)?))
624 }
625 }
626}
627
628pub fn normalize_posix_absolute(path: &str) -> anyhow::Result<String> {
629 anyhow::ensure!(
630 path.starts_with('/'),
631 "Remote execution path must be absolute: {path}"
632 );
633 let mut parts = Vec::new();
634 for part in path.split('/') {
635 match part {
636 "" | "." => {}
637 ".." => {
638 anyhow::ensure!(
639 parts.pop().is_some(),
640 "Path traversal escapes filesystem root: {path}"
641 );
642 }
643 other => parts.push(other),
644 }
645 }
646 Ok(format!("/{}", parts.join("/")))
647}
648
649pub fn normalize_local_lexically(path: &Path) -> anyhow::Result<PathBuf> {
650 let mut normalized = PathBuf::new();
651 for component in path.components() {
652 match component {
653 Component::CurDir => {}
654 Component::ParentDir => {
655 anyhow::ensure!(
656 normalized.pop(),
657 "Path traversal escapes filesystem root: {}",
658 path.display()
659 );
660 }
661 other => normalized.push(other.as_os_str()),
662 }
663 }
664 Ok(normalized)
665}
666
667pub type SharedExecutionBackend = std::sync::Arc<dyn ExecutionBackend>;
669
670pub fn normalize_path_lexically(
674 backend: &dyn ExecutionBackend,
675 path: &str,
676) -> anyhow::Result<BackendPath> {
677 normalize_lexically(
678 backend.kind(),
679 backend.workspace_root(),
680 backend.home_hint(),
681 path,
682 )
683}
684
685#[cfg(test)]
686mod anchored_path_tests {
687 use super::*;
688
689 #[test]
690 fn only_absolute_and_home_paths_are_anchored() {
691 for anchored in ["/srv/app", "~", "~/notes"] {
692 assert!(BackendPath::is_anchored(anchored), "{anchored}");
693 }
694 for relative in ["notes", "./notes", "~someone/notes", ""] {
695 assert!(!BackendPath::is_anchored(relative), "{relative}");
696 }
697 }
698}