fastshell 0.3.3

Lightweight Bash + Python runtime SDK for mobile AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

#[derive(Debug)]
pub enum VfsError {
    Io(io::Error),
    PathEscape(PathBuf),
    NotFound(String),
    NotADirectory(String),
    AlreadyExists(String),
}

impl std::fmt::Display for VfsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VfsError::Io(e) => write!(f, "IO error: {}", e),
            VfsError::PathEscape(p) => write!(f, "Path escapes sandbox: {}", p.display()),
            VfsError::NotFound(p) => write!(f, "Not found: {}", p),
            VfsError::NotADirectory(p) => write!(f, "Not a directory: {}", p),
            VfsError::AlreadyExists(p) => write!(f, "Already exists: {}", p),
        }
    }
}

impl std::error::Error for VfsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            VfsError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for VfsError {
    fn from(e: io::Error) -> Self {
        VfsError::Io(e)
    }
}

pub type Result<T> = std::result::Result<T, VfsError>;

#[derive(Debug, Clone)]
pub struct DirEntry {
    pub name: String,
    pub is_dir: bool,
    pub is_symlink: bool,
    pub size: u64,
    pub modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
pub struct Vfs {
    root: PathBuf,
}

impl Vfs {
    pub fn new(root: PathBuf) -> Result<Self> {
        if !root.exists() {
            fs::create_dir_all(&root)?;
        }
        let root = root.canonicalize()?;
        // (c) 2025 xiefujin <490021684@qq.com>
        Ok(Vfs { root })
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// If `p` is a full physical path pointing inside the sandbox, return its
    /// canonical form; otherwise `None`. Handles paths that reach the sandbox
    /// through symlinks (Android: /data/user/0/... vs /data/data/...) by
    /// canonicalizing the longest existing ancestor.
    fn physical_in_sandbox(&self, p: &Path) -> Option<PathBuf> {
        if p.starts_with(&self.root) {
            return Some(p.to_path_buf());
        }
        // Canonicalize the path (or its deepest existing ancestor + remainder)
        // and check again — the root itself is stored canonicalized.
        if let Ok(c) = fs::canonicalize(p) {
            if c.starts_with(&self.root) {
                return Some(c);
            }
            return None;
        }
        let mut ancestor = p.parent()?;
        loop {
            if let Ok(c) = fs::canonicalize(ancestor) {
                let rest = p.strip_prefix(ancestor).ok()?;
                let joined = c.join(rest);
                if joined.starts_with(&self.root) {
                    return Some(joined);
                }
                return None;
            }
            ancestor = ancestor.parent()?;
        }
    }

    pub fn resolve(&self, path: &str, cwd: &str) -> Result<PathBuf> {
        // (c) 2025 xiefujin <490021684@qq.com>
        let candidate = if path.starts_with('/') {
            // A leading '/' is a VFS-internal path relative to the sandbox
            // root — UNLESS the caller passed a full physical path that is
            // already inside the sandbox (e.g. Android passes
            // /data/user/0/<pkg>/files/fastshell/projects/x while the
            // canonical root is /data/data/<pkg>/... because /data/user/0 is
            // a symlink). Joining that onto the root again would double the
            // prefix and never match, so detect it via canonicalization.
            match self.physical_in_sandbox(Path::new(path)) {
                Some(p) => p,
                None => self.root.join(path.trim_start_matches('/')),
            }
        } else {
            let base = if cwd.starts_with('/') {
                self.root.join(cwd.trim_start_matches('/'))
            } else if cwd.is_empty() {
                self.root.clone()
            } else {
                self.root.join(cwd)
            };
            base.join(path)
        };

        let resolved = normalize_path(&candidate);

        if !resolved.starts_with(&self.root) {
            return Err(VfsError::PathEscape(resolved));
        }

        let canonical = match fs::canonicalize(&resolved) {
            Ok(c) => c,
            Err(_) => {
                if let Some(parent) = resolved.parent() {
                    if parent.exists() {
                        match fs::canonicalize(parent) {
                            Ok(canon_parent) => {
                                let fname = resolved.file_name().unwrap_or_default();
                                canon_parent.join(fname)
                            }
                            Err(_) => resolved,
                        }
                    } else {
                        resolved
                    }
                } else {
                    resolved
                }
            }
        };

        if !canonical.starts_with(&self.root) {
            return Err(VfsError::PathEscape(canonical));
        }

        Ok(canonical)
    }

    pub fn to_vpath(&self, abs_path: &Path) -> String {
        match abs_path.strip_prefix(&self.root) {
            Ok(rel) => {
                let s = rel.to_string_lossy();
                if s.is_empty() {
                    "/".to_string()
                } else {
                    format!("/{}", s)
                }
            }
            Err(_) => abs_path.to_string_lossy().to_string(),
        }
    }

    pub fn exists(&self, path: &str, cwd: &str) -> bool {
        self.resolve(path, cwd).map(|p| p.exists()).unwrap_or(false)
    }

    pub fn is_dir(&self, path: &str, cwd: &str) -> bool {
        self.resolve(path, cwd).map(|p| p.is_dir()).unwrap_or(false)
    }

    pub fn is_file(&self, path: &str, cwd: &str) -> bool {
        self.resolve(path, cwd)
            .map(|p| p.is_file())
            .unwrap_or(false)
    }

    pub fn create_dir(&self, path: &str, cwd: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if target.exists() {
            return Err(VfsError::AlreadyExists(self.to_vpath(&target)));
        }
        fs::create_dir(&target)?;
        Ok(())
    }

    pub fn create_dir_all(&self, path: &str, cwd: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        fs::create_dir_all(&target)?;
        Ok(())
    }

    pub fn read_to_string(&self, path: &str, cwd: &str) -> Result<String> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        Ok(fs::read_to_string(&target)?)
    }

