Skip to main content

blyte_agent/
fs.rs

1//! Where files actually live. The companion seam to [`crate::shell`].
2//!
3//! Routing commands through an executor while reading and writing files on the conversation model's
4//! own disk is coherent for exactly one deployment -- a bind-mounted workspace, where both
5//! views address the same bytes. For a shell that executes on another machine, or in a
6//! container without a mount, it is silently wrong: the model edits one filesystem and verifies
7//! another. That is the same defect the previous harness had in reverse, and it cost four runs
8//! before anyone noticed the worker was editing the host while its gate ran in the sandbox.
9//!
10//! DeepSeek's harness keeps `ctx.fs` separate from `ctx.shell` for this reason. So does this.
11//!
12//! Canonicalisation belongs here too, not in the tools. The workspace-escape check is only
13//! meaningful against the filesystem the write will actually land on -- resolving symlinks on
14//! the conversation model's disk says nothing about where a path leads inside a container.
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19pub trait Fs: Send + Sync {
20    fn read(&self, path: &Path) -> Result<String, String>;
21    fn write(&self, path: &Path, content: &str) -> Result<(), String>;
22    /// Resolve symlinks and `..`. Used for the workspace-escape check, so it must answer for
23    /// the filesystem the operation will really touch.
24    fn canonicalize(&self, path: &Path) -> Result<PathBuf, String>;
25    /// Whether paths name files on this machine, so tools may read them in-process.
26    fn is_local(&self) -> bool {
27        false
28    }
29}
30
31#[derive(Debug, Default, Clone)]
32pub struct LocalFs;
33
34impl Fs for LocalFs {
35    fn is_local(&self) -> bool {
36        true
37    }
38    fn read(&self, path: &Path) -> Result<String, String> {
39        std::fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))
40    }
41    fn write(&self, path: &Path, content: &str) -> Result<(), String> {
42        if let Some(dir) = path.parent() {
43            std::fs::create_dir_all(dir)
44                .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
45        }
46        std::fs::write(path, content).map_err(|e| format!("cannot write {}: {e}", path.display()))
47    }
48    fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
49        path.canonicalize()
50            .map_err(|e| format!("{}: {e}", path.display()))
51    }
52}
53
54/// Files inside a running container, reached the same way its shell is.
55#[derive(Debug, Clone)]
56pub struct ContainerFs {
57    pub container_id: String,
58}
59
60impl ContainerFs {
61    fn exec(&self, args: &[&str], stdin: Option<&str>) -> Result<(String, i32), String> {
62        use std::io::Write;
63        use std::process::Stdio;
64        let mut cmd = Command::new("docker");
65        cmd.args(["exec", "-i", &self.container_id])
66            .args(args)
67            .stdin(if stdin.is_some() {
68                Stdio::piped()
69            } else {
70                Stdio::null()
71            })
72            .stdout(Stdio::piped())
73            .stderr(Stdio::piped());
74        let mut child = cmd
75            .spawn()
76            .map_err(|e| format!("docker exec failed: {e}"))?;
77        if let Some(body) = stdin {
78            child
79                .stdin
80                .take()
81                .ok_or("no stdin")?
82                .write_all(body.as_bytes())
83                .map_err(|e| format!("cannot send content: {e}"))?;
84        }
85        let out = child
86            .wait_with_output()
87            .map_err(|e| format!("docker exec failed: {e}"))?;
88        Ok((
89            String::from_utf8_lossy(&out.stdout).to_string(),
90            out.status.code().unwrap_or(-1),
91        ))
92    }
93}
94
95impl Fs for ContainerFs {
96    fn read(&self, path: &Path) -> Result<String, String> {
97        let p = path.to_string_lossy().to_string();
98        match self.exec(&["cat", "--", &p], None)? {
99            (body, 0) => Ok(body),
100            _ => Err(format!("cannot read {p} in container")),
101        }
102    }
103    fn write(&self, path: &Path, content: &str) -> Result<(), String> {
104        let p = path.to_string_lossy().to_string();
105        let dir = path
106            .parent()
107            .map(|d| d.to_string_lossy().to_string())
108            .unwrap_or_default();
109        if !dir.is_empty() {
110            self.exec(&["mkdir", "-p", "--", &dir], None)?;
111        }
112        // `tee` rather than a redirect: the content never passes through a shell, so quotes,
113        // backticks and `$` in source code cannot be interpreted on the way in.
114        match self.exec(&["tee", "--", &p], Some(content))? {
115            (_, 0) => Ok(()),
116            _ => Err(format!("cannot write {p} in container")),
117        }
118    }
119    fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
120        let p = path.to_string_lossy().to_string();
121        match self.exec(&["readlink", "-f", "--", &p], None)? {
122            (out, 0) if !out.trim().is_empty() => Ok(PathBuf::from(out.trim())),
123            _ => Err(format!("cannot resolve {p} in container")),
124        }
125    }
126}
127
128/// Files reached through a persistent session: the container counterpart of [`LocalFs`] at a
129/// round trip of a few milliseconds, instead of 2-5 `docker exec` per operation (a container
130/// `edit` cost about 300 ms). Content crosses through a heredoc read by the `read` builtin, so no byte is interpreted on the
131/// way. Falls back to [`ContainerFs`] (or [`LocalFs`] for a local launcher) when no session can
132/// start. Error messages match [`ContainerFs`].
133pub struct SessionFs {
134    shell: crate::shell::PersistentShell,
135    fallback: Box<dyn Fs>,
136}
137
138impl SessionFs {
139    pub fn container(container_id: String, workdir: PathBuf) -> Self {
140        Self {
141            shell: crate::shell::PersistentShell::container(container_id.clone(), workdir),
142            fallback: Box::new(ContainerFs { container_id }),
143        }
144    }
145
146    /// A session on this machine: for tests, and for executors without a container.
147    pub fn local(root: PathBuf) -> Self {
148        Self {
149            shell: crate::shell::PersistentShell::local(root),
150            fallback: Box::new(LocalFs),
151        }
152    }
153
154    fn run(&self, command: &str) -> Option<crate::shell::Output> {
155        use crate::shell::Shell;
156        if !self.shell.is_persistent() {
157            return None;
158        }
159        self.shell
160            .exec(command, Path::new("/"), std::time::Duration::from_secs(120))
161            .ok()
162    }
163}
164
165fn sh_quote(s: &str) -> String {
166    format!("'{}'", s.replace('\'', r"'\''"))
167}
168
169impl Fs for SessionFs {
170    fn read(&self, path: &Path) -> Result<String, String> {
171        let p = path.to_string_lossy().to_string();
172        match self.run(&format!("cat -- {}", sh_quote(&p))) {
173            Some(o) if o.exit_code == 0 => Ok(o.stdout),
174            Some(_) => Err(format!("cannot read {p} in container")),
175            None => self.fallback.read(path),
176        }
177    }
178
179    fn write(&self, path: &Path, content: &str) -> Result<(), String> {
180        let p = path.to_string_lossy().to_string();
181        let dir = path
182            .parent()
183            .map(|d| d.to_string_lossy().to_string())
184            .unwrap_or_default();
185        let mkdir = if dir.is_empty() {
186            String::new()
187        } else {
188            let d = sh_quote(&dir);
189            format!("{{ [ -d {d} ] || mkdir -p -- {d}; }} && ")
190        };
191        // Content through a heredoc read by the `read` builtin: no process, no encoding. The
192        // heredoc adds one final newline, which is stripped, so the bytes are exact.
193        let delim = format!(
194            "__BLYTE_CONTENT_{}_{}__",
195            std::process::id(),
196            std::time::SystemTime::now()
197                .duration_since(std::time::UNIX_EPOCH)
198                .map(|d| d.as_nanos())
199                .unwrap_or(0)
200        );
201        let cmd = format!(
202            "IFS= read -r -d '' __blyte_w <<'{delim}' || true\n{content}\n{delim}\n\
203             __blyte_w=${{__blyte_w%$'\\n'}}; {mkdir}printf %s \"$__blyte_w\" > {}",
204            sh_quote(&p)
205        );
206        match self.run(&cmd) {
207            Some(o) if o.exit_code == 0 => Ok(()),
208            Some(_) => Err(format!("cannot write {p} in container")),
209            None => self.fallback.write(path, content),
210        }
211    }
212
213    fn canonicalize(&self, path: &Path) -> Result<PathBuf, String> {
214        let p = path.to_string_lossy().to_string();
215        match self.run(&format!("readlink -f -- {}", sh_quote(&p))) {
216            Some(o) if o.exit_code == 0 && !o.stdout.trim().is_empty() => {
217                Ok(PathBuf::from(o.stdout.trim()))
218            }
219            Some(_) => Err(format!("cannot resolve {p} in container")),
220            None => self.fallback.canonicalize(path),
221        }
222    }
223}