Skip to main content

rpi_tools/
file_io.rs

1//! Optional, protocol-neutral text I/O for the existing native tools.
2//!
3//! This is bounded text delegation, NOT an ExecutionEnv replacement or an OS
4//! sandbox. The caller must configure only while its session is idle, and own
5//! backend shutdown/timeouts. Each tool freezes configuration before resolving
6//! its path. Backends must not retain the owning harness/session (use weak
7//! references where necessary). No capabilities are enabled by default.
8//!
9//! Mutations serialize by router + lexical path, not symlink identity. There is
10//! no editor version/CAS, rollback, or retry after an unconfirmed write: a lost
11//! acknowledgment may mean the client already committed the change.
12
13use std::path::Path;
14use std::sync::Arc;
15
16use async_trait::async_trait;
17use futures::future::BoxFuture;
18use tokio::sync::Mutex;
19use tokio_util::sync::CancellationToken;
20
21use crate::error::{FileError, FileErrorCode};
22use crate::file_mutation_queue::MutationQueueRegistry;
23use crate::path_utils::normalize_tool_path;
24
25pub const MAX_FILE_IO_BYTES: usize = 256 * 1024;
26
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
28pub struct FileIOCapabilities {
29    pub read_text: bool,
30    pub write_text: bool,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum FileIOReadRange {
35    /// One-based offset, applied by the backend exactly once. Content is raw
36    /// text, not numbered/display-truncated. Empty content at EOF is valid.
37    Lines { offset_1based: u32, limit: u32 },
38    /// Full content for edit. A backend must fail rather than truncate it.
39    Complete,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum FileIORequest {
44    ReadText {
45        absolute_path: String,
46        range: FileIOReadRange,
47        max_bytes: usize,
48    },
49    WriteText {
50        absolute_path: String,
51        content: String,
52    },
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum FileIOResponse {
57    Text { content: String },
58    Written,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum FileIOErrorCode {
63    Unsupported,
64    Denied,
65    NotFound,
66    InvalidResponse,
67    TooLarge,
68    Timeout,
69    Cancelled,
70    Disconnected,
71    InvalidPath,
72}
73
74#[derive(Debug, Clone, thiserror::Error)]
75#[error("{code:?}: {message}")]
76pub struct FileIOError {
77    pub code: FileIOErrorCode,
78    pub message: String,
79}
80
81impl FileIOError {
82    pub fn new(code: FileIOErrorCode, message: impl Into<String>) -> Self {
83        Self {
84            code,
85            message: message.into(),
86        }
87    }
88}
89
90// Keep the existing tools' FileError -> AgentError surface. Preserve the typed
91// client error as source instead of adding variants to unrelated native traits.
92impl From<FileIOError> for FileError {
93    fn from(error: FileIOError) -> Self {
94        let code = match error.code {
95            FileIOErrorCode::Unsupported => FileErrorCode::NotSupported,
96            FileIOErrorCode::Denied => FileErrorCode::PermissionDenied,
97            FileIOErrorCode::NotFound => FileErrorCode::NotFound,
98            FileIOErrorCode::Cancelled => FileErrorCode::Aborted,
99            FileIOErrorCode::InvalidPath
100            | FileIOErrorCode::InvalidResponse
101            | FileIOErrorCode::TooLarge => FileErrorCode::Invalid,
102            FileIOErrorCode::Timeout | FileIOErrorCode::Disconnected => FileErrorCode::Unknown,
103        };
104        FileError::new(code, error.to_string()).with_source(Box::new(error))
105    }
106}
107
108#[async_trait]
109pub trait FileIOBackend: Send + Sync {
110    /// The transport owner supplies deadlines, bounded admission/ingress, and
111    /// retirement on future drop. Never retry writes automatically. Checking
112    /// max_bytes after decoding does not bound transport allocation by itself.
113    async fn request(
114        &self,
115        request: FileIORequest,
116        cancel: CancellationToken,
117    ) -> Result<FileIOResponse, FileIOError>;
118}
119
120#[derive(Debug, Clone, Copy)]
121pub enum FileIOOperation {
122    Read,
123    Write,
124    Edit,
125}
126
127#[derive(Default, Clone)]
128struct Configuration {
129    capabilities: FileIOCapabilities,
130    backend: Option<Arc<dyn FileIOBackend>>,
131}
132
133#[derive(Default)]
134pub struct FileIORouter {
135    configuration: Mutex<Configuration>,
136    queues: MutationQueueRegistry,
137}
138
139impl FileIORouter {
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// Atomic configuration replacement; the CLI owner MUST ensure idle state.
145    /// This layer has no run/harness knowledge. Existing operation snapshots
146    /// retain their original capability/backend choice across queue waits.
147    pub async fn configure(
148        &self,
149        capabilities: FileIOCapabilities,
150        backend: Option<Arc<dyn FileIOBackend>>,
151    ) -> Result<(), FileIOError> {
152        if (capabilities.read_text || capabilities.write_text) && backend.is_none() {
153            return Err(FileIOError::new(
154                FileIOErrorCode::Unsupported,
155                "selected client I/O requires a backend",
156            ));
157        }
158        *self.configuration.lock().await = Configuration {
159            capabilities,
160            backend,
161        };
162        Ok(())
163    }
164
165    /// None means the original local implementation. Errors NEVER mean local.
166    pub async fn select(
167        &self,
168        operation: FileIOOperation,
169    ) -> Result<Option<FileIOSnapshot>, FileIOError> {
170        let config = self.configuration.lock().await.clone();
171        let caps = config.capabilities;
172        let client = match operation {
173            FileIOOperation::Read => caps.read_text,
174            FileIOOperation::Write if caps.read_text && !caps.write_text => {
175                return Err(FileIOError::new(
176                    FileIOErrorCode::Unsupported,
177                    "write requires client write_text when client read_text is selected",
178                ));
179            }
180            FileIOOperation::Write => caps.write_text,
181            FileIOOperation::Edit if caps.read_text != caps.write_text => {
182                return Err(FileIOError::new(
183                    FileIOErrorCode::Unsupported,
184                    "edit requires both client read_text and write_text",
185                ));
186            }
187            FileIOOperation::Edit => caps.read_text && caps.write_text,
188        };
189        if !client {
190            return Ok(None);
191        }
192        let backend = config.backend.ok_or_else(|| {
193            FileIOError::new(FileIOErrorCode::Unsupported, "client backend unavailable")
194        })?;
195        Ok(Some(FileIOSnapshot {
196            backend,
197            capabilities: caps,
198        }))
199    }
200
201    /// Shared by client write AND edit. Cancellation never skips a queue turn.
202    pub(crate) async fn with_mutation_queue<F, R>(
203        &self,
204        absolute_path: &str,
205        cancel: &CancellationToken,
206        f: F,
207    ) -> Result<R, FileError>
208    where
209        F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
210        R: Send + 'static,
211    {
212        self.queues.with_key(absolute_path, cancel, f).await
213    }
214}
215
216/// Select only the mutation queue; local filesystem semantics stay in the tools.
217pub(crate) async fn with_tool_mutation_queue<F, R>(
218    router: Option<&FileIORouter>,
219    env: &dyn crate::file_mutation_queue::MutatingEnv,
220    path: &str,
221    cancel: &CancellationToken,
222    f: F,
223) -> Result<R, FileError>
224where
225    F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
226    R: Send + 'static,
227{
228    match router {
229        Some(router) => router.with_mutation_queue(path, cancel, f).await,
230        None => crate::file_mutation_queue::with_file_mutation_queue(env, path, cancel, f).await,
231    }
232}
233
234/// Immutable authority/backend choice for one complete tool operation.
235#[derive(Clone)]
236pub struct FileIOSnapshot {
237    backend: Arc<dyn FileIOBackend>,
238    capabilities: FileIOCapabilities,
239}
240
241impl FileIOSnapshot {
242    pub async fn read_text(
243        &self,
244        path: &str,
245        range: FileIOReadRange,
246        cancel: &CancellationToken,
247    ) -> Result<String, FileIOError> {
248        if !self.capabilities.read_text {
249            return Err(FileIOError::new(
250                FileIOErrorCode::Unsupported,
251                "client text read not selected",
252            ));
253        }
254        check_cancel(cancel)?;
255        let response = self
256            .backend
257            .request(
258                FileIORequest::ReadText {
259                    absolute_path: path.to_owned(),
260                    range,
261                    max_bytes: MAX_FILE_IO_BYTES,
262                },
263                cancel.clone(),
264            )
265            .await;
266        check_cancel(cancel)?;
267        match response? {
268            FileIOResponse::Text { content } => {
269                check_text_size(&content)?;
270                if let FileIOReadRange::Lines { limit, .. } = range {
271                    // A trailing newline is a terminator, not a sentinel line.
272                    if crate::truncate::split_lines_for_counting(&content).len() > limit as usize {
273                        return Err(FileIOError::new(
274                            FileIOErrorCode::InvalidResponse,
275                            "client returned more lines than requested",
276                        ));
277                    }
278                }
279                Ok(content)
280            }
281            _ => Err(FileIOError::new(
282                FileIOErrorCode::InvalidResponse,
283                "expected client text response",
284            )),
285        }
286    }
287
288    pub async fn write_text(
289        &self,
290        path: &str,
291        content: String,
292        cancel: &CancellationToken,
293    ) -> Result<(), FileIOError> {
294        if !self.capabilities.write_text {
295            return Err(FileIOError::new(
296                FileIOErrorCode::Unsupported,
297                "client text write not selected",
298            ));
299        }
300        check_cancel(cancel)?;
301        check_text_size(&content)?;
302        let response = self
303            .backend
304            .request(
305                FileIORequest::WriteText {
306                    absolute_path: path.to_owned(),
307                    content,
308                },
309                cancel.clone(),
310            )
311            .await;
312        check_cancel(cancel)?;
313        match response? {
314            FileIOResponse::Written => Ok(()),
315            _ => Err(FileIOError::new(
316                FileIOErrorCode::InvalidResponse,
317                "expected client write acknowledgment",
318            )),
319        }
320    }
321}
322
323fn check_cancel(cancel: &CancellationToken) -> Result<(), FileIOError> {
324    if cancel.is_cancelled() {
325        return Err(FileIOError::new(
326            FileIOErrorCode::Cancelled,
327            "operation cancelled; a dispatched write may already have committed",
328        ));
329    }
330    Ok(())
331}
332
333fn check_text_size(content: &str) -> Result<(), FileIOError> {
334    if content.len() > MAX_FILE_IO_BYTES {
335        return Err(FileIOError::new(
336            FileIOErrorCode::TooLarge,
337            "client text exceeds 256 KiB UTF-8 limit",
338        ));
339    }
340    Ok(())
341}
342
343/// Pure addressing: never call env.absolute_path, exists, stat or canonicalize.
344/// Supports explicit POSIX, drive-absolute and UNC namespaces on any host;
345/// preserves case. Relative paths use cwd's namespace. Home/file URI expansion,
346/// device namespaces and ambiguous Windows drive/root-relative paths are not
347/// supported (they would require host-specific authority).
348pub fn resolve_client_path(cwd: &Path, path: &str) -> Result<String, FileIOError> {
349    fn invalid() -> FileIOError {
350        FileIOError::new(
351            FileIOErrorCode::InvalidPath,
352            "unsupported or ambiguous client path",
353        )
354    }
355    fn absolute(value: &str) -> Result<Option<(String, String, bool)>, FileIOError> {
356        if value.starts_with("\\\\?\\")
357            || value.starts_with("\\\\.\\")
358            || value.starts_with("//?/")
359            || value.starts_with("//./")
360        {
361            return Err(invalid());
362        }
363        if value.starts_with("\\\\") || value.starts_with("//") {
364            let normalized = value.replace('\\', "/");
365            let mut parts = normalized[2..].split('/');
366            let server = parts.next().unwrap_or("");
367            let share = parts.next().unwrap_or("");
368            if server.is_empty()
369                || share.is_empty()
370                || [server, share]
371                    .iter()
372                    .any(|v| *v == "." || *v == ".." || v.contains(':'))
373            {
374                return Err(invalid());
375            }
376            return Ok(Some((
377                format!("//{server}/{share}/"),
378                parts.collect::<Vec<_>>().join("/"),
379                true,
380            )));
381        }
382        if value.as_bytes().get(1) == Some(&b':') {
383            if !value.as_bytes()[0].is_ascii_alphabetic()
384                || !matches!(value.as_bytes().get(2), Some(b'/') | Some(b'\\'))
385            {
386                return Err(invalid());
387            }
388            return Ok(Some((
389                format!("{}/", &value[..2]),
390                value[3..].replace('\\', "/"),
391                true,
392            )));
393        }
394        if value.starts_with('/') {
395            return Ok(Some(("/".into(), value[1..].into(), false)));
396        }
397        if value.starts_with('\\') {
398            return Err(invalid());
399        }
400        Ok(None)
401    }
402    let path = normalize_tool_path(path);
403    if path.is_empty() || path.contains('\0') || path.starts_with('~') || path.contains("://") {
404        return Err(invalid());
405    }
406    let (root, tail, windows) = if let Some(abs) = absolute(&path)? {
407        abs
408    } else {
409        let cwd = cwd.to_str().ok_or_else(invalid)?;
410        let (root, base, windows) = absolute(cwd)?.ok_or_else(invalid)?;
411        (root, format!("{base}/{path}"), windows)
412    };
413    if tail.contains(':') || (!windows && tail.contains('\\')) {
414        return Err(invalid());
415    }
416    let tail = if windows {
417        tail.replace('\\', "/")
418    } else {
419        tail
420    };
421    let mut components = Vec::new();
422    for part in tail.split('/') {
423        match part {
424            "" | "." => {}
425            ".." => {
426                components.pop();
427            }
428            _ => components.push(part),
429        }
430    }
431    Ok(format!("{root}{}", components.join("/")))
432}
433
434#[cfg(test)]
435#[path = "file_io_tests.rs"]
436mod tests;