Skip to main content

aidaemon_tools/fs/
workspace_backend.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use tokio::io::AsyncWriteExt;
5
6use crate::backend::{
7    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, ExecutionBackend,
8    ExecutionRequest, ProcessHandle, SpawnedProcess, WriteMode,
9};
10use crate::workspace::Workspace;
11
12/// File access confined to a [`Workspace`]. Every operation re-resolves its
13/// path, so a symlink cannot lead outside the root. It runs no processes;
14/// commands go through [`crate::Shell`] and its sandbox.
15#[derive(Debug, Clone)]
16pub struct WorkspaceBackend {
17    workspace: Workspace,
18    root: BackendPath,
19    id: String,
20}
21
22impl WorkspaceBackend {
23    pub fn new(workspace: Workspace) -> Self {
24        let root = workspace.root().display().to_string();
25        Self {
26            id: format!("workspace:{root}"),
27            root: BackendPath::new(root),
28            workspace,
29        }
30    }
31
32    fn confine(&self, path: &BackendPath) -> anyhow::Result<std::path::PathBuf> {
33        Ok(self.workspace.resolve(path.as_str())?)
34    }
35}
36
37fn metadata_of(metadata: &std::fs::Metadata) -> BackendMetadata {
38    let kind = metadata.file_type();
39    BackendMetadata {
40        file_type: if kind.is_symlink() {
41            BackendFileType::Symlink
42        } else if kind.is_dir() {
43            BackendFileType::Directory
44        } else if kind.is_file() {
45            BackendFileType::File
46        } else {
47            BackendFileType::Other
48        },
49        len: metadata.len(),
50        modified: metadata.modified().ok(),
51    }
52}
53
54#[async_trait]
55impl ExecutionBackend for WorkspaceBackend {
56    fn kind(&self) -> BackendKind {
57        BackendKind::Local
58    }
59
60    fn id(&self) -> &str {
61        &self.id
62    }
63
64    fn approval_scope(&self) -> &str {
65        &self.id
66    }
67
68    fn workspace_root(&self) -> &BackendPath {
69        &self.root
70    }
71
72    fn home_hint(&self) -> &BackendPath {
73        &self.root
74    }
75
76    fn allows_outside_workspace(&self) -> bool {
77        false
78    }
79
80    async fn home_dir(&self) -> anyhow::Result<BackendPath> {
81        Ok(self.root.clone())
82    }
83
84    async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath> {
85        let resolved = self.workspace.resolve(path)?;
86        Ok(BackendPath::new(resolved.display().to_string()))
87    }
88
89    async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath> {
90        let resolved = tokio::fs::canonicalize(self.confine(path)?)
91            .await
92            .map(|p| dunce::simplified(&p).to_path_buf())?;
93        Ok(BackendPath::new(resolved.display().to_string()))
94    }
95
96    async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata> {
97        Ok(metadata_of(
98            &tokio::fs::metadata(self.confine(path)?).await?,
99        ))
100    }
101
102    async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>> {
103        Ok(tokio::fs::read(self.confine(path)?).await?)
104    }
105
106    async fn write(
107        &self,
108        path: &BackendPath,
109        content: &[u8],
110        mode: WriteMode,
111        create_parents: bool,
112    ) -> anyhow::Result<()> {
113        let target = self.confine(path)?;
114        if create_parents && let Some(parent) = target.parent() {
115            tokio::fs::create_dir_all(parent).await?;
116        }
117        match mode {
118            WriteMode::Overwrite => tokio::fs::write(&target, content).await?,
119            WriteMode::Append => {
120                let mut file = tokio::fs::OpenOptions::new()
121                    .create(true)
122                    .append(true)
123                    .open(&target)
124                    .await?;
125                file.write_all(content).await?;
126                file.flush().await?;
127            }
128        }
129        Ok(())
130    }
131
132    async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()> {
133        Ok(tokio::fs::create_dir_all(self.confine(path)?).await?)
134    }
135
136    async fn copy(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
137        tokio::fs::copy(self.confine(source)?, self.confine(destination)?).await?;
138        Ok(())
139    }
140
141    async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
142        Ok(tokio::fs::rename(self.confine(source)?, self.confine(destination)?).await?)
143    }
144
145    async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()> {
146        Ok(tokio::fs::remove_file(self.confine(path)?).await?)
147    }
148
149    async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()> {
150        Ok(tokio::fs::remove_dir(self.confine(path)?).await?)
151    }
152
153    async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>> {
154        let directory = self.confine(path)?;
155        let mut reader = tokio::fs::read_dir(&directory).await?;
156        let mut entries = Vec::new();
157        while let Some(entry) = reader.next_entry().await? {
158            entries.push(BackendDirEntry {
159                path: BackendPath::new(entry.path().display().to_string()),
160                metadata: metadata_of(&tokio::fs::symlink_metadata(entry.path()).await?),
161            });
162        }
163        Ok(entries)
164    }
165
166    async fn spawn(&self, _request: ExecutionRequest) -> anyhow::Result<SpawnedProcess> {
167        anyhow::bail!("a workspace backend runs no processes; use the shell tool")
168    }
169
170    async fn terminate(&self, _handle: &ProcessHandle, _grace: Duration) -> anyhow::Result<()> {
171        anyhow::bail!("a workspace backend runs no processes")
172    }
173}