    pub fn read(&self, path: &str, cwd: &str) -> Result<Vec<u8>> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        Ok(fs::read(&target)?)
    }

    pub fn write(&self, path: &str, cwd: &str, contents: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if let Some(parent) = target.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::write(&target, contents)?;
        Ok(())
    }

    pub fn write_bytes(&self, path: &str, cwd: &str, contents: &[u8]) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if let Some(parent) = target.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::write(&target, contents)?;
        Ok(())
    }

    pub fn remove_file(&self, path: &str, cwd: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        if target.is_dir() {
            return Err(VfsError::NotADirectory(self.to_vpath(&target)));
        }
        fs::remove_file(&target)?;
        Ok(())
    }

    pub fn remove_dir(&self, path: &str, cwd: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        if !target.is_dir() {
            return Err(VfsError::NotADirectory(self.to_vpath(&target)));
        }
        fs::remove_dir(&target)?;
        Ok(())
    }

    pub fn remove_dir_all(&self, path: &str, cwd: &str) -> Result<()> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        fs::remove_dir_all(&target)?;
        Ok(())
    }

    pub fn list_dir(&self, path: &str, cwd: &str) -> Result<Vec<DirEntry>> {
        let target = self.resolve(path, cwd)?;
        if !target.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&target)));
        }
        if !target.is_dir() {
            return Err(VfsError::NotADirectory(self.to_vpath(&target)));
        }

        let mut entries = Vec::new();
        for entry in fs::read_dir(&target)? {
            let entry = entry?;
            // file_type() does not follow symlinks, so a symlink to a dir is
            // still reported as a symlink (needed for `find -type l`).
            let file_type = entry.file_type()?;
            let metadata = entry.metadata()?;
            entries.push(DirEntry {
                name: entry.file_name().to_string_lossy().to_string(),
                is_dir: metadata.is_dir(),
                is_symlink: file_type.is_symlink(),
                size: metadata.len(),
                modified: metadata.modified().ok(),
            });
        }
        entries.sort_by(|a, b| {
            a.is_dir
                .cmp(&b.is_dir)
                .reverse()
                .then(a.name.to_lowercase().cmp(&b.name.to_lowercase()))
        });
        Ok(entries)
    }

    pub fn copy(&self, from: &str, to: &str, cwd: &str) -> Result<()> {
        let src = self.resolve(from, cwd)?;
        if !src.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&src)));
        }
        let dst = self.resolve(to, cwd)?;

        if src.is_dir() {
            copy_dir_recursive(&src, &dst)?;
        } else {
            if let Some(parent) = dst.parent() {
                if !parent.exists() {
                    fs::create_dir_all(parent)?;
                }
            }
            fs::copy(&src, &dst)?;
        }
        Ok(())
    }

    pub fn rename(&self, from: &str, to: &str, cwd: &str) -> Result<()> {
        let src = self.resolve(from, cwd)?;
        if !src.exists() {
            return Err(VfsError::NotFound(self.to_vpath(&src)));
        }
        let dst = self.resolve(to, cwd)?;
        if let Some(parent) = dst.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::rename(&src, &dst)?;
        Ok(())
    }

    pub fn metadata_len(&self, path: &str, cwd: &str) -> Result<u64> {
        let target = self.resolve(path, cwd)?;
        Ok(target.metadata()?.len())
    }
}

fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        let dst_path = dst.join(entry.file_name());
        if file_type.is_dir() {
            copy_dir_recursive(&entry.path(), &dst_path)?;
        } else {
            fs::copy(entry.path(), &dst_path)?;
        }
    }
    Ok(())
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut components = Vec::new();

    for component in path.components() {
        match component {
            std::path::Component::ParentDir => {
                components.pop();
            }
            std::path::Component::CurDir => {}
            c => components.push(c),
        }
    }

    if components.is_empty() {
        PathBuf::from("/")
    } else {
        components.iter().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEST_COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn setup_vfs() -> Vfs {
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("fastshell_vfs_test_{}_{}", std::process::id(), n));
        let _ = fs::remove_dir_all(&dir);
        Vfs::new(dir).unwrap()
    }

    #[test]
    fn test_new_creates_root() {
        let dir = std::env::temp_dir().join(format!("fastshell_vfs_new_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();
        assert!(vfs.root().exists());
        assert!(vfs.root().is_dir());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_resolve_absolute_path() {
        let vfs = setup_vfs();
        let resolved = vfs.resolve("/home/user", "").unwrap();
        assert!(resolved.starts_with(vfs.root()));
        assert!(resolved.ends_with("home/user"));
    }

    #[test]
    fn test_resolve_relative_path() {
        let vfs = setup_vfs();
        let resolved = vfs.resolve("foo/bar", "/home").unwrap();
        assert!(resolved.ends_with("home/foo/bar"));
    }

    #[test]
    fn test_resolve_full_physical_path_inside_sandbox() {
        // Callers (e.g. Android FilesViewModel) may pass the full physical
        // path of a file inside the sandbox. It must NOT be double-joined
        // onto the root.
        let vfs = setup_vfs();
        vfs.create_dir("/projects", "").unwrap();
        vfs.create_dir("/projects/demo", "").unwrap();
        vfs.write("/projects/demo/a.txt", "", "hi").unwrap();
        let physical = vfs.root().join("projects/demo/a.txt");
        let resolved = vfs.resolve(physical.to_str().unwrap(), "/").unwrap();
        assert_eq!(resolved, physical.canonicalize().unwrap());
        assert_eq!(vfs.read_to_string(physical.to_str().unwrap(), "/").unwrap(), "hi");
    }

    #[test]
    fn test_resolve_physical_path_via_symlinked_prefix() {
        // Android: the app passes /data/user/0/... but the canonical sandbox
        // root is /data/data/... (symlinked). Simulate with a symlinked dir.
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("fs_vfs_link_{}_{}", std::process::id(), n));
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(base.join("real/sandbox")).unwrap();
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(base.join("real"), base.join("alias")).unwrap();
            let vfs = Vfs::new(base.join("real/sandbox")).unwrap();
            vfs.create_dir("/projects", "").unwrap();
            vfs.write("/projects/a.txt", "", "hi").unwrap();
            // Path through the symlinked alias — different textual prefix.
            let via_alias = base.join("alias/sandbox/projects/a.txt");
            assert_eq!(
                vfs.read_to_string(via_alias.to_str().unwrap(), "/").unwrap(),
                "hi"
            );
            // Non-existent file through the alias still resolves (for writes).
            let via_alias_new = base.join("alias/sandbox/projects/new.txt");
            let r = vfs.resolve(via_alias_new.to_str().unwrap(), "/").unwrap();
            assert!(r.starts_with(vfs.root()));
        }
        let _ = fs::remove_dir_all(&base);
    }

    #[test]
    fn test_resolve_prevents_escape() {
        let vfs = setup_vfs();
        let result = vfs.resolve("../../../etc/passwd", "/");
        assert!(result.is_err());
        match result {
            Err(VfsError::PathEscape(_)) => {}
            _ => panic!("Expected PathEscape error"),
        }
    }

    #[test]
    fn test_create_and_list_dir() {
        let vfs = setup_vfs();
        vfs.create_dir("/testdir", "").unwrap();
        assert!(vfs.is_dir("/testdir", ""));
        vfs.write("/testdir/file.txt", "", "hello").unwrap();
        let entries = vfs.list_dir("/testdir", "").unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "file.txt");
    }

    #[test]
    fn test_read_write() {
        let vfs = setup_vfs();
        vfs.write("/hello.txt", "", "Hello, world!").unwrap();
        let content = vfs.read_to_string("/hello.txt", "").unwrap();
        assert_eq!(content, "Hello, world!");
    }

    #[test]
    fn test_remove_file() {
        let vfs = setup_vfs();
        vfs.write("/temp.txt", "", "data").unwrap();
        assert!(vfs.exists("/temp.txt", ""));
        vfs.remove_file("/temp.txt", "").unwrap();
        assert!(!vfs.exists("/temp.txt", ""));
    }

    #[test]
    fn test_copy_file() {
        let vfs = setup_vfs();
        vfs.write("/src.txt", "", "copy me").unwrap();
        vfs.copy("/src.txt", "/dst.txt", "").unwrap();
        assert_eq!(vfs.read_to_string("/dst.txt", "").unwrap(), "copy me");
    }

    #[test]
    fn test_rename() {
        let vfs = setup_vfs();
        vfs.write("/old.txt", "", "rename me").unwrap();
        vfs.rename("/old.txt", "/new.txt", "").unwrap();
        assert!(!vfs.exists("/old.txt", ""));
        assert_eq!(vfs.read_to_string("/new.txt", "").unwrap(), "rename me");
    }

    #[test]
    fn test_to_vpath() {
        let vfs = setup_vfs();
        let abs = vfs.resolve("/foo/bar", "").unwrap();
        assert_eq!(vfs.to_vpath(&abs), "/foo/bar");
        assert_eq!(vfs.to_vpath(vfs.root()), "/");
    }
}