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 async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()>;
382 async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()>;
383 async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()>;
385 async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>>;
386 async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess>;
387 async fn terminate(&self, handle: &ProcessHandle, grace: Duration) -> anyhow::Result<()>;
388
389 async fn execute(
390 &self,
391 request: ExecutionRequest,
392 timeout: Duration,
393 ) -> anyhow::Result<ExecutionOutput> {
394 execute_spawned(self, request, timeout).await
395 }
396
397 async fn import_local_file(
400 &self,
401 local_path: &Path,
402 destination: &BackendPath,
403 ) -> anyhow::Result<BackendPath> {
404 let bytes = tokio::fs::read(local_path).await?;
405 self.write(destination, &bytes, WriteMode::Overwrite, true)
406 .await?;
407 Ok(destination.clone())
408 }
409
410 async fn export_local_file(
412 &self,
413 source: &BackendPath,
414 local_path: &Path,
415 ) -> anyhow::Result<()> {
416 let bytes = self.read(source).await?;
417 if let Some(parent) = local_path.parent() {
418 tokio::fs::create_dir_all(parent).await?;
419 }
420 tokio::fs::write(local_path, bytes).await?;
421 Ok(())
422 }
423
424 async fn resolve_executable(&self, executable: &str) -> anyhow::Result<Option<BackendPath>> {
429 let mut candidates = vec![executable.to_string()];
430 if !executable.contains('/') && !executable.contains('\\') {
431 let home = self.home_dir().await?;
432 for relative in [
433 ".local/bin",
434 ".cargo/bin",
435 ".npm-global/bin",
436 ".bun/bin",
437 ".deno/bin",
438 "go/bin",
439 "miniforge3/bin",
440 "anaconda3/bin",
441 "bin",
442 ] {
443 candidates.push(home.join(relative).join(executable).to_string());
444 }
445 for directory in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
446 candidates.push(format!("{directory}/{executable}"));
447 }
448 }
449 candidates.dedup();
450
451 for candidate in candidates {
452 let request = ExecutionRequest::argv(
453 "sh",
454 vec![
455 "-c".to_string(),
456 "command -v -- \"$1\" 2>/dev/null".to_string(),
457 "sh".to_string(),
458 candidate,
459 ],
460 );
461 let output = self.execute(request, Duration::from_secs(5)).await?;
462 if output.exit_code == 0
463 && let Some(resolved) = output
464 .stdout_lossy()
465 .lines()
466 .map(str::trim)
467 .find(|line| !line.is_empty())
468 {
469 return Ok(Some(BackendPath::new(resolved.to_string())));
470 }
471 }
472 Ok(None)
473 }
474
475 async fn executable_exists(&self, executable: &str) -> anyhow::Result<bool> {
476 Ok(self.resolve_executable(executable).await?.is_some())
477 }
478}
479
480async fn execute_spawned<B: ExecutionBackend + ?Sized>(
481 backend: &B,
482 request: ExecutionRequest,
483 timeout: Duration,
484) -> anyhow::Result<ExecutionOutput> {
485 let started = Instant::now();
486 let mut spawned = backend.spawn(request).await?;
487 let handle = spawned.handle().clone();
488 let stdout = spawned
489 .take_stdout()
490 .ok_or_else(|| anyhow::anyhow!("execution backend did not provide stdout"))?;
491 let stderr = spawned
492 .take_stderr()
493 .ok_or_else(|| anyhow::anyhow!("execution backend did not provide stderr"))?;
494 let mut child = spawned.into_child();
495
496 let stdout_task = tokio::spawn(async move {
497 let mut reader = stdout;
498 let mut bytes = Vec::new();
499 tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
500 Ok::<_, std::io::Error>(bytes)
501 });
502 let stderr_task = tokio::spawn(async move {
503 let mut reader = stderr;
504 let mut bytes = Vec::new();
505 tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut bytes).await?;
506 Ok::<_, std::io::Error>(bytes)
507 });
508
509 let (status, timed_out) = match tokio::time::timeout(timeout, child.wait()).await {
510 Ok(status) => (Some(status?), false),
511 Err(_) => {
512 backend
513 .terminate(&handle, Duration::from_secs(2))
514 .await
515 .ok();
516 let status = tokio::time::timeout(Duration::from_secs(3), child.wait())
517 .await
518 .ok()
519 .and_then(Result::ok);
520 (status, true)
521 }
522 };
523
524 let stdout = stdout_task
525 .await
526 .ok()
527 .and_then(Result::ok)
528 .unwrap_or_default();
529 let stderr = stderr_task
530 .await
531 .ok()
532 .and_then(Result::ok)
533 .unwrap_or_default();
534
535 Ok(ExecutionOutput {
536 exit_code: status.and_then(|status| status.code()).unwrap_or(-1),
537 stdout,
538 stderr,
539 duration_ms: started.elapsed().as_millis() as u64,
540 timed_out,
541 })
542}
543
544pub fn shell_quote(value: &str) -> String {
546 if value.is_empty() {
547 return "''".to_string();
548 }
549 format!("'{}'", value.replace('\'', "'\"'\"'"))
550}
551
552#[derive(Debug, Clone, PartialEq, Eq)]
557pub struct LexicalPaths {
558 kind: BackendKind,
559 workspace_root: BackendPath,
560 home: BackendPath,
561}
562
563impl LexicalPaths {
564 pub fn of(backend: &dyn ExecutionBackend) -> Self {
565 Self {
566 kind: backend.kind(),
567 workspace_root: backend.workspace_root().clone(),
568 home: backend.home_hint().clone(),
569 }
570 }
571
572 pub fn daemon_host() -> Self {
575 let workspace = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
576 let canonical = dunce::canonicalize(&workspace).unwrap_or_else(|_| workspace.clone());
577 let home = dirs::home_dir().unwrap_or_else(|| canonical.clone());
578 Self {
579 kind: BackendKind::Local,
580 workspace_root: BackendPath::new(canonical.to_string_lossy().into_owned()),
581 home: BackendPath::new(home.to_string_lossy().into_owned()),
582 }
583 }
584
585 pub fn normalize(&self, path: &str) -> anyhow::Result<BackendPath> {
586 normalize_lexically(self.kind, &self.workspace_root, &self.home, path)
587 }
588
589 pub fn posix(workspace_root: &str, home: &str) -> Self {
591 Self {
592 kind: BackendKind::Ssh,
593 workspace_root: BackendPath::new(workspace_root),
594 home: BackendPath::new(home),
595 }
596 }
597}
598
599pub fn normalize_lexically(
600 kind: BackendKind,
601 workspace_root: &BackendPath,
602 home: &BackendPath,
603 path: &str,
604) -> anyhow::Result<BackendPath> {
605 let expanded = if path == "~" {
606 home.as_str().to_string()
607 } else if let Some(rest) = path.strip_prefix("~/") {
608 home.join(rest).to_string()
609 } else if Path::new(path).is_absolute() {
610 path.to_string()
611 } else {
612 workspace_root.join(path).to_string()
613 };
614 match kind {
615 BackendKind::Local => Ok(BackendPath::new(
616 normalize_local_lexically(Path::new(&expanded))?
617 .to_string_lossy()
618 .into_owned(),
619 )),
620 BackendKind::Docker | BackendKind::Ssh => {
621 Ok(BackendPath::new(normalize_posix_absolute(&expanded)?))
622 }
623 }
624}
625
626pub fn normalize_posix_absolute(path: &str) -> anyhow::Result<String> {
627 anyhow::ensure!(
628 path.starts_with('/'),
629 "Remote execution path must be absolute: {path}"
630 );
631 let mut parts = Vec::new();
632 for part in path.split('/') {
633 match part {
634 "" | "." => {}
635 ".." => {
636 anyhow::ensure!(
637 parts.pop().is_some(),
638 "Path traversal escapes filesystem root: {path}"
639 );
640 }
641 other => parts.push(other),
642 }
643 }
644 Ok(format!("/{}", parts.join("/")))
645}
646
647pub fn normalize_local_lexically(path: &Path) -> anyhow::Result<PathBuf> {
648 let mut normalized = PathBuf::new();
649 for component in path.components() {
650 match component {
651 Component::CurDir => {}
652 Component::ParentDir => {
653 anyhow::ensure!(
654 normalized.pop(),
655 "Path traversal escapes filesystem root: {}",
656 path.display()
657 );
658 }
659 other => normalized.push(other.as_os_str()),
660 }
661 }
662 Ok(normalized)
663}
664
665pub type SharedExecutionBackend = std::sync::Arc<dyn ExecutionBackend>;
667
668pub fn normalize_path_lexically(
672 backend: &dyn ExecutionBackend,
673 path: &str,
674) -> anyhow::Result<BackendPath> {
675 normalize_lexically(
676 backend.kind(),
677 backend.workspace_root(),
678 backend.home_hint(),
679 path,
680 )
681}
682
683#[cfg(test)]
684mod anchored_path_tests {
685 use super::*;
686
687 #[test]
688 fn only_absolute_and_home_paths_are_anchored() {
689 for anchored in ["/srv/app", "~", "~/notes"] {
690 assert!(BackendPath::is_anchored(anchored), "{anchored}");
691 }
692 for relative in ["notes", "./notes", "~someone/notes", ""] {
693 assert!(!BackendPath::is_anchored(relative), "{relative}");
694 }
695 }
696}